Why does java.util.Date represent Year as "year-1900"?

EpicPandaForce picture EpicPandaForce · Oct 8, 2014 · Viewed 10.3k times · Source

In 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>.

Of course, in Java 1.1, the getYear() method and the like were deprecated in favor of java.util.Calendar, which still has this weird deprecation note:

 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).

And of course, Month is 0-based but we all know that (although you'd think they had removed that problem from Calendar - they didn't):

 * <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.

I did check the following questions:

Why does Java's Date.getYear() return 111 instead of 2011?

Why is the Java date API (java.util.Date, .Calendar) such a mess?

My question is:

  • What possibly could have the original creators of java.util.Date hoped to gain from storing the data of "year" by subtracting 1900 from it? Especially if it's basically stored as a long.

As such:

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);
    ....
  • Why 1900?

Answer

Jon Skeet picture Jon Skeet · Oct 8, 2014

Basically the original java.util.Date designers copied a lot from C. What you're seeing is the result of that - see the tm struct. So you should probably ask why that was designed to use the year 1900. I suspect the fundamental answer is "because we weren't very good at API design back when tm was designed." I'd contend that we're still not very good at API design when it comes to dates and times, because there are so many different use cases.

This is just the API though, not the storage format inside java.util.Date. No less annoying, mind you.