javascript - moment.js - UTC gives wrong date -


why moment.js utc show wrong date. example chrome's developer console:

moment(('07-18-2013')).utc().format("yyyy-mm-dd").tostring() // or moment.utc(new date('07-18-2013')).format("yyyy-mm-dd").tostring() 

both of them return "2013-07-17" why returning 17th instead of 18th, passed in.

but if use momentjs without utc:

moment(new date('07-18-2013')).format("yyyy-mm-dd").tostring() 

i "2013-07-18" expect when using moment.js utc.

does mean cannot correct date when using moment.js utc?

by default, momentjs parses in local time. if date string (with no time) provided, time defaults midnight.

in code, create local date , convert utc timezone (in fact, makes moment instance switch utc mode), when formatted, shifted (depending on local time) forward or backwards.

if local timezone utc+n (n being positive number), , parse date-only string, previous date.

here examples illustrate (my local time offset utc+3 during dst):

>>> moment('07-18-2013', 'mm-dd-yyyy').utc().format("yyyy-mm-dd hh:mm") "2013-07-17 21:00" >>> moment('07-18-2013 12:00', 'mm-dd-yyyy hh:mm').utc().format("yyyy-mm-dd hh:mm") "2013-07-18 09:00" >>> date() "thu jul 25 2013 14:28:45 gmt+0300 (jerusalem daylight time)" 

if want date-time string interpreted utc, should explicit it:

>>> moment(new date('07-18-2013 utc')).utc().format("yyyy-mm-dd hh:mm") "2013-07-18 00:00" 

or, matt johnson mentions in answer, can (and should) parse utc date in first place using moment.utc() , include format string second argument prevent ambiguity.

>>> moment.utc('07-18-2013', 'mm-dd-yyyy').format("yyyy-mm-dd hh:mm") "2013-07-18 00:00" 

to go other way around , convert utc date local date, can use local() method, follows:

>>> moment.utc('07-18-2013', 'mm-dd-yyyy').local().format("yyyy-mm-dd hh:mm") "2013-07-18 03:00" 

Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -