javascript moment.js - UTC 不像我期望的那样工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15133326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:37:39  来源:igfitidea点击:

moment.js - UTC does not work as i expect it

javascriptnode.jsutcmomentjs

提问by hereandnow78

testing in the node console:

在节点控制台中测试:

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

why isnt native the same timestamp as withMoment? why does withMoment return the timestamp calculated from the current local-time? how can i achieve that moment.utc() returns the same as Date.UTC()?

为什么本地时间戳与 withMoment 不同?为什么 withMoment 返回从当前本地时间计算的时间戳?我怎样才能实现那个 moment.utc() 返回与 Date.UTC() 相同的返回值?

回答by robertklep

Call moment.utc()the same way you're calling Date.UTC:

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

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

I think calling moment.utc(now)will make it assume nowlives in the local timezone, and it will convert it to UTC first, hence the difference.

我认为调用moment.utc(now)会使它假设now生活在本地时区,它会首先将其转换为 UTC,因此有所不同。

回答by timrwood

What you are doing is essentially this.

你所做的基本上就是这个。

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

Because nowis constructed in the current timezone and nativeis constructed in UTC, they will differ by your offset. 11 AM PST != 11 AM GMT.

因为now是在当前时区native中构建的,并且是在 UTC 中构建的,所以它们会因您的偏移量而有所不同。太平洋标准时间上午 11 点!= 格林威治标准时间上午 11 点。