2

Using moment.js, I want to get the time difference between 2 timestamps.

Doing the following,

var prevTime = moment('23:01:53', "HH:mm:SS");
var nextTime = moment('23:01:56', "HH:mm:SS");

var duration = moment(nextTime.diff(prevTime)).format("HH:mm:SS");

I get this result :

01:00:03

Why do I have a 1 hour difference? seconds and minutes seem to work well.

After doing that, I tried the following :

function time_diff(t1, t2) {
    var parts = t1.split(':');
    var d1 = new Date(0, 0, 0, parts[0], parts[1], parts[2]);
    parts = t2.split(':');
    var d2 = new Date(new Date(0, 0, 0, parts[0], parts[1], parts[2]) - d1);
    return (d2.getHours() + ':' + d2.getMinutes() + ':' + d2.getSeconds());
}

var diff = time_diff('23:01:53','23:01:56');

output is : 1:0:3

krakig
  • 1,515
  • 1
  • 19
  • 33
  • This may be due to an GMT offset : you might try UTC. Just a note : [`SS` is used for fractional seconds](http://momentjs.com/docs/#/parsing/string-format/) – Maen May 25 '16 at 08:38
  • Yes, I misread the docs. Corrected it, thanks! – krakig May 25 '16 at 08:42

1 Answers1

0

The problem you are having here is that when putting the nextTime.diff() in a moment constructor, you are effectively feeding milliseconds to moment() and it tries to interpret it as a timestamp, which is why you don't get the expected result.

There is no "nice way" of getting the result you want apart from getting a time and manually reconstructing what you are looking for :

var dur = moment.duration(nextTime.diff(prevTime)); 
var formattedDuration = dur.get("hours") +":"+ dur.get("minutes") +":"+ dur.get("seconds");

And a more elegant version that will give you zero padding in the output :

var difference = nextTime.diff(prevTime);
var dur = moment.duration(difference);
var zeroPaddedDuration = Math.floor(dur.asHours()) + moment.utc(difference).format(":mm:ss");

Should make you happier!

EDIT : I have noticed you use HH:mm:SS for your format, but you should instead use HH:mm:ss. 'SS' Will give you fractional values for the seconds between 0 and 999, which is not what you want here.

zoubida13
  • 1,738
  • 12
  • 20