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

java.util.Date

  * In all methods of class Date that accept or return * year, month, date, hours, minutes, and seconds values, the * following representations are used: * 
    *
  • A year y is represented by the integer * y-1900.

当然,在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删除了这个问题 – 但他们没有):

  * 
  • A month is represented by an integer from 0 to 11; 0 is January, * 1 is February, and so forth; thus 11 is December.
  • 我确实检查了以下问题:

    为什么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); .... 
    • 为什么1900

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

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

    java.util.Date根本没有日期。 特定的即时时间 (引用http://docs.oracle.com/javase/6/docs/api/java/util/Date.html ) ,精确到毫秒

    它与任何特定日期,小时等无关。您可以使用给定的日历和时区从中提取日期,年份等。 不同的日历,时区将提供不同的日期。

    如果您对存储日期(日,月,年)感兴趣,请不要使用java.util.Date

    代替

    • 来自http://www.joda.org/joda-time/的 org.joda.time.DateTime
    • 如果您使用的是java8,请使用java.time包http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html