const d = new Date(); // get 'now'
d.getDay(); // 0 = Sunday, 1 = Monday... in my browser's timezone.
d.toLocaleDateString('en-GB', { timeZone: 'NZ' }); // formatted date in NZ
console.log(d);
How can I get the numeric day in NZ? toLocaleDateString does not support weekday: 'numeric'.
The only way I can think of is to map the day to Sat, Sun ... and then use a {Sun: 0...} map to map it back to a number?!
EDIT: To be clear: the day-of-the week for a given time will be different in different timezones. But Date.getDay() only returns the numeric date in the browser's timezone. toLocaleDateString can present the date in different timezones, however it does not appear to support outputting the day/weekday as a number, which seems a surprising omission.
Also, I do not want to use some deprecated massive library (looking at you, moment) but instead I want to use vanilla Javascript.
OK, as of April 2022, apparently there is no way! Here's my work-around:
// This date is Wednesday 2022-04-20 13:00:00 at UTC/GMT
// In NZ, it is Thursday 2022-04-21 01:00:00
const d = new Date(Date.UTC(2022, 3, 20, 13, 0, 0));
const timeZone = 'NZ';
const numericDayInNZ =
['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
.indexOf(d.toLocaleDateString('en-GB', {weekday:'short', timeZone}));
console.log("At UTC date: ", d,
"your timezone has a numeric day of:", d.getDay(),
"and in NZ it is", numericDayInNZ);
Note: if you want to use this code in your own locale, you can either change the en-GB and all the day names, or just leave it as-is if that's unoffensive and all you need is the number.
The handy thing is that you can rearrange the days, e.g. to put Sun last if you wanted 0 = Monday.
I think it was an oversight in the spec not to have included a Date.prototype.getDay equivalent in Date.prototype.toLocale(Date|Time)?String functions, but at least this solution is efficient enough and does not require bulky third party libs.