I'm trying to find the best way in JavaScript to get the day of the week of a particular date in any time zone, given only a date string.
Specifically, if I have a date string like:
2022-01-29
And I create a new Date object in JS with that string, and then call the getDay
method on the Date object, because I'm in the "America/New_York" time zone, I actually get the day of the week for the day before that date, not the day of the week of the date itself.
This can be easily demonstrated for anyone in a time zone that is minus-UTC time (e.g., America, Canada, etc.) by running:
new Date('2022-01-29').getDay()
which should return 6
for Saturday, but because of the time zone shift, I get 5
for Friday.
I found "https://stackoverflow.com/a/39209842/128421", which recommended using the getTimezoneOffset
method like:
var date = new Date('2016-08-25T00:00:00')
var userTimezoneOffset = date.getTimezoneOffset() * 60000;
new Date(date.getTime() - userTimezoneOffset);
That does seem to work, but a couple of points:
- The SO post recommends using
- userTimezoneOffset
at the end, but it only works for me with+ userTimezoneOffset
. Why? - Comments on the post said that it doesn't work for Daylight Saving Time or in all time zones, something I'm not sure how to easily confirm. In my initial testing, it seems to work fine for DST, but maybe there's something I'm missing, and either way, I'm not sure how to test it for other time zones.
What is the best way to get the day of the week in JavaScript when all I have is a date string?