Reputation: 171369
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.
Upvotes: 0
Views: 820
Reputation: 778
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.
Upvotes: 1
Reputation: 430
I haven't surveyed the latest data-fns
. But when I used it a couple of years ago, it didn't have a timezone support. Since the Date
class does not keep the timezone information internally, it causes some problems when the location of time acquisition is different from where it is used. See this stackoverflow post for details.
There are some libraries available to solve this problem. Since you are using date-fns
you might want to try date-fns-tz.
Upvotes: 1