While working with cookies in Java/GWT and thus—to set the expire date—with
Date, I found a doubtful Java behavior.
My goal was to set a cookie to expire in about one month from today like this:
Date expires = new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 30); Cookies.setCookie("myCookie", "myData", expires);
And kept wondering why the cookie never got stored.
And finally created a simple test case like this:
Date today = new Date(); Date tomorrow = new Date(today.getTime() + 1000 * 60 * 60 * 24); Date nextMonth = new Date(today.getTime() + 1000 * 60 * 60 * 24 * 30);
And got following dates:
today=Mon Feb 07 14:27:50 CET 2011 tomorrow=Tue Feb 08 14:27:50 CET 2011 nextMonth=Tue Jan 18 21:25:02 CET 2011
According to Java’s calculation, the cookie was expired already before even being set.
Took me a bit to understand why:
1000 * 60 * 60 * 24 * 30 = 2,592,000,000 = 0x9A7EC800
Thus, the first bit got set to one… a classical overflow causing the integer value to become negative – just try:
System.out.println(1000 * 60 * 60 * 24 * 30);
It will print out
Fix: Add a little
L will solve the issue by forcing the compiler to calculate using the scope of
Date nextMonthLong = new Date(today.getTime() + 1000L * 60 * 60 * 24 * 30);
I guess I will fall for that one again sometime as the error is not obvious in my opinion — especially because
getTime() returns a
long and still, the compiler sticks with an
int for the multiplication part.