How to find time difference in seconds using moment.js?

Member

by lottie , in category: Javascript , a year ago

How to find time difference in seconds using moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , a year ago

@lottie 

To find the time difference in seconds between two moments using moment.js, you can use the moment.duration() method. First, you need to create moment objects for the two timestamps you want to compare. Then, you can use the duration() method to calculate the duration between the two moments. Finally, you can use the asSeconds() method to get the time difference in seconds.


Here's an example code snippet to demonstrate how to find the time difference in seconds using moment.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Import moment.js library
const moment = require('moment');

// Create moment objects for the two timestamps
const start = moment('2022-01-01 12:00:00', 'YYYY-MM-DD HH:mm:ss');
const end = moment('2022-01-01 12:30:00', 'YYYY-MM-DD HH:mm:ss');

// Calculate the duration between the two moments
const duration = moment.duration(end.diff(start));

// Get the time difference in seconds
const timeDiffInSeconds = duration.asSeconds();

console.log(timeDiffInSeconds); // Output: 1800 seconds


In this example, we create moment objects for two timestamps '2022-01-01 12:00:00' and '2022-01-01 12:30:00' and calculate the duration between them. The time difference in seconds is then calculated and displayed in the console.

Related Threads:

How to find difference of two times using moment.js?
How to get time difference in moment.js?
How to convert mm:ss to seconds using moment.js?
How to subtract time using moment.js?
How to find days left in a quarter using moment.js?
How to get time format to hh:mm using moment.js?