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