Calendar
is an abstract base class for converting between a Date
object and a set of integer fields such as YEAR
, MONTH
, DAY
, HOUR
, and so on. (A Date
object represents a specific instant in time with millisecond precision. See {@link Date}for information about the Date
class.) Note: This class is similar, but not identical, to the class java.util.Calendar
. Changes are detailed below.
Subclasses of Calendar
interpret a Date
according to the rules of a specific calendar system. ICU4J contains several subclasses implementing different international calendar systems.
Like other locale-sensitive classes, Calendar
provides a class method, getInstance
, for getting a generally useful object of this type. Calendar
's getInstance
method returns a calendar of a type appropriate to the locale, whose time fields have been initialized with the current date and time:
Calendar rightNow = Calendar.getInstance()
When a ULocale
is used by getInstance
, its 'calendar
' tag and value are retrieved if present. If a recognized value is supplied, a calendar is provided and configured as appropriate. Currently recognized tags are "buddhist", "chinese", "coptic", "ethiopic", "gregorian", "hebrew", "islamic", "islamic-civil", and "japanese". For example:
will return an instance of JapaneseCalendar (using en_US conventions for minimum days in first week, start day of week, et cetera).Calendar cal = Calendar.getInstance(new ULocale("en_US@calendar=japanese"));
A Calendar
object can produce all the time field values needed to implement the date-time formatting for a particular language and calendar style (for example, Japanese-Gregorian, Japanese-Traditional). Calendar
defines the range of values returned by certain fields, as well as their meaning. For example, the first month of the year has value MONTH
== JANUARY
for all calendars. Other values are defined by the concrete subclass, such as ERA
and YEAR
. See individual field documentation and subclass documentation for details.
When a Calendar
is lenient, it accepts a wider range of field values than it produces. For example, a lenient GregorianCalendar
interprets MONTH
== JANUARY
, DAY_OF_MONTH
== 32 as February 1. A non-lenient GregorianCalendar
throws an exception when given out-of-range field settings. When calendars recompute field values for return by get()
, they normalize them. For example, a GregorianCalendar
always produces DAY_OF_MONTH
values between 1 and the length of the month.
Calendar
defines a locale-specific seven day week using two parameters: the first day of the week and the minimal days in first week (from 1 to 7). These numbers are taken from the locale resource data when a Calendar
is constructed. They may also be specified explicitly through the API.
When setting or getting the WEEK_OF_MONTH
or WEEK_OF_YEAR
fields, Calendar
must determine the first week of the month or year as a reference point. The first week of a month or year is defined as the earliest seven day period beginning on getFirstDayOfWeek()
and containing at least getMinimalDaysInFirstWeek()
days of that month or year. Weeks numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow it. Note that the normalized numbering returned by get()
may be different. For example, a specific Calendar
subclass may designate the week before week 1 of a year as week n of the previous year.
When computing a Date
from time fields, two special circumstances may arise: there may be insufficient information to compute the Date
(such as only year and month but no day in the month), or there may be inconsistent information (such as "Tuesday, July 15, 1996" -- July 15, 1996 is actually a Monday).
Insufficient information. The calendar will use default information to specify the missing fields. This may vary by calendar; for the Gregorian calendar, the default for a field is the same as that of the start of the epoch: i.e., YEAR = 1970, MONTH = JANUARY, DATE = 1, etc.
Inconsistent information. If fields conflict, the calendar will give preference to fields set more recently. For example, when determining the day, the calendar will look for one of the following combinations of fields. The most recent combination, as determined by the most recently set single field, will be used.
For the time of day:MONTH + DAY_OF_MONTH MONTH + WEEK_OF_MONTH + DAY_OF_WEEK MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK DAY_OF_YEAR DAY_OF_WEEK + WEEK_OF_YEAR
HOUR_OF_DAY AM_PM + HOUR
Note: for some non-Gregorian calendars, different fields may be necessary for complete disambiguation. For example, a full specification of the historial Arabic astronomical calendar requires year, month, day-of-month and day-of-week in some cases.
Note: There are certain possible ambiguities in interpretation of certain singular times, which are resolved in the following ways:
The date or time format strings are not part of the definition of a calendar, as those must be modifiable or overridable by the user at runtime. Use {@link DateFormat}to format dates.
Field manipulation methods
Calendar
fields can be changed using three methods: set()
, add()
, and roll()
.
set(f, value)
changes field f
to value
. In addition, it sets an internal member variable to indicate that field f
has been changed. Although field f
is changed immediately, the calendar's milliseconds is not recomputed until the next call to get()
, getTime()
, or getTimeInMillis()
is made. Thus, multiple calls to set()
do not trigger multiple, unnecessary computations. As a result of changing a field using set()
, other fields may also change, depending on the field, the field value, and the calendar system. In addition, get(f)
will not necessarily return value
after the fields have been recomputed. The specifics are determined by the concrete calendar class.
Example: Consider a GregorianCalendar
originally set to August 31, 1999. Calling set(Calendar.MONTH, Calendar.SEPTEMBER)
sets the calendar to September 31, 1999. This is a temporary internal representation that resolves to October 1, 1999 if getTime()
is then called. However, a call to set(Calendar.DAY_OF_MONTH, 30)
before the call to getTime()
sets the calendar to September 30, 1999, since no recomputation occurs after set()
itself.
add(f, delta)
adds delta
to field f
. This is equivalent to calling set(f, get(f) + delta)
with two adjustments:
Add rule 1. The value of field
f
after the call minus the value of fieldf
before the call isdelta
, modulo any overflow that has occurred in fieldf
. Overflow occurs when a field value exceeds its range and, as a result, the next larger field is incremented or decremented and the field value is adjusted back into its range.Add rule 2. If a smaller field is expected to be invariant, but it is impossible for it to be equal to its prior value because of changes in its minimum or maximum after field
f
is changed, then its value is adjusted to be as close as possible to its expected value. A smaller field represents a smaller unit of time.HOUR
is a smaller field thanDAY_OF_MONTH
. No adjustment is made to smaller fields that are not expected to be invariant. The calendar system determines what fields are expected to be invariant.
In addition, unlike set()
, add()
forces an immediate recomputation of the calendar's milliseconds and all fields.
Example: Consider a GregorianCalendar
originally set to August 31, 1999. Calling add(Calendar.MONTH, 13)
sets the calendar to September 30, 2000. Add rule 1 sets the MONTH
field to September, since adding 13 months to August gives September of the next year. Since DAY_OF_MONTH
cannot be 31 in September in a GregorianCalendar
, add rule 2 sets the DAY_OF_MONTH
to 30, the closest possible value. Although it is a smaller field, DAY_OF_WEEK
is not adjusted by rule 2, since it is expected to change when the month changes in a GregorianCalendar
.
roll(f, delta)
adds delta
to field f
without changing larger fields. This is equivalent to calling add(f, delta)
with the following adjustment:
Roll rule. Larger fields are unchanged after the call. A larger field represents a larger unit of time.
DAY_OF_MONTH
is a larger field thanHOUR
.
Example: Consider a GregorianCalendar
originally set to August 31, 1999. Calling roll(Calendar.MONTH, 8)
sets the calendar to April 30, 1999. Add rule 1 sets the MONTH
field to April. Using a GregorianCalendar
, the DAY_OF_MONTH
cannot be 31 in the month April. Add rule 2 sets it to the closest possible value, 30. Finally, the roll rule maintains the YEAR
field value of 1999.
Example: Consider a GregorianCalendar
originally set to Sunday June 6, 1999. Calling roll(Calendar.WEEK_OF_MONTH, -1)
sets the calendar to Tuesday June 1, 1999, whereas calling add(Calendar.WEEK_OF_MONTH, -1)
sets the calendar to Sunday May 30, 1999. This is because the roll rule imposes an additional constraint: The MONTH
must not change when the WEEK_OF_MONTH
is rolled. Taken together with add rule 1, the resultant date must be between Tuesday June 1 and Saturday June 5. According to add rule 2, the DAY_OF_WEEK
, an invariant when changing the WEEK_OF_MONTH
, is set to Tuesday, the closest possible value to Sunday (where Sunday is the first day of the week).
Usage model. To motivate the behavior of add()
and roll()
, consider a user interface component with increment and decrement buttons for the month, day, and year, and an underlying GregorianCalendar
. If the interface reads January 31, 1999 and the user presses the month increment button, what should it read? If the underlying implementation uses set()
, it might read March 3, 1999. A better result would be February 28, 1999. Furthermore, if the user presses the month increment button again, it should read March 31, 1999, not March 28, 1999. By saving the original date and using either add()
or roll()
, depending on whether larger fields should be affected, the user interface can behave as most users will intuitively expect.
Note: You should always use {@link #roll roll} and {@link #add add} ratherthan attempting to perform arithmetic operations directly on the fields of a Calendar. It is quite possible for Calendar subclasses to have fields with non-linear behavior, for example missing months or days during non-leap years. The subclasses' add and roll methods will take this into account, while simple arithmetic manipulations may give invalid results.
Calendar Architecture in ICU4J
Recently the implementation of Calendar
has changed significantly in order to better support subclassing. The original Calendar
class was designed to support subclassing, but it had only one implemented subclass, GregorianCalendar
. With the implementation of several new calendar subclasses, including the BuddhistCalendar
, ChineseCalendar
, HebrewCalendar
, IslamicCalendar
, and JapaneseCalendar
, the subclassing API has been reworked thoroughly. This section details the new subclassing API and other ways in which com.ibm.icu.util.Calendar
differs from java.util.Calendar
.
Changes
Overview of changes between the classic Calendar
architecture and the new architecture.
fields[]
array is private
now instead of protected
. Subclasses must access it using the methods {@link #internalSet} and{@link #internalGet}. Motivation: Subclasses should not directly access data members.time
long word is private
now instead of protected
. Subclasses may access it using the method {@link #internalGetTimeInMillis}, which does not provoke an update. Motivation: Subclasses should not directly access data members.Calendar
base class. As a result, it is much easier to subclass Calendar
. Motivation: Subclasses should not have to reimplement common code. Certain behaviors are common across calendar systems: The definition and behavior of week-related fields and time fields, the arithmetic ( {@link #add(int,int) add} and {@link #roll(int,int) roll}) behavior of many fields, and the field validation system.Calendar
base class contains some Gregorian calendar algorithmic support that subclasses can use (specifically in {@link #handleComputeFields}). Subclasses can use the methods getGregorianXxx()
to obtain precomputed values. Motivation: This is required by all Calendar
subclasses in order to implement consistent time zone behavior, and Gregorian-derived systems can use the already computed data.FIELD_COUNT
constant has been removed. Use {@link #getFieldCount}. In addition, framework API has been added to allow subclasses to define additional fields. Motivation: The number of fields is not constant across calendar systems.Date(Long.MIN_VALUE)
or Date(Long.MAX_VALUE)
. Instead, the Calendar
constants {@link #MIN_DATE}, {@link #MAX_DATE}, {@link #MIN_MILLIS}, {@link #MAX_MILLIS}, {@link #MIN_JULIAN}, and {@link #MAX_JULIAN} should be used. Motivation: Withthe addition of the {@link #JULIAN_DAY} field, Julian daynumbers must be restricted to a 32-bit int
. This restricts the overall supported range. Furthermore, restricting the supported range simplifies the computations by removing special case code that was used to accomodate arithmetic overflow at millis near Long.MIN_VALUE
and Long.MAX_VALUE
.Calendar
.DateFormat
.Subclass API
The original Calendar
API was based on the experience of implementing a only a single subclass, GregorianCalendar
. As a result, all of the subclassing kinks had not been worked out. The new subclassing API has been refined based on several implemented subclasses. This includes methods that must be overridden and methods for subclasses to call. Subclasses no longer have direct access to fields
and stamp
. Instead, they have new API to access these. Subclasses are able to allocate the fields
array through a protected framework method; this allows subclasses to specify additional fields.
More functionality has been moved into the base class. The base class now contains much of the computational machinery to support the Gregorian calendar. This is based on two things: (1) Many calendars are based on the Gregorian calendar (such as the Buddhist and Japanese imperial calendars). (2) All calendars require basic Gregorian support in order to handle timezone computations.
Common computations have been moved into Calendar
. Subclasses no longer compute the week related fields and the time related fields. These are commonly handled for all calendars by the base class.
Subclass computation of time => fields
The {@link #ERA}, {@link #YEAR}, {@link #EXTENDED_YEAR}, {@link #MONTH}, {@link #DAY_OF_MONTH}, and {@link #DAY_OF_YEAR} fields arecomputed by the subclass, based on the Julian day. All other fields are computed by Calendar
.
Calendar
, they must also be computed. These are the only fields that the subclass should compute. All other fields are computed by the base class, so time and week fields behave in a consistent way across all calendars. The default version of this method in Calendar
implements a proleptic Gregorian calendar. Within this method, subclasses may call getGregorianXxx()
to obtain the Gregorian calendar month, day of month, and extended year for the given date.Subclass computation of fields => time
The interpretation of most field values is handled entirely by Calendar
. Calendar
determines which fields are set, which are not, which are set more recently, and so on. In addition, Calendar
handles the computation of the time from the time fields and handles the week-related fields. The only thing the subclass must do is determine the extended year, based on the year fields, and then, given an extended year and a month, it must return a Julian day number.
Other methods
limitType
. This method only needs to handle the fields {@link #ERA}, {@link #YEAR}, {@link #MONTH}, {@link #WEEK_OF_YEAR}, {@link #WEEK_OF_MONTH}, {@link #DAY_OF_MONTH}, {@link #DAY_OF_YEAR}, {@link #DAY_OF_WEEK_IN_MONTH}, {@link #YEAR_WOY}, and {@link #EXTENDED_YEAR}. Other fields are invariant (with respect to calendar system) and are handled by the base class.IllegalArgumentException
. The method may call super.validateField(field)
to handle fields in a generic way, that is, to compare them to the range getMinimum(field)
..getMaximum(field)
.int[]
array large enough to hold the calendar's fields. This is only necessary if the calendar defines additional fields beyond those defined by Calendar
. The length of the result must be at least {@link #BASE_FIELD_COUNT} and no more than{@link #MAX_FIELD_COUNT}.DateFormat
appropriate to this calendar. This is only required if a calendar subclass redefines the use of a field (for example, changes the {@link #ERA} field from a symbolic fieldto a numeric one) or defines an additional field.Normalized behavior
The behavior of certain fields has been made consistent across all calendar systems and implemented in Calendar
.
Calendar
and to maintain basic correpsondences between calendar systems. Affected fields: {@link #AM_PM}, {@link #HOUR}, {@link #HOUR_OF_DAY}, {@link #MINUTE}, {@link #SECOND}, {@link #MILLISECOND}, {@link #ZONE_OFFSET}, and {@link #DST_OFFSET}.GregorianCalendar
fields: the {@link #YEAR}, {@link #MONTH}, and {@link #DAY_OF_MONTH}. As a result, Calendar
always computes these fields, even for non-Gregorian calendar systems. These fields are available to subclasses.WEEK_OF_YEAR, WEEK_OF_MONTH
, {@link #DAY_OF_WEEK_IN_MONTH}, {@link #DOW_LOCAL}, {@link #YEAR_WOY} are all computed ina consistent way in the base class, based on the {@link #EXTENDED_YEAR}, {@link #DAY_OF_YEAR}, {@link #MONTH}, and {@link #DAY_OF_MONTH}, which are computed by the subclass.Supported range
The allowable range of Calendar
has been narrowed. GregorianCalendar
used to attempt to support the range of dates with millisecond values from Long.MIN_VALUE
to Long.MAX_VALUE
. This introduced awkward constructions (hacks) which slowed down performance. It also introduced non-uniform behavior at the boundaries. The new Calendar
protocol specifies the maximum range of supportable dates as those having Julian day numbers of -0x7F000000
to +0x7F000000
. This corresponds to years from ~5,000,000 BCE to ~5,000,000 CE. Programmers should use the constants {@link #MIN_DATE} (or{@link #MIN_MILLIS} or {@link #MIN_JULIAN}) and {@link #MAX_DATE} (or {@link #MAX_MILLIS} or{@link #MAX_JULIAN}) in Calendar
to specify an extremely early or extremely late date.
General notes
GregorianCalendar
class supports dates before the historical onset of the calendar by extending the calendar system backward in time. Similarly, the HebrewCalendar
extends backward before the start of its epoch into zero and negative years. Subclasses do not throw exceptions because a date precedes the historical start of a calendar system. Instead, they implement {@link #handleGetLimit} to return appropriate limits on{@link #YEAR}, {@link #ERA}, etc. fields. Then, if the calendar is set to not be lenient, out-of-range field values will trigger an exception.ERA==AD ? YEAR : 1-YEAR
. Another example is the Mayan long count, which has years (KUN
) and nested cycles of years (KATUN
and BAKTUN
). The Mayan {@link #EXTENDED_YEAR} is computed as TUN + 20 * (KATUN+ 20 * BAKTUN)
. The Calendar
base class uses the {@link #EXTENDED_YEAR} field to compute the week-relatedfields.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|