首页 > 解决方案 > MomentJS,UTC时间戳,是问题还是错误?,很少查询

问题描述

moment().valueOf()使用and时我没有发现时间戳有任何差异moment.utc().valueOff(),我的 timezoneOffset 为 +5。

console.log(moment().valueOf())
console.log(moment().valueOf())
console.log(moment().utc().valueOf(),  moment().valueOf(), '=', moment().utc().valueOf() -  moment().valueOf())

> 1564388008550
> 1564388008551
> 1564388008551 1564388008551 "=" 0

预计必须有5小时的差异?或者可能是我们的观点是错误的通常时间戳总是在UTC?这就是为什么这两种方法都提供相同的时间戳!我们只能在格式化的日期字符串中找到区别?

标签: javascriptmomentjs

解决方案


moment.js 实例是原生 Date 对象的包装器,它使用始终为 UTC 的时间值。不同的时区可用于显示日期(时间戳),但时间值不会改变。

默认情况下,moment 的输出是本地的。utc方法将时刻实例设置为 UTC 模式,因此默认情况下输出显示为 UTC。它不会更改时刻实例包裹的 Date 中心的 UTC 时间值,例如

let m = moment();

console.log('time value: ' + m.valueOf());  // time value of instance
console.log('local timestamp: ' + m.format()); // timestamp in host timezone

m.utc();  // set to UTC mode, so default is UTC

console.log('time value: ' + m.valueOf()); // time value unchanged
console.log('UTC timestamp: ' + m.format()); // Equivalent timestamp with no timezone (UTC)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>


推荐阅读