0

How to avoid the local timezone conversions when working with new Date() in javascript, for example, today is "2022-03-24", if I use new Date("2022-03-24") I'll be getting different dates in different countries, how to avoid this conversation and use only the date, also I need the date object because of the date picker.

is this a solution?

let date = new Date(2022, 02, 24, 0, 0, 0, 0)
Ranjith M
  • 217
  • 1
  • 2
  • 11
  • [this might be able to answer your question.](https://stackoverflow.com/questions/25417978/datetime-locale-string-not-change-even-i-changed-the-locale-in-app-in-android) I'm unable to comment, so I've used an answer to help. – Archigan Mar 24 '22 at 17:03

1 Answers1

0

A few things:

  • Your example of new Date("2022-03-24") will have the input will be interpreted as midnight UTC due to the format you used. It's identical to new Date("2022-03-24T00:00:00.000Z"). You'd also get the same result with new Date(Date.UTC(2022, 2, 24, 0, 0, 0, 0)).
  • Your example of new Date(2022, 2, 24, 0, 0, 0, 0) will have the input interpreted as local time due to the constructor you used. It gives the same output as new Date("2022-03-24T00:00:00.000") (without the Z).
  • The Date object itself has no time zone - it is just a wrapper around a UTC-based Unix timestamp.
  • What you do with the resulting Date object has as much to do with whether you will observe a time zone conversion as creating it does. For example, toString will provide a string representation in terms of local time, but toISOString will provide a string representation in terms of UTC.
  • Thus, the only way to completely avoid any time zone conversions is to construct in terms of UTC and then only use functions that output in terms of UTC (like toISOString) or get/set in terms of UTC (like getUTCHours, setUTCHours, etc.)
  • You mentioned you are using a date picker.
    • Many date pickers will have properties that give you back a Date object, but some will instead give you back a string in yyyy-mm-dd format. If your goal is to pass along the chosen date to a back end API, you should avoid using a Date object. Just take the string and send that instead. The standard <input type="date"> is a good example. See the docs for its Value property for more details.
    • If your date picker only provides a Date object, then chances are it was constructed in terms of the user's local time zone. You should make a date string in yyyy-mm-dd format yourself (using the local time based properties getFullYear, getMonth, and getDate), and then pass that to your API.
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575