I have 2 kinds of date strings coming back to the UI. One date format has timezone and the other doesn’t.
The date string that has timezone displays the date correctly but the date string with no timezone displays the previous date.
how can I handle both the scenarios properly?
Here’s how I have it in my app:
const d = new Date("2022-03-25"); // Thu Mar 24 2022 19:00:00 GMT-0500
const x = new Date("2022-12-14T06:03:14Z"); // Dec 14 2022 00:03:14 GMT-0600
Update:
This works but looking for a more elegant/efficient way. Please help
const parsed = value.includes('T') ? new Date(value)
: new Date(value.replace(/-/g, '/'));
2
Answers
If you can use string to handle dates, you can use
toIOSString
new Date("2022-03-25").toISOString() // '2022-03-25T00:00:00.000Z'
new Date("2022-12-14T06:03:14Z").toISOString() '2022-12-14T06:03:14.000Z'
If you wanna add a timezone to all strings
EDIT if you wanna remove the timezone from all strings
If I run
new Date("2023-01-01T00:00:00Z")
in a browser here in Sweden with the CEST timezone it outputsDate Sun Jan 01 2023 01:00:00 GMT+0100 (Central European Standard Time)
– which is one hour after midnightwhile
new Date("2023-01-01T00:00:00Z".replace("Z", ""))
outputsDate Sun Jan 01 2023 00:00:00 GMT+0100 (Central European Standard Time)
– exactly midnight