skip to Main Content

If I create a new date using the new Date() constructor in JavaScript, passing a string with a ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ) UTC date, I get the following

new Date("2023-05-11T00:00:00Z")
Wed May 10 2023 21:00:00 GMT-0300 (Argentina Standard Time)
// or also
new Date("2023-05-11T00:00:00+00:00")
Wed May 10 2023 21:00:00 GMT-0300 (Argentina Standard Time)

When In fact I’d like to get the correct day number 11 instead of 10

If I just remove the UTC specification it works ok:

new Date("2023-05-11T00:00:00")
Thu May 11 2023 00:00:00 GMT-0300 (Argentina Standard Time)

How should I deal with it? Should I just remove the trailing ‘Z’?

2

Answers


  1. Dates internally are always UTC-based timestamps. You can use .toISOString() to get the UTC date string from any date instance. Or, as you noted, you can create dates with strings that represent your local time or any other time zone. But understand that the time zone is not part of the internal UTC-based timestamp. Time zone comes into play when you convert a string to a Date instance, or when you request a string rendering of an existing Date instance.

    In your case, Argentina is 3 hours behind UTC, so midnight of day 11 is 21:00 on day 10 (of some month).

    Login or Signup to reply.
  2. You can use the following code.

    var d = new Date("2023-05-11T00:00:00Z");
    d.toLocaleString('en-US', { timeZone: 'America/New_York' });
    

    If you want to know toLocaleString() method more, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

    Thank you

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