简体   繁体   中英

Wrong hour difference between 2 timestamps (hh:mm:ss)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM