Determining the time difference between two specific datetimes is a common requirement in many applications. This article provides a comprehensive guide to obtaining a precise time interval using moment.js, addressing potential issues and offering alternative approaches.
Given two datetimes represented as strings, the goal is to calculate the time difference and display it in an HH:MM:SS format. For instance:
var now = "04/09/2013 15:00:00"; var then = "04/09/2013 14:20:30"; //expected result: "00:39:30"
Using moment.js's diff function, you might try the following:
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, this approach incorrectly adds 10 hours, despite the internal values of the duration being accurate.
To resolve this issue, there are two options:
Option 1 (for durations less than 24 hours):
moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
This approach converts the time difference to UTC, eliminating any daylight saving time inconsistencies.
Option 2 (for durations of 24 hours or greater):
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");
This approach calculates the time difference in milliseconds, converts it to a duration object, and extracts the hours, minutes, and seconds separately.
For those seeking a convenient solution for formatting duration objects, a third-party plugin called moment-duration-format can be employed:
var s = d.format("hh:mm:ss");
The above is the detailed content of How to Accurately Calculate the Time Difference Between Two Datetimes using moment.js?. For more information, please follow other related articles on the PHP Chinese website!