Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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

Problem courtesy of: hereandnow78


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.

Solution courtesy of: robertklep


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription