Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 733
hereandnow78 Avatar asked Feb 28 '13 10:02

hereandnow78


People also ask

How do you use UTC in moments?

utc() will be in UTC mode, and any moment created with moment() will not. To switch from UTC to local time, you can use moment#utc or moment#local.

Is MomentJS deprecated?

Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release. This deprecation warning is thrown when no known format is found for a date passed into the string constructor.

Does moment convert UTC to local?

To convert UTC time to Local you have to use moment. local() .


2 Answers

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.

like image 186
robertklep Avatar answered Oct 03 '22 19:10

robertklep


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.

like image 45
timrwood Avatar answered Oct 03 '22 20:10

timrwood