tags:

views:

606

answers:

2

I know Date is mostly deprecated, but I still use it form time to time (less code than using Calendar). I came across a truly bizarre bug, and I'm wondering if anyone can explain this to me.

This code, which adds 24 days to the current time:

long nowL = System.currentTimeMillis();
Date now = new Date(nowL);
System.out.println("now = "+now);
Date future = new Date(nowL+ 24*24*60*60*1000);
System.out.println("future = "+future);

gives this correct output:

now = Thu Jun 11 10:50:09 IDT 2009

future = Sun Jul 05 10:50:09 IDT 2009

while this code, which adds 25 days:

long nowL = System.currentTimeMillis();
Date now = new Date(nowL);
System.out.println("now = "+now);
Date future = new Date(nowL+ 25*24*60*60*1000);
System.out.println("future = "+future);

gives this output:

now = Thu Jun 11 10:51:25 IDT 2009

future = Sun May 17 17:48:37 IDT 2009

I can understand a difference of hours, even days, but can anyone explain why adding too many milliseconds causes going back in time?? I'm baffled.

+21  A: 

25*24*60*60*1000 = 2160000000 = 0x80BEFC00

you are computing an integer value, and get an overflow. if it was

25*24*60*60*1000L

everything should be fine.

mfx
Very subtle - well spotted!
belugabob
Yep, I had the same thought and verified it just to find that you'd already figured it out. :)
Emil H
TRWTF is that the compiler doesn't warn you about an integer overflow for a constant..
Thorarin
well I'll be damned... I was sure I used long.
Yuval
+4  A: 
Pourquoi Litytestdata