How to get time difference in moment.js?

Member

by jerad , in category: Javascript , a year ago

How to get time difference in moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , a year ago

@jerad 

You can get the time difference between two moments in Moment.js by using the diff() method. This method allows you to specify what unit of time you want the difference to be calculated in (e.g., days, hours, minutes, etc.).


Here is an example of how to get the time difference between two moments in Moment.js:

1
2
3
4
5
6
7
8
var firstMoment = moment('2021-09-17 08:00:00');
var secondMoment = moment('2021-09-18 12:00:00');

var diffInHours = secondMoment.diff(firstMoment, 'hours');
var diffInMinutes = secondMoment.diff(firstMoment, 'minutes');

console.log(diffInHours); // Output: 28
console.log(diffInMinutes); // Output: 1680


In the above example, we first create two moments representing different dates and times. We then use the diff() method to calculate the time difference between the two moments in hours and minutes. Finally, we log the results to the console.

Related Threads:

How to find time difference in seconds using moment.js?
How to get difference between two datetime of moment.js?
How to get difference between n dates in moment.js?
How to get time format to hh:mm using moment.js?
How to check time difference in mysql query?
How to take date time difference by milliseconds in oracle?