7 Feb 2011, 2:58pm
java:

leave a comment




  • Anzeige
  • 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 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 won­der­ing why the cookie never got stored.

    And finally cre­ated 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 cookie 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 value 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­piler 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­cially because getTime() returns a long and still, the com­piler sticks with an int for the mul­ti­pli­ca­tion part.