Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

219
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!