Categories
JavaScript Answers

How to Get the Hour Difference Between Two Times with Moment.js and JavaScript?

Spread the love

Sometimes, we want to get the hour difference between two times with moment.js and JavaScript.

In this article, we’ll look at how to get the hour difference between two times with moment.js and JavaScript.

Get the Hour Difference Between Two Times with Moment.js and JavaScript

To get the hour difference between two times with moment.js and JavaScript, we can use the duration, diff, asHours and asMinutes methods.

For instance, we can write:

const startTime = moment("12:26:59 am", "HH:mm:ss a");
const endTime = moment("06:12:07 pm", "HH:mm:ss a");
const duration = moment.duration(endTime.diff(startTime));
const hours = parseInt(duration.asHours());
const minutes = parseInt(duration.asMinutes()) % 60;

console.log(hours, minutes);

We parse 2 times into moment objects with the moment function.

We pass in the format of the time as the 2nd argument.

Then we call moment.duration with the difference between endTime and startTime that we get with the diff method.

Next, we get the hours part of the duration with the asHours method.

And we get the minutes part of the duration with the asMinutes method and get the remainder of that divided by 60.

Therefore, we get 17 45 from the console log.

Conclusion

To get the hour difference between two times with moment.js and JavaScript, we can use the duration, diff, asHours and asMinutes methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *