为什么java.util.Date将Year表示为"year-1900"?

Epi*_*rce 4 java date offset java.util.date

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>.
Run Code Online (Sandbox Code Playgroud)

当然,在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).
Run Code Online (Sandbox Code Playgroud)

当然,以月为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.
Run Code Online (Sandbox Code Playgroud)

我确实检查了以下问题:

为什么Java的Date.getYear()返回111而不是2011?

为什么Java date API(java.util.Date,.Calendar)如此混乱?

我的问题是:

  • 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);
    ....
Run Code Online (Sandbox Code Playgroud)
  • 为什么1900

Jon*_*eet 11

基本上原始的java.util.Date设计者从C中复制了很多.你所看到的是结果 - 看tm结构.所以你应该问为什么这个设计是为了使用1900年.我怀疑基本的答案是"因为我们在设计时不太擅长API设计tm." 我认为,就日期和时间而言,我们仍然不擅长API设计,因为有太多不同的用例.

这只是API,而不是内部的存储格式java.util.Date.同样烦人,请注意.