Skip to content
Advertisement

How to get the day name from the date string regardless of user’s timezone?

Given a date (without time) e.g. 2021-08-11, how could I get its day name (e.g. Wednesday) regardless of the user’s timezone?

Note that trying to use:

new Date("2021-08-11").toLocaleString('en-AU', { weekday:'long' })

or date-fns‘s format:

format(new Date("2021-08-11"), "EEEE")

results in the wrong day (Tuesday) if the user’s timezone is GMT-7, for example.

Advertisement

Answer

You can use date-fns-tz as suggested by the other comment. It interally uses Intl. If you only care about getting the day you can just use Intl directly:

let formatter = new Intl.DateTimeFormat('en-US', {
  timeZone: 'UTC',
  weekday: 'long',
});

formatter.format(new Date("2021-08-11")) // outputs: "Wednesday"

I would recommend that you also format your dates to ISO i.e. "2021-08-11T00:00:00.000Z" as the Z at the end will ensure that the date is parsed in UTC before formatting.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement