Dani Dani - 6 months ago 122
Javascript Question

Get hours difference between two dates in Moment Js

I'm able to get the different between two dates using MomentJs as follow:

moment(end.diff(startTime)).format("m[m] s[s]")


However, i also want to display the hour when applicable (after 60 minutes are passed only).

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 how many hours different between the two dates.

Any thoughts on how to get the hour different between two dates?

Thanks.

Answer

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();
Comments