moment js is returning wrong formatted values for an iso timestamp

醉酒当歌 提交于 2019-12-31 04:11:11

问题


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.

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

This should return 2018-01-31 but rather it's returning 2018-02-01.

It's adding one day to every date like that. I'm suspecting some time zone based issue but I'm not able to figure it out.


回答1:


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




回答2:


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>


来源:https://stackoverflow.com/questions/48578131/moment-js-is-returning-wrong-formatted-values-for-an-iso-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!