4

I'm trying to add some day on a date but actually i got a strange result...

I test with today as current day (28/02/2019), and try to add like 400 day and I'm in year 2096... I think tere is a problem

Take a look at my function :

const user = { LastReport: new Date(), Validite: "413" }

var temp = new Date(user.LastReport)
console.log("Current : " + temp);
user.DateValide = temp.setDate(temp.getDate() + user.Validite);
console.log("Day to add : " + user.Validite)
console.log("Result : " + new Date(user.DateValide))

and my result :

enter image description here

There is something i'm doing wrong ?

adiga
  • 34,372
  • 9
  • 61
  • 83
Toto NaBendo
  • 290
  • 3
  • 26

1 Answers1

5

The temp.getDate() + user.Validite are being concatenated as strings so the days added is 28413 instead of 441.

Use parseInt() to convert them to Number or you can prefix them with an arithmetic operator like +.

const user = { LastReport: new Date(), Validite: "413" }

var temp = new Date(user.LastReport)
console.log("Current : " + temp);
//user.DateValide = temp.setDate(parseInt(temp.getDate()) + parseInt(user.Validite));
user.DateValide = temp.setDate(+temp.getDate() + +user.Validite);
console.log("Day to add : " + user.Validite)
console.log("Result : " + new Date(user.DateValide))
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
  • In ECMAScript, the '+' character is overloaded and has three possible meanings. When used like `+ +user.Validite`, the first is seen as the [*addition operator*](http://ecma-international.org/ecma-262/9.0/#sec-addition-operator-plus), the second is seen as the [*unary + operator*](http://ecma-international.org/ecma-262/9.0/#sec-unary-plus-operator). :-) – RobG Mar 02 '19 at 21:27