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

175
Visualizações
How to get the Monday of the current week (or previous week in some cases) regardless of the week starts on Sunday or Monday

I have let today = new Date() object. I need to get the Monday of the current week regardless if the week starts on Sunday or Monday. If the week starts on a Sunday and the today is Sunday I need to get the Monday on the previous week. Sunday should always be the last day. Any suggestions on how to solve this?

Now I use this, which at least works fine when the week starts on Monday.

// Get the monday date of current week
function getMondayOfCurrentWeek(d) {

  const date = new Date(d);
  const day = date.getDay(); // Sunday - Saturday : 0 - 6

  //  Day of month - day of week (-6 if Sunday), otherwise +1
  const diff = date.getDate() - day + (day === 0 ? -6 : 1);

  return new Date(date.setDate(diff));
}

console.log(
  getMondayOfCurrentWeek(new Date(2022,3,3)).toDateString()
);

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

0

Your code DOES get the previous Monday on a Sunday

What does "If the week starts on a Sunday" mean to your?

In JS Sunday is the 0th or first day

// Get the monday date of current week
function getMondayOfCurrentWeek(d) {
  const date = new Date(d);
  const day = date.getDay(); // Sunday - Saturday : 0 - 6
  //  Day of month - day of week (-6 if Sunday), otherwise +1
  const diff = date.getDate() - day + (day === 0 ? -6 : 1);
  return date.setDate(diff), date;
}

console.log(getMondayOfCurrentWeek(new Date()).toDateString() )

console.log(getMondayOfCurrentWeek(new Date(2022,3,3,15,0,0,0)).toDateString() ); // Sunday 3rd of April 2022

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