【问题标题】:moment.js - UTC does not work as i expect itmoment.js - UTC 无法按我的预期工作
【发布时间】:2013-02-14 12:19:30
【问题描述】:

在节点控制台中测试:

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() 相同的结果?

【问题讨论】:

    标签: javascript node.js utc momentjs


    【解决方案1】:

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

    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 点。

    【讨论】:

      【解决方案2】:

      拨打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,因此会有所不同。

      【讨论】:

      • 已经尝试过了,并且发现它有效。这是我唯一的选择吗?认为 moment.js 为我节省了代码和时间;-(
      • 您可以将native 传递给moment.utc() 而不是now,这样也可以。
      • 是的,仍然不是我想要的,但是 ty ;-)
      • 伙计,你拯救了我的一天。请喝杯啤酒,然后把账单寄给我。
      猜你喜欢
      • 1970-01-01
      • 2014-09-30
      • 1970-01-01
      • 2021-10-11
      • 2021-06-05
      • 2016-07-09
      • 1970-01-01
      • 2013-12-23
      相关资源
      最近更新 更多