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

前端 未结 2 1162

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?

相关标签:
2条回答
  • 2021-01-29 04:44

    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>

    0 讨论(0)
  • 2021-01-29 04:45

    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.

    0 讨论(0)
提交回复
热议问题