简体   繁体   中英

Moment.js keeps returning UTC instead of Local Date

I'm having what I hope/assume is a simple and silly issue getting Moment.js to return the local date.

I'm passing in this date/time string: 2015-02-19T06:32:00.001-05:00

Using this code:

var departureDateTime = "2015-02-19T06:32:00.001-05:00";
moment(departureDateTime).format("YYYY-MM-DD"); // returns 2015-02-19

That looks correct. However, if I inspect the time with the code below it will return the time in UTC, which will cause the date to be incorrect (a day in the future) at certain times during the day.

moment(departureDateTime).format("h:mma")); // 11:32am

What am I missing? I thought the default for Moment.js was to return the local time, so I'm confused as to why it wouldn't return 6:32am instead of 11:32am.

Thanks for any assistance you can offer.

A way to do it:

var dateStr = "2015-02-19T06:32:00.001-05:00";
moment(dateStr).utcOffset(dateStr).format("h:mma")

(From here: http://momentjs.com/docs/#/manipulating/utc-offset/ )

Edit: The intended way to do it, according to the documentation identified by K_C, is to use parseZone :

var dateStr = "2015-02-19T06:32:00.001-05:00";
moment.parseZone(dateStr).format('h:mma');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM