MomentJS diff 增加了一个小时

MomentJS diff is adding an hour

我正在做这个

const currentCETTime = moment.tz('2020-03-18 15:58:38', 'Europe/Madrid');
const limitCETTime = moment.tz('2020-03-18 18:00:00', 'Europe/Madrid');
console.log('current',currentCETTime.format('HH:mm:ss'));
console.log('limit', limitCETTime.format('HH:mm:ss'));
const seconds = Math.abs(limitCETTime.diff(currentCETTime) / 1000);
console.log('hours', (seconds / 60) / 60);
const rem = moment(seconds * 1000);
console.log('diff', moment(rem).tz('Europe/Madrid').format('HH:mm'));
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-10-year-range.min.js"></script>

我得到了一个错误的区别:

我应该得到 2:01 小时的差异而不是 03:01

如果您打印出 rem 的整个日期,就会看到问题:

const currentCETTime = moment.tz('2020-03-18 15:58:38', 'Europe/Madrid');
const limitCETTime = moment.tz('2020-03-18 18:00:00', 'Europe/Madrid');
console.log('current',currentCETTime.format('HH:mm:ss'));
console.log('limit', limitCETTime.format('HH:mm:ss'));
const seconds = Math.abs(limitCETTime.diff(currentCETTime) / 1000);
console.log('hours', (seconds / 60) / 60);
const rem = moment(seconds * 1000);
console.log('diff', moment(rem).tz('Europe/Madrid').toString());
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-10-year-range.min.js"></script>

对毫秒值调用 moment 会产生新的纪元日期。

以秒为单位的差异是正确的。如果你想要小时差,你可以用小时参数调用 diff 。请注意,力矩向下舍入到最接近的整数值。

const currentCETTime = moment.tz('2020-03-18 15:58:38', 'Europe/Madrid');
const limitCETTime = moment.tz('2020-03-18 18:00:00', 'Europe/Madrid');
console.log('current',currentCETTime.format('HH:mm:ss'));
console.log('limit', limitCETTime.format('HH:mm:ss'));
const hours = limitCETTime.diff(currentCETTime, 'hours');
console.log('hours', hours);
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-10-year-range.min.js"></script>

moment(milliseconds) 以及 tz 变体,将毫秒添加到日期 1970-01-01 01:00:00。这是此方法的 unix timestamp parser 行为。这就是为什么格式化后 returns 看起来 像一个额外的小时,但那是因为它从 1 小时开始而不是 0 小时。您可以通过传入来检查此行为0 表示总毫秒数,您会看到 returns 小时值为 1。

如果只需要小时和秒,则无需使用时区。您可以调用 utc 然后格式化。检查下面的代码。

const currentCETTime = moment.tz('2020-03-18 15:58:38', 'Europe/Madrid');
const limitCETTime = moment.tz('2020-03-18 18:00:00', 'Europe/Madrid');
console.log('current',currentCETTime.format('HH:mm:ss'));
console.log('limit', limitCETTime.format('HH:mm:ss'));
const seconds = Math.abs(limitCETTime.diff(currentCETTime) / 1000);
console.log('hours', (seconds / 60) / 60);
const rem = moment(seconds * 1000);
console.log('diff', moment(rem).utc().format('HH:mm'));
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-10-year-range.min.js"></script>