2013-02-28 92 views
7

测试UTC不起作用:moment.js - 因为我希望它在节点控制台

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()?

回答

11

呼叫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,因此。

+1

已经尝试过了,看到它有效。这是我唯一的选择吗?认为moment.js节省了我的代码和时间;-( – hereandnow78 2013-02-28 12:35:39

+0

你可以将'native'传递给'moment.utc()'而不是'now',那也可以。 – robertklep 2013-02-28 12:45:04

+0

是的,仍然不是我想要的,但是ty ;-) – hereandnow78 2013-02-28 13:32:18

3

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

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点!=上午11点。

相关问题