When I fetch data from my PostgreSQL database, it comes in the following format: 2022-11-30T21:00:00.000Z
and it’s not a string; it’s in the form of a date object.
The library that I’m using to work with dates is dayjs
. So here is the issue.
When I call the format method, I get a bad date. like one day off.
dayjs(‘2022-11-30T21:00:00.000Z’) and it gives me 2022-12-01T00:00:00+03:00
.So the real date that was stored was 30th November, but it gives me 1st December.
I saw this post dayjs returns wrong date with format in Stack overflow but the accepted solution is wired because it assumes that I manually remove the Z
at the end.
And even when i try to convert it in a YYYY-MM-DD
by using dayjs('2022-11-30T21:00:00.000Z').format('YYYY-MM-DD')
it’s returning 2020-12-01
.
I really stuck.
3
Answers
The date conversion is correct. The given date is 0 UTC and the output is +3 UTC. Since the time provided is 21.00, the converted date with +3 UTC is the next day at time 00.00
This happens because the library converts the time to the local timezone. In this timezone (UTC+3), the time happens to fall on a different date as well. If you want to keep the original date, you have to tell dayjs to use UTC instead of the local timezone.
As the library’s docs explain, you can customize which timezone you use for the parsing/converting. For this, you have to add the timezone and UTC plugins. For example, in the browser:
Once you add the plugins, you can get the correct and formatted UTC days in this way:
You can see the complete solution here.
You have to use dayjs
utc
like this:If you set
utc(true)
, it will return Dec 1 instead of Nov 30.Source: https://day.js.org/docs/en/manipulate/utc#docsNav