Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

220
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda