Node.js calculate datetime difference in hours minutes and seconds moment.js

Node.js calculate datetime difference in hours minutes and seconds moment.js

In this Node.js tutorial, I will tell you how to calculate datetime difference in days, hours, minutes and seconds using moment.js with example.

You can use moment in browser and in Node.js to calculate date difference.

Install Moment in Node.js

Run the npm command to install dependencies of Moment.js

npm install moment --save

Now require this package :

var moment = require("moment");
Calculate datetime difference in days
  1. function calculateDays(startDate,endDate)
  2. {
  3. var start_date = moment(startDate, 'YYYY-MM-DD HH:mm:ss');
  4. var end_date = moment(endDate, 'YYYY-MM-DD HH:mm:ss');
  5. var duration = moment.duration(end_date.diff(start_date));
  6. var days = duration.asDays();
  7. return days;
  8. }

Above function will return the number of days between two given dates.

Moment have various function that return the number of weeks (0 - 4), number of hours (0 - 23), number of minutes (0 - 59), number of months (0 - 11) etc.

moment.duration().asDays(); // get the length of the duration in days
moment.duration().asHours(); // get the length of the duration in hours
moment.duration().asWeeks(); // get the length of the duration in weeks
moment.duration().asMonths(); // get the length of the duration in months
moment.duration().asYears(); // get the length of the duration in years

If you have any subscription and you want to know the remaining days from current day :

moment(subs_ends_at).diff(new Date(),'days');

subs_ends_at variable hold the expiry date.

A complete list of moment functions are given below :

S.No Moment Function Result
1 moment() 2017-08-31T06:53:16.470Z
2 moment().unix() 1504162446
3 moment().format('MMMM Do YYYY, h:mm:ss a') August 31st 2017, 11:57:57 am
4 moment().format('D') 31
5 moment().format('dddd') Thursday
6 moment().format("MMM Do YY") Aug 31st 17
7 moment().format() 2017-08-31T12:01:51+05:30
8 moment("20131231", "YYYYMMDD").fromNow() 4 years ago
9 moment("20200722", "YYYYMMDD").fromNow() in 3 years
10 moment().startOf('day').fromNow() 12 hours ago
11 moment().endOf('day').fromNow() in 12 hours
12 moment().startOf('hour').fromNow() 16 minutes ago
13 moment().subtract(10, 'days').calendar() 08/21/2017
14 moment().calendar() Today at 12:16 PM
15 moment().add(1, 'days').calendar() Tomorrow at 12:16 PM
16 moment.locale() en
17 moment().format('LT') 12:17 PM
18 moment().format('LTS') 12:17:52 PM
19 moment().format('L') 08/31/2017
20 moment().format('l') 8/31/2017
21 moment().format('LL') August 31, 2017
22 moment().format('ll') Aug 31, 2017
23 moment().format('LLL') August 31, 2017 12:19 PM
24 moment().format('lll') Aug 31, 2017 12:20 PM
25 moment().format('LLLL') Thursday, August 31, 2017 12:20 PM
26 moment().format('llll') Thu, Aug 31, 2017 12:20 PM

Phone: (+91) 8800417876
Noida, 201301