moment js is returning wrong formatted values for an iso timestamp

后端 未结 2 1795
孤城傲影
孤城傲影 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

提交回复
热议问题