Home > Web Front-end > JS Tutorial > body text

How to Calculate the Hours Difference Between Two Dates in Moment.js?

Mary-Kate Olsen
Release: 2024-10-27 14:42:02
Original
653 people have browsed it

How to Calculate the Hours Difference Between Two Dates in Moment.js?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template