Posts Tagged ‘Day’

Gotcha: Java Calendar class returns 0-based month, but 1-based days

Just noticed that the Java Calendar class breaks the least-user-expected rule (that is don’t make something behave in the least expected way) regarding the indexing of the month value it returns, compared to all other indexed variables it can return (like day of year, day of month, day of week etc.). The former is using a 0-based index, whereas all the others are 1-based.
public int get(int field)
Returns the value of the given calendar field. In lenient mode, all calendar fields are normalized. In non-lenient mode, all calendar fields are validated and this method throws an exception if any calendar fields have out-of-range values. The normalization and validation are handled by the complete() method, which process is calendar system dependent.
field – the given calendar field.
the value for the given calendar field.
public static final int MONTH
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.
public static final int DATE
Field number for get and set indicating the day of the month. This is a synonym for DAY_OF_MONTH. The first day of the month has value 1.
public static final int DAY_OF_MONTH
Field number for get and set indicating the day of the month. This is a synonym for DATE. The first day of the month has value 1.

There is an interesting discussion about this at

At one reads that this confusing setting came from UNIX (similar to those silly command abbreviations [“creat” instead of “create” etc.):

The origins lie with the POSIX

standard functions |ctime|, |gmtime| and |localtime|, which accept or

return a |time_t| structure with the following fields (from man 3 ctime


|int tm_mday;    /* day of month (1 – 31) */

int tm_mon;     /* month of year (0 – 11) */

int tm_year;    /* year – 1900 */


This API was copied pretty much exactly into the Java Date class in Java

1.0, and from there mostly intact into the Calendar class in Java 1.1.

Sun fixed the most glaring problem when they introduced Calendar – the

fact that the year 2001 in the Gregorian calendar was represented by the

value 101 in their Date class. But I’m not sure why they didn’t change

the day and month values to at least both be consistent in their

indexing, either from zero or one. This inconsistency and related

confusion still exists in Java (and C) to this day.”

%d bloggers like this: