问题
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 ofmoment().
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