How to get time difference in moment.js?

Member

by jerad , in category: Javascript , 7 months ago

How to get time difference in moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 7 months 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.