Skip to content
Advertisement

Moment date conversion from datepicker format problem

I have a problem with converting date time which comes from datepicker to moment (I use this library) time format.

What I get from datepicker: 2021-01-30T07:00:00.000Z

The code that I used via moment:

let tempTime = moment(dateString).toDate()

Output I get with this implementation: Fri Apr 30 2021 00:00:00 GMT-0700 (Mountain Standard Time)

What I expected: Fri Apr 30 2021 07:00:00 GMT-0700 (Mountain Standard Time)

The difference is between hours. In my implementation they just being ignored.

How can I overcome this issue?

Thanks for your attention!

Advertisement

Answer

The problem with conversion is the date string is in an UTC format. Either you remove the Z at the end or you can provide custom format and escape the UTC identifer like below.

const dateString = "2021-01-30T07:00:00.000Z";
let tempTime = moment(dateString, "YYYY-MM-DDTHH:mm:ss[Z]").toDate();
console.log(tempTime);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement