skip to Main Content

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


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

    Login or Signup to reply.
  2. If you wanna add a timezone to all strings

    value.includes('T') ? new Date(value) : new Date(value + "T00:00:00.000Z");
    

    EDIT if you wanna remove the timezone from all strings

    new Date(value.replace("Z", ""));
    

    If I run new Date("2023-01-01T00:00:00Z") in a browser here in Sweden with the CEST timezone it outputs Date Sun Jan 01 2023 01:00:00 GMT+0100 (Central European Standard Time) – which is one hour after midnight

    while new Date("2023-01-01T00:00:00Z".replace("Z", "")) outputs Date Sun Jan 01 2023 00:00:00 GMT+0100 (Central European Standard Time) – exactly midnight

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search