How to get difference between two datetime of moment.js?

by ryan.murray , in category: Javascript , 8 months ago

How to get difference between two datetime of moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lottie , 8 months ago

@ryan.murray 

To get the difference between two datetime using Moment.js, you can use the diff() method. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const moment = require('moment');

// Datetime 1
const datetime1 = moment('2022-01-01 12:00:00');

// Datetime 2
const datetime2 = moment('2022-01-02 12:00:00');

// Get the difference in milliseconds
const diffMilliseconds = datetime2.diff(datetime1);

// Get the difference in seconds
const diffSeconds = datetime2.diff(datetime1, 'seconds');

// Get the difference in minutes
const diffMinutes = datetime2.diff(datetime1, 'minutes');

// Get the difference in hours
const diffHours = datetime2.diff(datetime1, 'hours');

// Get the difference in days
const diffDays = datetime2.diff(datetime1, 'days');

console.log('Difference in milliseconds:', diffMilliseconds);
console.log('Difference in seconds:', diffSeconds);
console.log('Difference in minutes:', diffMinutes);
console.log('Difference in hours:', diffHours);
console.log('Difference in days:', diffDays);


This code snippet demonstrates how to get the difference between two datetime objects using Moment.js and different units of time such as milliseconds, seconds, minutes, hours, and days. You can adjust the date and time values in datetime1 and datetime2 to suit your requirements.