在java.util.Date
中:
* In all methods of class <code>Date</code> that accept or return
* year, month, date, hours, minutes, and seconds values, the
* following representations are used:
* <ul>
* <li>A year <i>y</i> is represented by the integer
* <i>y</i><code>-1900</code>.
当然,在Java 1.1中,不推荐使用
getYear()
方法等,而推荐使用java.util.Calendar
,该方法仍然具有以下怪异的弃用说明: int getYear()
Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR) - 1900.
setYear(int year)
Deprecated. As of JDK version 1.1, replaced by Calendar.set(Calendar.YEAR, year + 1900).
当然,Month是基于
0
的,但是我们都知道(尽管您认为他们已经从Calendar
中消除了这个问题-他们没有): * <li>A month is represented by an integer from 0 to 11; 0 is January,
* 1 is February, and so forth; thus 11 is December.
我确实检查了以下问题:
Why does Java's Date.getYear() return 111 instead of 2011?
Why is the Java date API (java.util.Date, .Calendar) such a mess?
我的问题是:
java.util.Date
的原始创建者希望通过从中减去1900来存储“年”的数据而获得什么呢?特别是如果它基本上存储了很长时间。 因此:
private transient long fastTime;
@Deprecated
public int getYear() {
return normalize().getYear() - 1900;
}
@Deprecated
public void setYear(int year) {
getCalendarDate().setNormalizedYear(year + 1900);
}
private final BaseCalendar.Date getCalendarDate() {
if (cdate == null) {
BaseCalendar cal = getCalendarSystem(fastTime);
....
最佳答案
基本上,原始的java.util.Date设计器从C复制了很多东西。您看到的是结果(请参见 tm
struct)。因此,您可能应该问为什么将其设计为使用1900年。我怀疑基本答案是“因为在设计tm
时,我们对API的设计不是很擅长”。我认为在日期和时间方面,我们在API设计上仍然不是很擅长,因为有很多不同的用例。
不过,这只是API,而不是java.util.Date
内的存储格式。别烦,请注意。