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 the following:
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 the following:
new Date('2022-01-29').getDay()
You should get 6
for Saturday, but because of the time zone shift, you get 5
for Friday.
I found another SO post (Parse date without timezone javascript) that recommended using the getTimezoneOffset
method as follows:
var date = new Date('2016-08-25T00:00:00')
var userTimezoneOffset = date.getTimezoneOffset() * 60000;
new Date(date.getTime() - userTimezoneOffset);
That does seem to work for me right now, but a couple of points:
- The SO post recommends using
- userTimezoneOffset
at the end, but it only works for me with+ userTimezoneOffset
. What’s up with that? - 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 daylight saving time, but maybe there’s something I’m missing, and either way, I’m not sure how to test it for other time zones.
Long story short, what is the best way to get the day of the week in JS when all you have is a date string? Thank you.
>Solution :
Use
new Date('2022-01-29').getUTCDay()
new Date('2022-01-29')
will create a Date object with the UTC (Greenwhich) date "2022-01-29" and time "00:00h". When getting a weekday with .getDay()
your browser would calculate it for your local timezone. By using .getUTCDay()
instead you get the weekday for the UTC timezone.
Interesting point made by @RayHatfield
console.log("UTC-time:", new Date("2022-01-29").getUTCHours()) // 0
console.log("UTC-time:", new Date("2022-01-29Z00:00:00").getUTCHours()) // 0 ("Z" is for "ZULU" -> UTC)
console.log("UTC-time:", new Date("2022-01-29T00:00:00").getUTCHours()) // UTC time (h) for your local midnight