Odi's astoundingly incomplete notes
New entries | CodeAmbiguous semantics of Calendar.YEAR in GregorianCalendar
Today I had to file a bug report to Sun:
java.util.GregorianCalendar
uses the field Calendar.YEAR
in an ambiguous way. This problem surfaces when dealing with Calendar.WEEK_OF_YEAR
.
Calendar cal = new GregorianCalendar(); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); cal.set(Calendar.YEAR, 2003); cal.set(Calendar.WEEK_OF_YEAR, 1);the YEAR field is interpreted together with the
WEEK_OF_YEAR field
as the year of the WEEK_OF_YEAR
value.
When getting the YEAR
field again:
assertEquals(1, cal.get(Calendar.WEEK_OF_YEAR)); assertEquals(2003, cal.get(Calendar.YEAR));the
YEAR
field is interpreted as the year of the date represented by the calendar.
This introduces a modality in two ways:
- the meaning of
YEAR
is different when setting and when getting - when settingm the meaning of
YEAR
is different depending ifWEEK_OF_YEAR
is set or not
The two years are not the same, which can be verified for Monday of week 1 of year 2003 which is Dec 30 2002.
As you can see, there are clearly two semantically differnt years associated with a calendar but they appear intermixed in one single YEAR
field currently. On reading the year of the week is completely missing and must be determined with some additional functionality outside the Calendar class (see Workaround).
Thus I request that the year of the date and the year belonging to the WEEK_OF_YEAR
be separated into individual fields. A good name would be for instance Calendar.YEAR_OF_WEEK
and Calendar.YEAR_OF_DAY
. Calendar.YEAR
should be deprecated for its ambiguous semantics.
This is related to Bug #4267450 which request a API for reading the year associated with a week in the DateFormat.