2个时间戳之间的小时差错(hh:mm:ss) [英] Wrong hour difference between 2 timestamps (hh:mm:ss)

查看:174
本文介绍了2个时间戳之间的小时差错(hh:mm:ss)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用moment.js,我想获取两个时间戳之间的时差.

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

执行以下操作

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");

我得到这个结果:

01:00:03

为什么我会有1个小时的时差?秒和分钟似乎效果很好.

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');

输出为:1:0:3

推荐答案

您遇到的问题是,将nextTime.diff()放在一刹那的构造函数中时,您实际上将毫秒数传给了moment(),并且它试图解释它作为时间戳记,这就是为什么您得不到预期结果的原因.

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");

应该让你更快乐!

我注意到您使用HH:mm:SS作为格式,但是您应该改用HH:mm:ss. "SS"将为您提供介于0到999之间的秒的分数值,这不是您想要的.

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.

这篇关于2个时间戳之间的小时差错(hh:mm:ss)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆