Determining the time difference between two instances is a fundamental task in various programming scenarios. This article delves into how to calculate this difference effectively using specific examples.
Consider the following requirement:
var now = "04/09/2013 15:00:00"; var then = "04/09/2013 14:20:30"; //expected result: "00:39:30"
Initially, you might try the following approach:
var now = moment("04/09/2013 15:00:00"); var then = moment("04/09/2013 14:20:30"); console.log(moment(moment.duration(now.diff(then))).format("hh:mm:ss")) // outputs 10:39:30
However, in this example, the unexpected value "10" appears in the result. This is because moment.duration converts the difference between now and then into an object containing internal values like milliseconds. To convert this duration into a time interval, you can use:
duration.get("hours") + ":" + duration.get("minutes") + ":" + duration.get("seconds")
This would produce the desired result: "00:39:30."
Note: This approach is suitable only for durations less than 24 hours. For larger durations, you need a different approach.
var now = "04/09/2013 15:00:00"; var then = "02/09/2013 14:20:30"; var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss")); var d = moment.duration(ms); var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss"); // outputs: "48:39:30"
In this case, we calculate the time difference as milliseconds, convert it to a duration object d, and then format it using UTC time. This gives us the correct result, "48:39:30."
Alternatively, you can use the moment-duration-format plugin to simplify the formatting process.
The above is the detailed content of How to Accurately Calculate the Time Difference Between Two Datetimes in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!