Home > Web Front-end > JS Tutorial > How to Calculate the Hour Difference Between Two Dates Using Moment.js?

How to Calculate the Hour Difference Between Two Dates Using Moment.js?

Linda Hamilton
Release: 2024-10-27 05:16:29
Original
697 people have browsed it

How to Calculate the Hour Difference Between Two Dates Using Moment.js?

Getting Hour Difference Between Two Dates in Moment.js

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]")
Copy after login

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.

Getting Hours from a Moment.js 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();
Copy after login

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!

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