[英]Wrong hour difference between 2 timestamps (hh:mm:ss)
Using moment.js, I want to get the time difference between 2 timestamps. 使用moment.js,我想获得两个时间戳之间的时差。
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? 为什么我会相差1小时? 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
输出是:
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. 您在这里遇到的问题是,将
nextTime.diff()
放入矩构造函数中时,您实际上将毫秒馈入了moment()
,并且试图将其解释为时间戳,这就是为什么无法获得预期的原因结果。
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
. 编辑:我已经注意到您使用
HH:mm:SS
作为格式,但是您应该改为使用HH:mm:ss
。 'SS' Will give you fractional values for the seconds between 0 and 999, which is not what you want here. “ SS”将为您提供介于0到999之间的秒的分数值,这不是您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.