2014-03-01 43 views
0

的JavaDoc Date類規定,正開始日期與時間(毫秒)構造

public Date(long date) 
Allocates a Date object and initializes it to represent the specified number of   
milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 
00:00:00 GMT. 

下面是一個使用日期計算的毫秒數(長毫秒)構造函數計算1月24日和1月25日期代碼

public static void main(String[] args) throws java.text.ParseException { 

    long milliSecFor25 = (24*60*60*24*1000); 
    long milliSecFor26 = (25*60*60*24*1000); 
    Date dateJan25 = new Date(milliSecFor25); 
    Date dateJan26 = new Date(milliSecFor26); 
    System.out.println("Date for Jan 25:" + dateJan25); 
    System.out.println("Date for Jan 26:" + dateJan26); 
} 

上執行下面的代碼我得到下面的輸出,

Date for Jan 25: Sun Jan 25 05:30:00 IST 1970 
    Date for Jan 26: Sun Dec 07 12:27:12 IST 1969 

這是不正確的。有人可以解釋爲什麼不`噸我得到年01月25

正確的日期
+0

,我認爲你應該檢查你的「曖昧」的使用以供將來參考 - 我想你只是說「不正確」在這裏,這是不一樣的東西。 –

+0

@JonSkeet:雅好感謝,我將在這裏改變它太 –

回答

5

的問題是在這裏:

25*60*60*24*1000 

所有這一切都在整數執行算術 - 和值溢出。

你可以看到,如果執行使用long值而不是算術,並顯示結果相比Integer.MAX_VALUE

milliSecFor26 = (25*60*60*24*1000L); 
System.out.println("Millis: " + milliSecFor26); 
System.out.println("Integer.MAX_VALUE: " + Integer.MAX_VALUE); 

打印:

Millis: 2160000000 
Integer.MAX_VALUE: 2147483647 

所以你int算術實際上是溢出來一個值,這就是爲什麼你看到Unix紀元前Date值。

隨着旁白:

  • 您可以使用TimeUnit.DAYS.toMillis(26)作爲計算這一
  • 在Java標準庫(前的Java 8),你應該使用Calendar以獲得適當的Date從更清潔的方式年/月/日
  • Joda Time更好庫Date/Calendar
  • 爪哇8將具有even cleaner date/time API(在java.time包)。
6

你有一個整數溢出。使用多頭,而不是整數:

long milliSecFor25 = (24L * 60L * 60L * 24L * 1000L);