Get hours difference between two dates in Moment Js

Get hours difference between two dates in Moment Js

I’m able to get the difference between two dates using MomentJs as follows:
moment(end.diff(startTime)).format(“m[m] s[s]”)

However, I also want to display the hour when applicable (only when >= 60 minutes have passed).
However, when I try to retrieve the duration hours using the following:
var duration = moment.duration(end.diff(startTime));
var hours = duration.hours();

it is returning the current hour and not the number of hours between the two dates.
How do I get the difference in hours between two Moments?


Solution 1:

You were close. You just need to use the duration.asHours() method (see the docs).

var duration = moment.duration(end.diff(startTime));
var hours = duration.asHours();

Solution 2:

Following code block shows how to calculate the difference in number of days between two dates using MomentJS.

var now = moment(new Date()); //todays date
var end = moment("2015-12-1"); // another date
var duration = moment.duration(now.diff(end));
var days = duration.asDays();

Solution 3:

Or you can do simply:

var a = moment('2016-06-06T21:03:55');//now
var b = moment('2016-05-06T20:03:55');

console.log(a.diff(b, 'minutes')) // 44700
console.log(a.diff(b, 'hours')) // 745
console.log(a.diff(b, 'days')) // 31
console.log(a.diff(b, 'weeks')) // 4

docs: here

Solution 4:

All you need to do is pass in hours as the second parameter to moments diff function.

var a = moment([21,30,00], "HH:mm:ss")
var b = moment([09,30,00], "HH:mm:ss")
a.diff(b, 'hours') // 12



const dateFormat = "YYYY-MM-DD HH:mm:ss";
// Get your start and end date/times
const rightNow = moment().format(dateFormat);
const thisTimeYesterday = moment().subtract(1, 'days').format(dateFormat);
// pass in hours as the second parameter to the diff function
const differenceInHours = moment(rightNow).diff(thisTimeYesterday, 'hours');

console.log(`${differenceInHours} hours have passed since this time yesterday`);

Solution 5:

There is a great moment method called fromNow() that will return the time from a specific time in nice human readable form, like this:

moment('2019-04-30T07:30:53.000Z').fromNow() // an hour ago || a day ago || 10 days ago

Or if you want that between two specific dates you can use:

var a = moment([2007, 0, 28]);
var b = moment([2007, 0, 29]);
a.from(b); // "a day ago"

Taken from the Docs:

Solution 6:

I know this is old, but here is a one liner solution:

const hourDiff = start.diff(end, "hours");

Where start and end are moment objects.