Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 889
Dani Avatar asked Aug 06 '14 00:08

Dani


People also ask

How do you find the time difference between two dates in a moment?

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 between two time in Javascript?

Calculate the time difference in hours and minutes with: split(":"); var time1 = splitted1[0]+splitted1[1]; var time2 = splitted2[0]+splitted2[1]; var hours; var minutes; if (time1 < time2) { var diff = getTimeDiff('{time2}', '{time1}', 'm'); hours = Math.

What is Moment () hour ()?

The moment(). hour() Method is used to get the hours from the current time or to set the hours. Syntax: moment().hour(); or. moment().


2 Answers

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(); 
like image 161
GregL Avatar answered Oct 02 '22 21:10

GregL


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(); console.log(days) 
like image 31
selftaught91 Avatar answered Oct 02 '22 20:10

selftaught91