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:
JavaScript
x
2
1
new Date("2021-08-11").toLocaleString('en-AU', { weekday:'long' })
2
or date-fns
‘s format
:
JavaScript
1
2
1
format(new Date("2021-08-11"), "EEEE")
2
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:
JavaScript
1
7
1
let formatter = new Intl.DateTimeFormat('en-US', {
2
timeZone: 'UTC',
3
weekday: 'long',
4
});
5
6
formatter.format(new Date("2021-08-11")) // outputs: "Wednesday"
7
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.