Java Cookies from the Future Past

While work­ing with cook­ies in Java/GWT and thus—to set the expire date—with Date, I found a doubt­ful Java behav­ior.

My goal was to set a cook­ie to expire in about one mon­th from today like this:

Date expires = new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 30);
Cookies.setCookie("myCookie", "myData", expires);

And kept won­der­ing why the cook­ie nev­er got stored.

And final­ly cre­at­ed a sim­ple 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 fol­low­ing 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

Accord­ing to Java’s cal­cu­la­tion, the cook­ie was expired already before even being set. 

Took me a bit to under­stand why:
1000 * 60 * 60 * 24 * 30 = 2,592,000,000 = 0x9A7EC800
Thus, the first bit got set to one… a clas­si­cal over­flow caus­ing the inte­ger val­ue to become neg­a­tive — just try:

System.out.println(1000 * 60 * 60 * 24 * 30);

It will print out -1702967296.

Fix: Add a lit­tle L will solve the issue by forc­ing the com­pil­er to cal­cu­late using the scope of long:

Date nextMonthLong = new Date(today.getTime() + 1000L * 60 * 60 * 24 * 30);

I guess I will fall for that one again some­time as the error is not obvi­ous in my opin­ion — espe­cial­ly because getTime() returns a long and still, the com­pil­er sticks with an int for the mul­ti­pli­ca­tion part. 

Leave a Reply

Your email address will not be published. Required fields are marked *