When working with dates in JavaScript, the Moment.js library offers a convenient way to handle date manipulation. For instance, getting the time difference between two dates is straightforward:
moment(end.diff(startTime)).format("m[m] s[s]")
However, this may not be sufficient if you want to display hours when applicable. To address this, you need to extract the hours from the duration.
Initially, you tried to retrieve the hours using duration.hours(). However, this method returns the current hour, not the difference between two dates.
The correct approach is to use the duration.asHours() method, as seen in the docs. Here's how:
var duration = moment.duration(end.diff(startTime)); var hours = duration.asHours();
Now, hours will hold the difference in hours between the two dates. You can use it to format the output as desired.
The above is the detailed content of How to Calculate the Hour Difference Between Two Dates Using Moment.js?. For more information, please follow other related articles on the PHP Chinese website!