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

Member

by shyann , in category: Javascript , a year ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , a year 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.

Related Threads:

How to find time difference in seconds using moment.js?
How to check if the current time is between two times using moment.js?
How to get difference between two datetime of moment.js?
How to find days left in a quarter using moment.js?
How to create two datepicker using vue.js and moment.js?
How to check if two dates are more than 7 days apart using moment.js?