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

158
Visualizações
Javascript to get the previous working day. Returns undefined

Been knocking my head for a few hours searching for a solution. Why would prevDate return undefined? Just don't understand what I am missing.

async function prevDate(date) {
    date.setDate(date.getDate()-1)
    if (date.getDay() == 0 || date.getDay() == 6) {
        prevDate(date)
    } else {
        console.log("date: ", date, "day: ", date.getDay())
        return (date)
    }
}

date = new Date("2021-09-20T00:00:00")
prevDate(date)
.then((res) => {
    console.log("res: ", res) //undefined
})
.catch((err) => {
    console.log(err)
})

output
date:  2021-09-17T04:00:00.000Z day:  5
res:  undefined
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The other people stated the reason your code doesn't work. But I'm wondering why you are using an async function for code that is not asynchronous. If you still want to use a recursive function it can be simply written like this:

function prevDate (date) {
  date.setDate(date.getDate() - 1);
  
  if (!(date.getDay() % 6)) {
    return prevDate(date);
  } else {
    console.log(`date: ${date} day: ${date.getDay()}`);
    return date;
  }
}

const date = new Date("2021-09-20T00:00:00");
console.log(`res: ${prevDate(date)}`);

Or you can simplify it even further:

const prevDate = (date) => {
  date.setDate(date.getDate() - 1);
  return !(date.getDay() % 6) ? prevDate(date) : date;
};

const date = new Date("2021-09-20T00:00:00");
console.log(`res: ${prevDate(date)}`);

about 4 years ago · Juan Pablo Isaza Relatório

0

You can write a simple function that subtracts 1, 2 or 3 days depending on which day of the week the date is on, e.g.

// Return previous work day (i.e. not Sat or Sun)
function getPreviousWorkDay(d = new Date()) {
  return new Date(d.getFullYear(), d.getMonth(), d.getDate() - ({1:3, 0:2}[d.getDay()] || 1)
  );
}

// Examples over year and month end
[new Date(2020,11,28), // Mon
 new Date(2020,11,29), // Tue
 new Date(2020,11,30), // Wed
 new Date(2020,11,31), // Thu
 new Date(2021, 0, 1), // Fri
 new Date(2021, 0, 2), // Sat
 new Date(2021, 0, 3), // Sun
].forEach(d => 
  console.log(`${d.toDateString()} => ${getPreviousWorkDay(d).toDateString()}`)
);

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