Categories
JavaScript Answers

How to Get the Hours Difference Between Two Dates with Moment.js?

Spread the love

Moment.js is a popular JavaScript date and time manipulation library that we can use to calculate various things with date and time.

In this library, we’ll look at how to get the hours difference between 2 dates with moment.js

The moment.duration Method

The moment.duration lets us calculate the duration between 2 dates.

We can combine it with the diff method to calculate the hours difference between 2 dates.

For instance, we can write:

const startTime = moment('2021-01-01')  
const end = moment('2021-02-01')  
const duration = moment.duration(end.diff(startTime));  
const hours = duration.asHours();  
console.log(hours)

We call end.diff(startTime) to calculate the difference between end and startTime .

Then we call moment.duration to get the moment duration.

And finally, we call asHours to get the duration as hours.

Therefore, hours is 744 hours.

Moment.js fromNow and from Methods

We can use the fromNow method to get a human readable string of the difference between a date and now.

For instance, we can write:

const diff = moment('2021-01-01').fromNow()   
console.log(diff)

And we get something like ‘2 months ago’ .

We can use moment.js from method to get a human-readable string between the difference between 2 dates.

For instance, we can write:

const a = moment('2021-01-01');  
const b = moment('2021-02-01');  
const diff = a.from(b);  
console.log(diff)

And we get 'a month ago’ as a value of diff since February 1, 2021 is 1 month ahead of January 1, 2021.

Moment.js diff Method with Unit as the Second Argument

We can pass in a second argument to the diff method to return the difference in the unit specified.

For instance, we can write:

const a = moment('2021-01-01');  
const b = moment('2021-02-01');  
const diff = a.diff(b, 'hours');  
console.log(diff)

We get the difference between date-time a and b .

And a is behind b by 1 month, so we get -744 as the result of diff .

The 2nd argument is 'hours' so the result is in hours.

Conclusion

We can get the difference between 2 dates with the units we specified with various moment.js methods.

Also, we can get human readable durations with moment.js.

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 *