Home  >  Article  >  Web Front-end  >  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
Linda HamiltonOriginal
2024-10-27 05:16:29606browse

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]")

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();

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!

Statement:
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