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

前端 未结 2 1167

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));

提交回复
热议问题