Search code examples
javascriptdatetimezone-offsetdayofweek

What's the best way in JavaScript to get the day of the week of a date string in any time zone?


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:

  1. The SO post recommends using - userTimezoneOffset at the end, but it only works for me with + userTimezoneOffset. Why?
  2. 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?


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:00Z").getUTCHours()) // 0 (ISO 8601 date string -> UTC)
    console.log("UTC-time:", new Date("2022-01-29T00:00:00").getUTCHours()) // UTC time (h) for your local midnight

    See https://en.m.wikipedia.org/wiki/ISO_8601 for details on date strings.