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

前端 未结 2 1802
我在风中等你
我在风中等你 2021-01-12 05:27

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 nati         


        
相关标签:
2条回答
  • 2021-01-12 06:04

    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 now is constructed in the current timezone and native is constructed in UTC, they will differ by your offset. 11 AM PST != 11 AM GMT.

    0 讨论(0)
  • 2021-01-12 06:22

    Call moment.utc() the same way you're calling 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 now lives in the local timezone, and it will convert it to UTC first, hence the difference.

    0 讨论(0)
提交回复
热议问题