By default, MomentJS parses in local time. If only a date string is provided (no time), the default value is used until midnight.
In your code, you create a local date and then convert it to the UTC time zone (in fact, it switches the instance of the instance to UTC ), so when it is formatted, it moves (depending on your local time) forward or backward.
If the local time zone is UTC + N (N is a positive number) and you parse the string for date only, you will get the previous date.
Here are some examples to illustrate this (my local time offset is 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 you want the date and time string to be interpreted as UTC, you must be explicit:
>>> moment(new Date('07-18-2013 UTC')).utc().format("YYYY-MM-DD HH:mm") "2013-07-18 00:00"
or, as Matt Johnson mentions in his answer, you can ( and probably ) parse it as a UTC date using moment.utc() and include the format string as the second argument to prevent ambiguity.
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').format("YYYY-MM-DD HH:mm") "2013-07-18 00:00"
To switch sides and convert the UTC date to a local date, you can use the local() method as follows:
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').local().format("YYYY-MM-DD HH:mm") "2013-07-18 03:00"
MasterAM Jul 25 '13 at 11:29 2013-07-25 11:29
source share