Getting Hours Difference between Two Dates in Moment.js
When comparing two dates in Moment.js, it's easy to determine the difference in minutes and seconds. However, when the time span exceeds an hour, displaying the duration in hours may be desirable.
Determining the Duration
The first attempt used moment(end.diff(startTime)).format("m[m] s[s]") to calculate the difference, which worked well for minutes and seconds. The next step was to use moment.duration(end.diff(startTime)) to obtain the duration. However, retrieving the hours using duration.hours() did not provide the correct number of hours between the dates.
Solution
The correct method for obtaining the difference in hours is duration.asHours(). The following code demonstrates the proper way to determine the duration in hours:
<code class="javascript">var duration = moment.duration(end.diff(startTime)); var hours = duration.asHours();</code>
By using asHours(), you can accurately display the time difference between two dates, including both hours and minutes if necessary.
The above is the detailed content of How to Calculate the Hours Difference Between Two Dates in Moment.js?. For more information, please follow other related articles on the PHP Chinese website!