Home > Back-end >  Why does setDate give strange answer when passed a string value?
Why does setDate give strange answer when passed a string value?

Time:10-13

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?

CodePudding user response:

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));
  • Related