gpt4 book ai didi

javascript - moment.js diff 显示错误结果

转载 作者:行者123 更新时间:2023-12-04 01:10:00 25 4
gpt4 key购买 nike

我正在使用 momentjs 编写一个小脚本,它显示了我在特定时间之前有多少小时和分钟(单独)。但由于某种原因,结果是错误的。

到目前为止我的代码是这样的:

var TimeA = moment('08:00:00', 'HH:mm:ss');
var TimeB = moment('16:00:00', 'HH:mm:ss');

var DiffAB = moment(TimeA.diff(TimeB)).format('HH:mm:ss');

var DiffHours = moment(DiffAB, 'HH:mm:ss').format('H');
var DiffMinutes = moment(DiffAB, 'HH:mm:ss').format('mm');

console.log('TimeA: ' + moment(TimeA).format('HH:mm:ss'));
console.log('TimeB: ' + moment(TimeB).format('HH:mm:ss'));

console.log('Difference A-B: ' + DiffAB);

console.log('Diff Hours: ' + DiffHours);
console.log('Diff Minutes: ' + DiffMinutes);

这就是输出:

TimeA: 08:00:00
TimeB: 16:00:00
Difference A-B: 17:00:00
Diff Hours: 17
Diff Minutes: 00

A - B 的差应该是 8 但它显示为 17

最佳答案

根据 momentjs 文档

If the moment is earlier than the moment you are passing to moment.fn.diff, the return value will be negative.

将它翻译成你的例子:

If TimeA is earlier than TimeB passed to moment.diff then the value will be negative

并且由于它以毫秒形式返回,-28800000 是这样的指令:从午夜开始计算该毫秒数,这会为您提供不同的时间

所以你应该做的是

var DiffAB = moment(TimeB.diff(TimeA)).utcOffset(0).format('HH:mm:ss');

差异文档 https://momentjs.com/docs/#/displaying/difference/

来自文档的例子

An easy way to think of this is by replacing .diff( with a minus operator.

          // a < b
a.diff(b) // a - b < 0
b.diff(a) // b - a > 0

关于javascript - moment.js diff 显示错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43283600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com