Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
How to get numeric day-of-week for given timezone in Javascript?

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda