How to find difference of two times using moment.js?

Member

by shyann , in category: Javascript , 9 months ago

How to find difference of two times using moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 9 months ago

@shyann 

To find the difference between two times using Moment.js, you can create Moment objects representing the two times and then use the diff() method.


Here's an example code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const moment = require('moment');

// Create Moment objects for the two times
const time1 = moment('2021-01-01 12:00:00', 'YYYY-MM-DD HH:mm:ss');
const time2 = moment('2021-01-01 13:30:00', 'YYYY-MM-DD HH:mm:ss');

// Find the difference between the two times
const difference = time2.diff(time1);

// Convert the difference to hours
const differenceInHours = moment.duration(difference).asHours();

console.log(differenceInHours);


In this code snippet, we first create Moment objects time1 and time2 representing the two times. We then use the diff() method to find the difference between time2 and time1. Finally, we convert the difference to hours using the asHours() method on a duration object.


You can adjust the format of the times and the unit of measurement for the difference as needed.