Does DateUtil.AddDays accept a variable for the # of days?

400 views Asked by At

I'm trying to use a variable for the number of days in my call to DateUtil.addDays, but it's not working. Am I missing something simple, or does it just not work?

//Example:
x = 10  //this int is the result of some math, and changes frequently
y = Thu Aug 31 00:00:00 MST 2017  //this is the date

z = DateUtil.addDays(y, x)   //This will error.
z = DateUtil.addDays(y, 10)  //This works.
1

There are 1 answers

0
Pac0 On BEST ANSWER

You have to be careful with your types in Java.

Examples :

// suppose variable y contains your date as in your example
int x = 10;                   // value is 10
double w = x;                 // value is same as 10 (or, more precisely, 10.0)

z = DateUtil.addDays(y, x);   // This will compile. 

// This will not compile. AddDays expect an argument of type `int`,
// not a `double`, even if the value inside is mathematically
// the same as the int 10.
 z = DateUtil.addDays(y, w);

// This will compile : the result of Math.round() is of type int
z = DateUtil.addDays(y, Math.round(w));