2009-06-11 23 views
5

我知道Date大多已棄用,但我仍然不時使用它(比使用Calendar更少的代碼)。我遇到了一個真正奇怪的錯誤,我想知道是否有人可以向我解釋這一點。Java的Date類正在發生什麼?這是一個已知的錯誤?

該代碼,這增加24天到當前時間:

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); 

給出了這樣的正確的輸出:

現在=星期四06月11 10點50分09秒IDT 2009

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

while this code,which added 2 5天:

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); 

給出了這樣的輸出:

現在=週四6月11日10時51分25秒IDT 2009年

未來=太陽5月17日17點48分37秒IDT 2009年

我可以理解小時甚至幾天的差異,但任何人都可以解釋爲什麼加入太多毫秒導致回到?我很困惑。

回答

27

25 * 24 * 60 * 60 * 1000 = 21.6億= 0x80BEFC00

您正在計算的整數值,並得到一個溢出。如果它是

25 * 24 * 60 * 60 * 1000L

一切都應該罰款。

+0

很微妙 - 好斑點! – belugabob 2009-06-11 08:16:17

5

這不是Date類中的錯誤,它是整數溢出的情況。 int S IN的Java只能是-2 和2之間31 - 25 1,但 1000是大於2 - 1,從而它溢出。

如果運行

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

如果您通過添加後綴L給它,該產品指定你爲long一起乘以一個號碼,你得到的結果

2073600000 
-2134967296 

也將是一個longlong值可能會高達2 -1因此,除非將批次天添加到您的Date s,否則不會溢出。例如,

System.out.println(25L*24*60*60*1000); 

給你

2160000000 
相關問題