简体   繁体   中英

How to convert from GMT/UTC to local time and back using momentjs?

I have the following string:

"December 25, 2018 01:02:20"

I intend this to be GMT/UTC Using moment.js, how do I convert this to local time and back to UTC?

When I do:

moment(myDateString).local()

Then later to try to convert back:

moment(myDateStrig).utc()

They both yield different results. How do I make it so that I can convert the time I have from UTC to local, then back to UTC?

Note: When I try the .utc() function on the string "December 25, 2018 01:02:20" I get a different time. When I do a .local() on the utc converted moment, I get a different date that is not my original date of "December 25, 2018 01:02:20" .

Please show an example if you can as I it looks like I have 3 different dates.

Since your input represent UTC time, you have to use moment.utc (as suggested by others in the comments):

By default, moment parses and displays in local time.

If you want to parse or display a moment in UTC, you can use moment.utc() instead of moment() .

Moreover, since your input string is not in a format recognized by moment(String) (ISO 8601 or RFC 2822), you have to pass format parameter as second argument of moment.utc , see String + Format parsing section of the docs.

Here a code sample:

 var input = "December 25, 2018 01:02:20"; var fmt = 'MMMM DD, YYYY HH:mm:ss'; var m = moment.utc(input, fmt); console.log(m.local().format(fmt)); console.log(m.utc().format(fmt));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>

In order to interpret a string such as "December 25, 2018 01:02:20" which does not have a time zone on it, you can call moment() on it, which will interpret it as local time, or you can call moment.utc() on it, which will interpret it as UTC time.

Try this:

const myUtcMoment = moment.utc(myDateString)

This should result in a Moment object that represents 01:02:20 AM on December 25, 2018 in the UTC time zone.

In order to convert that Moment to local time, you can do this:

const myLocalMoment = myUtcMoment.local()

And to convert it back, you can call myLocalMoment.utc() .

By the way, with this date format, it is not really clear whether this is 24-hour time or not. The Moment.js docs recommend specifying a format in order to alleviate ambiguity.

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