Get time difference between datetimes

date, difference, javascript, momentjs, time

Solution

This approach will work ONLY when the total duration is less than 24 hours:

var now  = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";

moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")

// outputs: "00:39:30"

If you have 24 hours or more, the hours will reset to zero with the above approach, so it is not ideal.

If you want to get a valid response for durations of 24 hours or greater, then you'll have to do something like this instead:

var now  = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";

var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");

// outputs: "48:39:30"

Note that I'm using the utc time as a shortcut. You could pull out `d.minutes()` and `d.seconds()` separately, but you would also have to zeropad them.

This is necessary because the ability to format a `duration` objection is not currently in moment.js. It has been requested here. However, there is a third-party plugin called moment-duration-format that is specifically for this purpose:

var now  = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";

var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = d.format("hh:mm:ss");

// outputs: "48:39:30"

Problem

How to get the difference between 2 times? Example: ``` var now = "04/09/2013 15:00:00"; var then = "04/09/2013 14:20:30"; //expected result: "00:39:30" ``` I tried: ``` var now = moment("04/09/2013 15:00:00"); var then = moment("04/09/2013 14:20:30"); console.log(moment(moment.duration(now.diff(then))).format("hh:mm:ss")) //outputs 10:39:30 ``` What is "10" there? I am at utc-0300. Result of `moment.duration(now.diff(then))` is a duration with correct internal values: ``` days: 0 hours: 0 milliseconds: 0 minutes: 39 months: 0 seconds: 30 years: 0 ``` How to convert a momentjs duration to a time interval? I can use: ``` duration.get("hours") +":"+ duration.get("minutes") +:+ duration.get("seconds") ``` But is there something more elegant? `now` is: ``` Tue Apr 09 2013 15:00:00 GMT-0300 (E. South America Standard Time)…} ``` And `moment(moment.duration(now.diff(then)))` is: ``` Wed Dec 31 1969 22:39:30 GMT-0200 (E. South America Daylight Time)…} ``` The value is -0200 because for 31/12/1969 daylight saving time was used.

Original source

Related problems