moment.js – UTC不工作,因为我期望它

在节点控制台中testing:

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返回从当前本地时间计算的时间戳? 我怎么能实现这个moment.utc()返回相同的Date.UTC()?

以与调用Date.UTC相同的方式调用moment.utc()

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

我认为调用moment.utc(now)会让它now生活在当地的时区,它会首先将它转换为UTC,从而有所不同。

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

 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是在当前时区中构build的,并且native是以UTCforms构build的,所以它们将因您的偏移而有所不同。 上午11点!=上午11点。