I would like to generate a list of dates, but found out the date is wrong start from - 25 * 24 * 60 * 60 * 1000
My local date is 2016-07-17. I got
2016-
Much easier to use minusDays( 1 ) on java.time.LocalDate.
LocalDate today = LocalDate.now(); // Better to pass the optional `ZoneId`.
for (int i=0; i<240; i++) {
LocalDate localDate = today.minusDays( i );
System.out.println( localDate.toString() );
…
}
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
Integer overflow.
Multiplying 25 * 24 * 60 * 60 * 1000
results in 2160000000
which is more than what fits in an integer.
You're overflowing the range of int
. i * 24 * 60 * 60 * 1000
yields an int
(which is then subtracted from the long
from getDate
).
It's okay when i
is 24, because the result is 2,073,600,000, which is less than the maximum positive value for an int
, 2,147,483,647. But when you reach i = 25
, you wrap around (the value if you weren't constrained to int
would be 2,160,000,000, which is too big).
Just make it a long
multiplication, either by declaring i
as a long or by making the 24 a long
:
Date dt = new Date(new Date().getTime() - i * 24L * 60 * 60 * 1000);
// ---------------------------------------------^
Why xxx works but yyy not work?
Because you've broken up the multiplication into two parts (I've added a space in there for clarity, since the -1
otherwise looks like a negative number rather than the subtraction operator followed by 1
):
Date xxx = new Date(new Date().getTime()-24 * 24 * 60 * 60 * 1000 - 1 * 24 * 60 * 60 * 1000);
// The first part -----------------------^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
// The second part ------------------------------------------------/
... and neither of the two parts you've broken it up into overflows the range of int
.
In general, I wouldn't suggest manipulating dates this way, not least because not all days have exactly 24 hours in them (consider the days going into and out of daylight saving time). I'd use a library that lets you work at the "day" level, such as the Java 8 java.time
stuff, or JodaTime, or similar.