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

222
Visualizações
Why does setDate give strange answer when passed a string value?

I just came across a bug in my code and cannot figure out why. Two examples below of adding days to dates using Date.setDate(). In the first example I'm passing a numeric duration and getting the correct answer. In the second example I'm passing a string duration and getting an answer > 3 years in the future which is not what I want!

today = new Date(); //2021-10-12
duration = 30
new Date(new Date().setDate(today.getDate() + duration)); // 2021-11-11
duration2 = '30'
new Date(new Date().setDate(today.getDate() + duration2)); // 2025-02-11 why?

What is happening in the second example that causes the date to be so far in the future?

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

0

When a number is added to a string, they will be concatenated together. For example, 1 + '1' === '11'.

You need to convert the string to a number first, which can be done with the unary plus operator or parseInt.

new Date(new Date().setDate(today.getDate() + +duration2));
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