2012-10-22 15 views
0

可能重複:
Why does Java’s Date.getYear() return 111 instead of 2011?無法從Date對象中的真正的約會我在java

我想獲得的年,月,日形成一個日期對象,但下面讓我完全隨機的東西:

Date d = new Date(); 
    System.out.println(d.getYear() + " - " + d.getMonth() + " - " + d.getDay()); 

我得到:112 - 9 - 1

有誰知道爲什麼?你有沒有一個好主意?對於我的程序,我需要Date對象。

+0

對面http://stackoverflow.com/questions/13021060/java-date-output-is-wrong-why –

回答

9

讀這三種方法the javadoc(這已被棄用,因此不應該被使用,BTW)將告訴你爲什麼:

  • 112:自1900年數
  • 9:月份數,從0開始(所以9指十月)
  • 1:月的一天

使用日曆獲取日期字段,使用DateFormat格式化日期。

+0

正是我要去交+1 –

+0

我覺得最後一個必須是DAY_OF_WEEK。不是一個月的日子 – chrome

+0

啊,很好。謝謝。 – gedemagt

1

燁...的docs know

具體來說,一年getYear回報是當前公曆年份減去1900

再者,這些干將已被棄用。你應該使用Calendar類。

如果必須取Date對象中,然後使用Calendar.getInstance().setTime(dateObject)

1

源代碼解釋原因。

@Deprecated 
public int getYear() { 
    return normalize().getYear() - 1900; 
} 
@Deprecated 
public int getMonth() { 
return normalize().getMonth() - 1; // adjust 1-based to 0-based 
} 

@Deprecated 
public int getDay() { 
return normalize().getDayOfWeek() - gcal.SUNDAY; 
}