moment js is returning wrong formatted values for an iso timestamp

后端 未结 2 1772
孤城傲影
孤城傲影 2021-01-16 00:10

I\'m passing \"2018-01-31T22:55:02.907Z\" this timestamp to the moment() function but it returns the wrong value after formatting the date part.

相关标签:
2条回答
  • 2021-01-16 00:27

    You have to use .utc when passing timestamp like this: If you do:

    console.log(moment("2018-01-31").format('YYYY-MM-DD'));
    

    It would give you the desired result but when passing timestamp like you have done now, what you should do is:

    console.log(moment.utc("2018-01-31T22:55:02.907Z").format('YYYY-MM-DD'));
    

    You can also see how this works:

    console.log(moment({ years:2018, months:0, date:31, hours:22, minutes:55, seconds:02, milliseconds:907}).format('YYYY-MM-DD'));
    

    For passing timestamp you should check the documentation again. https://momentjs.com/docs/#/parsing/unix-timestamp-milliseconds/

    This also might be a helpful link: https://coderwall.com/p/exrbag/use-momentjs-to-parse-unix-timestamps

    0 讨论(0)
  • 2021-01-16 00:42

    You have to use moment.utc():

    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().

    console.log(moment("2018-01-31T22:55:02.907Z").format('YYYY-MM-DD'));
    console.log(moment.utc("2018-01-31T22:55:02.907Z").format('YYYY-MM-DD'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

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