moment.js - 因为我希望它UTC不起作用(moment.js - UTC does no

2019-07-20 16:56发布

测试在节点控制台:

var moment = require('moment');

// create a new Date-Object
var now = new Date(2013, 02, 28, 11, 11, 11);

// create the native timestamp
var native = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes(), now.getSeconds());

// create the timestamp with moment
var withMoment = moment.utc(now).valueOf()
// it doesnt matter if i use moment(now).utc().valueOf() or moment().utc(now).valueOf()

// native: 1364469071000
// withMoment: 1364465471000
native === withMoment // false!?!?! 

// this returns true!!!
withMoment === now.getTime()

为什么心不是本地人相同的时间戳withMoment? 为什么withMoment返回从当前本地时间计算的时间戳? 我怎样才能做到这一点moment.utc()返回同Date.UTC()?

Answer 1:

呼叫moment.utc()你调用同样的方式Date.UTC

var withMoment = moment.utc([now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes(), now.getSeconds()]).valueOf();

我想打电话moment.utc(now)将使其承担now住在当地时区,并会先将其转换为UTC,因此差异。



Answer 2:

你在做什么基本上是这样。

var now    = new Date(2013, 02, 28, 11, 11, 11);
var native = Date.UTC(2013, 02, 28, 11, 11, 11);

console.log(now === utc); // false
console.log(now - utc); // your offset from GMT in milliseconds

因为now是在当前时区构建和native在UTC构建,他们会被你的偏移不同。 11:00 PST!= 11:00 GMT。



文章来源: moment.js - UTC does not work as i expect it