Class Calendar
- All Implemented Interfaces:
Serializable
,Cloneable
,Comparable<Calendar>
- Direct Known Subclasses:
ChineseCalendar
,CopticCalendar
,EthiopicCalendar
,GregorianCalendar
,HebrewCalendar
,IndianCalendar
,IslamicCalendar
,PersianCalendar
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
Date
for information about the Date
class.)
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", "japanese", and "roc". 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, some 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),
there may be inconsistent information (such as "Tuesday, July 15, 1996" --
July 15, 1996 is actually a Monday), or the input time might be ambiguous
because of time zone transition.
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
Ambiguous Wall Clock Time. When time offset from UTC has changed, it produces an ambiguous time slot around the transition. For example, many US locations observe daylight saving time. On the date switching to daylight saving time in US, wall clock time jumps from 12:59 AM (standard) to 2:00 AM (daylight). Therefore, wall clock time from 1:00 AM to 1:59 AM do not exist on the date. When the input wall time fall into this missing time slot, the ICU Calendar resolves the time using the UTC offset before the transition by default. In this example, 1:30 AM is interpreted as 1:30 AM standard time (non-exist), so the final result will be 2:30 AM daylight time.
On the date switching back to standard time, wall clock time is moved back one hour at 2:00 AM. So wall clock time from 1:00 AM to 1:59 AM occur twice. In this case, the ICU Calendar resolves the time using the UTC offset after the transition by default. For example, 1:30 AM on the date is resolved as 1:30 AM standard time.
Ambiguous wall clock time resolution behaviors can be customized by Calendar APIs
setRepeatedWallTimeOption(int)
and setSkippedWallTimeOption(int)
.
These methods are available in ICU 49 or later versions.
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:
- 24:00:00 "belongs" to the following day. That is, 23:59 on Dec 31, 1969 < 24:00 on Jan 1, 1970 < 24:01:00 on Jan 1, 1970
- Although historically not precise, midnight also belongs to "am", and noon belongs to "pm", so on the same day, 12:00 am (midnight) < 12:01 am, and 12:00 pm (noon) < 12:01 pm
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 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 roll
and add
rather
than 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.
- The
fields[]
array isprivate
now instead ofprotected
. Subclasses must access it using the methodsinternalSet(int, int)
andinternalGet(int)
. Motivation: Subclasses should not directly access data members. - The
time
long word isprivate
now instead ofprotected
. Subclasses may access it using the methodinternalGetTimeInMillis()
, which does not provoke an update. Motivation: Subclasses should not directly access data members. - The scope of responsibility of subclasses has been drastically
reduced. As much functionality as possible is implemented in the
Calendar
base class. As a result, it is much easier to subclassCalendar
. 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 (add
androll
) behavior of many fields, and the field validation system. - The subclassing API has been completely redesigned.
- The
Calendar
base class contains some Gregorian calendar algorithmic support that subclasses can use (specifically inhandleComputeFields(int)
). Subclasses can use the methodsgetGregorianXxx()
to obtain precomputed values. Motivation: This is required by allCalendar
subclasses in order to implement consistent time zone behavior, and Gregorian-derived systems can use the already computed data. - The
FIELD_COUNT
constant has been removed. UsegetFieldCount()
. 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. - The range of handled dates has been narrowed from +/-
~300,000,000 years to +/- ~5,000,000 years. In practical terms
this should not affect clients. However, it does mean that client
code cannot be guaranteed well-behaved results with dates such as
Date(Long.MIN_VALUE)
orDate(Long.MAX_VALUE)
. Instead, theCalendar
protected constants should be used. Motivation: With the addition of theJULIAN_DAY
field, Julian day numbers must be restricted to a 32-bitint
. This restricts the overall supported range. Furthermore, restricting the supported range simplifies the computations by removing special case code that was used to accommodate arithmetic overflow at millis nearLong.MIN_VALUE
andLong.MAX_VALUE
. - New fields are implemented:
JULIAN_DAY
defines single-field specification of the date.MILLISECONDS_IN_DAY
defines a single-field specification of the wall time.DOW_LOCAL
andYEAR_WOY
implement localized day-of-week and week-of-year behavior. - Subclasses can access protected millisecond constants
defined in
Calendar
. - New API has been added to support calendar-specific subclasses
of
DateFormat
. - Several subclasses have been implemented, representing various international calendar systems.
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 ERA
, YEAR
,
EXTENDED_YEAR
, MONTH
,
DAY_OF_MONTH
, and DAY_OF_YEAR
fields are
computed by the subclass, based on the Julian day. All other fields
are computed by Calendar
.
- Subclasses should implement
handleComputeFields(int)
to compute theERA
,YEAR
,EXTENDED_YEAR
,MONTH
,DAY_OF_MONTH
, andDAY_OF_YEAR
fields, based on the value of theJULIAN_DAY
field. If there are calendar-specific fields not defined byCalendar
, 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 inCalendar
implements a proleptic Gregorian calendar. Within this method, subclasses may callgetGregorianXxx()
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.
- Subclasses should implement
handleGetExtendedYear()
to return the extended year for this calendar system, based on theYEAR
,EXTENDED_YEAR
, and any fields that the calendar system uses that are larger than a year, such asERA
. - Subclasses should implement
handleComputeMonthStart(int, int, boolean)
to return the Julian day number associated with a month and extended year. This is the Julian day number of the day before the first day of the month. The month number is zero-based. This computation should not depend on any field values.
Other methods
- Subclasses should implement
handleGetMonthLength(int, int)
to return the number of days in a given month of a given extended year. The month number, as always, is zero-based. - Subclasses should implement
handleGetYearLength(int)
to return the number of days in the given extended year. This method is used by computeWeekFields to compute theWEEK_OF_YEAR
andYEAR_WOY
fields. - Subclasses should implement
handleGetLimit(int, int)
to return the protected values of a field, depending on the value oflimitType
. This method only needs to handle the fieldsERA
,YEAR
,MONTH
,WEEK_OF_YEAR
,WEEK_OF_MONTH
,DAY_OF_MONTH
,DAY_OF_YEAR
,DAY_OF_WEEK_IN_MONTH
,YEAR_WOY
, andEXTENDED_YEAR
. Other fields are invariant (with respect to calendar system) and are handled by the base class. - Optionally, subclasses may override
validateField(int)
to check any subclass-specific fields. If the field's value is out of range, the method should throw anIllegalArgumentException
. The method may callsuper.validateField(field)
to handle fields in a generic way, that is, to compare them to the rangegetMinimum(field)
..getMaximum(field)
. - Optionally, subclasses may override
handleCreateFields()
to create anint[]
array large enough to hold the calendar's fields. This is only necessary if the calendar defines additional fields beyond those defined byCalendar
. The length of the result must be be between the base and maximum field counts. - Optionally, subclasses may override
handleGetDateFormat(java.lang.String, java.util.Locale)
to create aDateFormat
appropriate to this calendar. This is only required if a calendar subclass redefines the use of a field (for example, changes theERA
field from a symbolic field to a numeric one) or defines an additional field. - Optionally, subclasses may override
roll
andadd
to handle fields that are discontinuous. For example, in the Hebrew calendar the month "Adar I" only occurs in leap years; in other years the calendar jumps from Shevat (month #4) to Adar (month #6). TheHebrewCalendar.add
andHebrewCalendar.roll
methods take this into account, so that adding 1 month to Shevat gives the proper result (Adar) in a non-leap year. The protected utility methodpinField
is often useful when implementing these two methods.
Normalized behavior
The behavior of certain fields has been made consistent across all
calendar systems and implemented in Calendar
.
- Time is normalized. Even though some calendar systems transition
between days at sunset or at other times, all ICU4J calendars
transition between days at local zone midnight. This
allows ICU4J to centralize the time computations in
Calendar
and to maintain basic correspondences between calendar systems. Affected fields:AM_PM
,HOUR
,HOUR_OF_DAY
,MINUTE
,SECOND
,MILLISECOND
,ZONE_OFFSET
, andDST_OFFSET
. - DST behavior is normalized. Daylight savings time behavior is
computed the same for all calendar systems, and depends on the
value of several
GregorianCalendar
fields: theYEAR
,MONTH
, andDAY_OF_MONTH
. As a result,Calendar
always computes these fields, even for non-Gregorian calendar systems. These fields are available to subclasses. - Weeks are normalized. Although locales define the week
differently, in terms of the day on which it starts, and the
designation of week number one of a month or year, they all use a
common mechanism. Furthermore, the day of the week has a simple
and consistent definition throughout history. For example,
although the Gregorian calendar introduced a discontinuity when
first instituted, the day of week was not disrupted. For this
reason, the fields
DAY_OF_WEEK
,WEEK_OF_YEAR, WEEK_OF_MONTH
,DAY_OF_WEEK_IN_MONTH
,DOW_LOCAL
,YEAR_WOY
are all computed in a consistent way in the base class, based on theEXTENDED_YEAR
,DAY_OF_YEAR
,MONTH
, andDAY_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,800,000 BCE to ~5,800,000 CE. Programmers
should use the protected constants in Calendar
to
specify an extremely early or extremely late date.
General notes
- Calendars implementations are proleptic. For example,
even though the Gregorian calendar was not instituted until the
16th century, the
GregorianCalendar
class supports dates before the historical onset of the calendar by extending the calendar system backward in time. Similarly, theHebrewCalendar
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 implementhandleGetLimit(int, int)
to return appropriate limits onYEAR
,ERA
, etc. fields. Then, if the calendar is set to not be lenient, out-of-range field values will trigger an exception. - Calendar system subclasses compute a extended
year. This differs from the
YEAR
field in that it ranges over all integer values, including zero and negative values, and it encapsulates the information of theYEAR
field and all larger fields. Thus, for the Gregorian calendar, theEXTENDED_YEAR
is computed asERA==AD ? YEAR : 1-YEAR
. Another example is the Mayan long count, which has years (KUN
) and nested cycles of years (KATUN
andBAKTUN
). The MayanEXTENDED_YEAR
is computed asTUN + 20 * (KATUN + 20 * BAKTUN)
. TheCalendar
base class uses theEXTENDED_YEAR
field to compute the week-related fields.
- Author:
- Mark Davis, Deborah Goldsmith, Chen-Lieh Huang, Alan Liu, Laura Werner
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic class
Deprecated.This API is ICU internal only.static final class
Simple, immutable struct-like class for access to the CLDR week data. -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final int
Value of theAM_PM
field indicating the period of the day from midnight to just before noon.static final int
Field number forget
andset
indicating whether theHOUR
is before or after noon.static final int
Value of theMONTH
field indicating the fourth month of the year.static final int
Value of theMONTH
field indicating the eighth month of the year.protected static final int
Deprecated.ICU 58 The numeric value may change over time, see ICU ticket #12420.static final int
Field number forget
andset
indicating the day of the month.static final int
Field number forget
andset
indicating the day of the month.static final int
Field number forget
andset
indicating the day of the week.static final int
Field number forget
andset
indicating the ordinal number of the day of the week within the current month.static final int
Field number forget
andset
indicating the day number within the current year.static final int
Value of theMONTH
field indicating the twelfth month of the year.static final int
Field number forget()
andset()
indicating the localized day of week.static final int
Field number forget
andset
indicating the daylight savings offset in milliseconds.protected static final int
The Julian day of the epoch, that is, January 1, 1970 on the Gregorian calendar.static final int
Field number forget
andset
indicating the era, e.g., AD or BC in the Julian calendar.static final int
Field number forget()
andset()
indicating the extended year.static final int
Value of theMONTH
field indicating the second month of the year.static final int
Value of theDAY_OF_WEEK
field indicating Friday.protected static final int
Limit type forgetLimit()
andhandleGetLimit()
indicating the greatest minimum value that a field can take.static final int
Field number forget
andset
indicating the hour of the morning or afternoon.static final int
Field number forget
andset
indicating the hour of the day.protected static final int
Value of the time stampstamp[]
indicating that a field has been set via computations from the time or from other fields.static final int
Field indicating whether or not the current month is a leap month.protected static final int
The Julian day of the Gregorian epoch, that is, January 1, 1 on the Gregorian calendar.static final int
Value of theMONTH
field indicating the first month of the year.static final int
Field number forget()
andset()
indicating the modified Julian day number.static final int
Value of theMONTH
field indicating the seventh month of the year.static final int
Value of theMONTH
field indicating the sixth month of the year.protected static final int
Limit type forgetLimit()
andhandleGetLimit()
indicating the least maximum value that a field can take.static final int
Value of theMONTH
field indicating the third month of the year.protected static final Date
The maximum supportedDate
.protected static final int
Deprecated.ICU 58 The numeric value may change over time, see ICU ticket #12420.protected static final int
The maximum supported Julian day.protected static final long
The maximum supported epoch milliseconds.protected static final int
Limit type forgetLimit()
andhandleGetLimit()
indicating the maximum value that a field can take (greatest maximum).static final int
Value of theMONTH
field indicating the fifth month of the year.static final int
Field number forget
andset
indicating the millisecond within the second.static final int
Field number forget()
andset()
indicating the milliseconds in the day.protected static final Date
The minimum supportedDate
.protected static final int
The minimum supported Julian day.protected static final long
The minimum supported epoch milliseconds.protected static final int
Limit type forgetLimit()
andhandleGetLimit()
indicating the minimum value that a field can take (least minimum).protected static final int
If the time stampstamp[]
has a value greater than or equal toMINIMUM_USER_SET
then it has been set by the user via a call toset()
.static final int
Field number forget
andset
indicating the minute within the hour.static final int
Value of theDAY_OF_WEEK
field indicating Monday.static final int
Field number forget
andset
indicating the month.static final int
Value of theMONTH
field indicating the eleventh month of the year.static final int
Value of theMONTH
field indicating the tenth month of the year.protected static final long
The number of milliseconds in one day.protected static final int
The number of milliseconds in one hour.protected static final int
The number of milliseconds in one minute.protected static final int
The number of milliseconds in one second.protected static final long
The number of milliseconds in one week.static final int
Value of theAM_PM
field indicating the period of the day from noon to just before midnight.protected static final int
Value to OR against resolve table field values for remapping.static final int
Value of theDAY_OF_WEEK
field indicating Saturday.static final int
Field number forget
andset
indicating the second within the minute.static final int
Value of theMONTH
field indicating the ninth month of the year.static final int
Value of theDAY_OF_WEEK
field indicating Sunday.static final int
Value of theDAY_OF_WEEK
field indicating Thursday.static final int
Value of theDAY_OF_WEEK
field indicating Tuesday.static final int
Value of theMONTH
field indicating the thirteenth month of the year.protected static final int
Value of the time stampstamp[]
indicating that a field has not been set since the last call toclear()
.static final int
Option used bysetRepeatedWallTimeOption(int)
andsetSkippedWallTimeOption(int)
specifying an ambiguous wall time to be interpreted as the earliest.static final int
Option used bysetRepeatedWallTimeOption(int)
andsetSkippedWallTimeOption(int)
specifying an ambiguous wall time to be interpreted as the latest.static final int
Option used bysetSkippedWallTimeOption(int)
specifying an ambiguous wall time to be interpreted as the next valid wall time.static final int
Value of theDAY_OF_WEEK
field indicating Wednesday.static final int
Field number forget
andset
indicating the week number within the current month.static final int
Field number forget
andset
indicating the week number within the current year.static final int
Deprecated.static final int
Deprecated.static final int
Deprecated.static final int
Deprecated.static final int
Field number forget
andset
indicating the year.static final int
Field number forget()
andset()
indicating the extended year corresponding to theWEEK_OF_YEAR
field.static final int
Field number forget
andset
indicating the raw offset from GMT in milliseconds. -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotected
Calendar()
Constructs a Calendar with the default time zone and the defaultFORMAT
locale.protected
Constructs a calendar with the specified time zone and locale.protected
Constructs a calendar with the specified time zone and locale. -
Method Summary
Modifier and TypeMethodDescriptionvoid
add
(int field, int amount) Add a signed amount to a specified field, using this calendar's rules.boolean
Compares the time field records.boolean
Compares the time field records.final void
clear()
Clears the values of all the time fields.final void
clear
(int field) Clears the value in the given time field.clone()
Overrides Cloneableint
Compares the times (in millis) represented by twoCalendar
objects.protected void
complete()
Fills in any unset fields in the time field list.protected void
Converts the current millisecond time valuetime
to field values infields[]
.protected final void
computeGregorianFields
(int julianDay) Compute the Gregorian calendar year, month, and day of month from the Julian day.protected int
computeGregorianMonthStart
(int year, int month) Compute the Julian day of a month of the Gregorian calendar.protected int
Compute the Julian day number as specified by this calendar's fields.protected int
Deprecated.ICU 60protected long
Deprecated.This API is ICU internal only.protected void
Converts the current field values infields[]
to the millisecond time valuetime
.protected int
computeZoneOffset
(long millis, int millisInDay) Deprecated.ICU 60protected int
computeZoneOffset
(long millis, long millisInDay) Deprecated.This API is ICU internal only.boolean
Compares this calendar to the specified object.int
fieldDifference
(Date when, int field) Returns the difference between the given time and the time this calendar object is set to.protected String
fieldName
(int field) Returns a string name for a field, for debugging and exceptions.protected static final int
floorDivide
(int numerator, int denominator) Divide two integers, returning the floor of the quotient.protected static final int
floorDivide
(int numerator, int denominator, int[] remainder) Divide two integers, returning the floor of the quotient, and the modulus remainder.protected static final int
floorDivide
(long numerator, int denominator, int[] remainder) Divide two integers, returning the floor of the quotient, and the modulus remainder.protected static final long
floorDivide
(long numerator, long denominator) Divide two long integers, returning the floor of the quotient.final int
get
(int field) Returns the value for a given time field.int
getActualMaximum
(int field) Returns the maximum value that this field could have, given the current date.int
getActualMinimum
(int field) Returns the minimum value that this field could have, given the current date.static Locale[]
Returns the list of locales for which Calendars are installed.static ULocale[]
Returns the list of locales for which Calendars are installed.static String
getDateAtTimePattern
(Calendar cal, ULocale uLocale, int dateStyle) Deprecated.This API is ICU internal only.getDateTimeFormat
(int dateStyle, int timeStyle, ULocale loc) Returns aDateFormat
appropriate to this calendar.getDateTimeFormat
(int dateStyle, int timeStyle, Locale loc) Returns aDateFormat
appropriate to this calendar.static String
getDateTimePattern
(Calendar cal, ULocale uLocale, int dateStyle) Deprecated.This API is ICU internal only.int
getDayOfWeekType
(int dayOfWeek) Deprecated.protected int
getDefaultDayInMonth
(int extendedYear, int month) Subclasses may override this.protected int
getDefaultMonthInYear
(int extendedYear) Subclasses may override this.getDisplayName
(ULocale loc) Returns the name of this calendar in the language of the given locale.getDisplayName
(Locale loc) Returns the name of this calendar in the language of the given locale.final int
Returns the number of fields defined by this calendar.protected int[][][]
Returns the field resolution array for this calendar.int
final int
getGreatestMinimum
(int field) Returns the highest minimum value for the given field if varies.protected final int
Returns the day of month (1-based) on the Gregorian calendar as computed bycomputeGregorianFields()
.protected final int
Returns the day of year (1-based) on the Gregorian calendar as computed bycomputeGregorianFields()
.protected final int
Returns the month (0-based) on the Gregorian calendar as computed bycomputeGregorianFields()
.protected final int
Returns the extended year on the Gregorian calendar as computed bycomputeGregorianFields()
.static Calendar
Returns a calendar using the default time zone and locale.static Calendar
getInstance
(TimeZone zone) Returns a calendar using the specified time zone and default locale.static Calendar
getInstance
(TimeZone zone, ULocale locale) Returns a calendar with the specified time zone and locale.static Calendar
getInstance
(TimeZone zone, Locale aLocale) Returns a calendar with the specified time zone and locale.static Calendar
getInstance
(ULocale locale) Returns a calendar using the default time zone and specified locale.static Calendar
getInstance
(Locale aLocale) Returns a calendar using the default time zone and specified locale.static final String[]
getKeywordValuesForLocale
(String key, ULocale locale, boolean commonlyUsed) Given a key and a locale, returns an array of string values in a preferred order that would make a difference.final int
getLeastMaximum
(int field) Returns the lowest maximum value for the given field if varies.protected int
getLimit
(int field, int limitType) Returns a limit for a field.final ULocale
getLocale
(ULocale.Type type) Returns the locale that was used to create this object, or null.final int
getMaximum
(int field) Returns the maximum value for the given time field.int
Returns what the minimal days required in the first week of the year are.final int
getMinimum
(int field) Returns the minimum value for the given time field.final int
Deprecated.This API is ICU internal only.int
Gets the behavior for handling wall time repeating multiple times at negative time zone offset transitions.int
Gets the behavior for handling skipped wall time at positive time zone offset transitions.protected final int
getStamp
(int field) Returns the timestamp of a field.final Date
getTime()
Returns this Calendar's current time.long
Returns this Calendar's current time as a long.Returns the time zone.getType()
Returns the calendar type name string for this Calendar object.Return simple, immutable struct-like class for access to the week data in this calendar.static Calendar.WeekData
getWeekDataForRegion
(String region) Return simple, immutable struct-like class for access to the CLDR week data.int
getWeekendTransition
(int dayOfWeek) Deprecated.protected static final int
gregorianMonthLength
(int y, int m) Returns the length of a month of the Gregorian calendar.protected static final int
gregorianPreviousMonthLength
(int y, int m) Returns the length of a previous month of the Gregorian calendar.protected void
handleComputeFields
(int julianDay) Subclasses may override this method to compute several fields specific to each calendar system.protected int
handleComputeJulianDay
(int bestField) Subclasses may override this.protected abstract int
handleComputeMonthStart
(int eyear, int month, boolean useMonth) Returns the Julian day number of day before the first day of the given month in the given extended year.protected int[]
Subclasses that use additional fields beyond those defined inCalendar
should override this method to return anint[]
array of the appropriate length.protected DateFormat
handleGetDateFormat
(String pattern, ULocale locale) Creates aDateFormat
appropriate to this calendar.protected DateFormat
handleGetDateFormat
(String pattern, String override, ULocale locale) Creates aDateFormat
appropriate to this calendar.protected DateFormat
handleGetDateFormat
(String pattern, String override, Locale locale) Creates aDateFormat
appropriate to this calendar.protected DateFormat
handleGetDateFormat
(String pattern, Locale locale) Creates aDateFormat
appropriate to this calendar.protected abstract int
Returns the extended year defined by the current fields.protected abstract int
handleGetLimit
(int field, int limitType) Subclass API for defining limits of different types.protected int
handleGetMonthLength
(int extendedYear, int month) Returns the number of days in the given month of the given extended year of this calendar system.protected int
handleGetYearLength
(int eyear) Returns the number of days in the given extended year of this calendar system.int
hashCode()
Returns a hash code for this calendar.boolean
Deprecated.This API is ICU internal only.protected final int
internalGet
(int field) Returns the value for a given time field.protected final int
internalGet
(int field, int defaultValue) Returns the value for a given time field, or return the given default value if the field is not set.protected final long
Returns the current milliseconds without recomputing.protected final void
internalSet
(int field, int value) Set a field to a value.boolean
isEquivalentTo
(Calendar other) Returns true if the given Calendar object is equivalent to this one.protected static final boolean
isGregorianLeapYear
(int year) Determines if the given year is a leap year.boolean
Tell whether date/time interpretation is to be lenient.final boolean
isSet
(int field) Determines if the given time field has a value set.boolean
Returns true if this Calendar's current date and time is in the weekend in this calendar system.boolean
Returns true if the given date and time is in the weekend in this calendar system.protected static final int
julianDayToDayOfWeek
(int julian) Returns the day of week, from SUNDAY to SATURDAY, given a Julian day.protected static final long
julianDayToMillis
(int julian) Converts Julian day to time as milliseconds.protected static final int
millisToJulianDay
(long millis) Converts time as milliseconds to Julian day.protected int
newerField
(int defaultField, int alternateField) Returns the field that is newer, either defaultField, or alternateField.protected int
newestStamp
(int first, int last, int bestStampSoFar) Returns the newest stamp of a given range of fields.protected void
pinField
(int field) Adjust the specified field so that it is within the allowable range for the date to which this calendar is set.protected void
prepareGetActual
(int field, boolean isMinimum) Prepare this calendar for computing the actual minimum or maximum.protected int
resolveFields
(int[][][] precedenceTable) Given a precedence table, return the newest field combination in the table, or -1 if none is found.final void
roll
(int field, boolean up) Rolls (up/down) a single unit of time on the given field.void
roll
(int field, int amount) Rolls (up/down) a specified amount time on the given field.final void
set
(int field, int value) Sets the time field with the given value.final void
set
(int year, int month, int date) Sets the values for the fields year, month, and date.final void
set
(int year, int month, int date, int hour, int minute) Sets the values for the fields year, month, date, hour, and minute.final void
set
(int year, int month, int date, int hour, int minute, int second) Sets the values for the fields year, month, date, hour, minute, and second.void
setFirstDayOfWeek
(int value) void
setLenient
(boolean lenient) Specify whether or not date/time interpretation is to be lenient.void
setMinimalDaysInFirstWeek
(int value) Sets what the minimal days required in the first week of the year are.final void
setRelatedYear
(int year) Deprecated.This API is ICU internal only.void
setRepeatedWallTimeOption
(int option) Sets the behavior for handling wall time repeating multiple times at negative time zone offset transitions.void
setSkippedWallTimeOption
(int option) Sets the behavior for handling skipped wall time at positive time zone offset transitions.final void
Sets this Calendar's current time with the given Date.void
setTimeInMillis
(long millis) Sets this Calendar's current time from the given long value.void
setTimeZone
(TimeZone value) Sets the time zone with the given time zone value.setWeekData
(Calendar.WeekData wdata) Set data in this calendar based on the WeekData input.toString()
Returns a string representation of this calendar.protected void
validateField
(int field) Validate a single field of this calendar.protected final void
validateField
(int field, int min, int max) Validate a single field of this calendar given its minimum and maximum allowed value.protected void
Ensure that each field is within its valid range by callingvalidateField(int)
on each field that has been set.protected final int
weekNumber
(int dayOfPeriod, int dayOfWeek) Returns the week number of a day, within a period.protected int
weekNumber
(int desiredDay, int dayOfPeriod, int dayOfWeek) Returns the week number of a day, within a period.
-
Field Details
-
ERA
public static final int ERAField number forget
andset
indicating the era, e.g., AD or BC in the Julian calendar. This is a calendar-specific value; see subclass documentation.- See Also:
-
YEAR
public static final int YEARField number forget
andset
indicating the year. This is a calendar-specific value; see subclass documentation.- See Also:
-
MONTH
public static final int MONTHField number forget
andset
indicating the month. This is a calendar-specific value. The first month of the year isJANUARY
; the last depends on the number of months in a year.- See Also:
-
WEEK_OF_YEAR
public static final int WEEK_OF_YEARField number forget
andset
indicating the week number within the current year. The first week of the year, as defined bygetFirstDayOfWeek()
andgetMinimalDaysInFirstWeek()
, has value 1. Subclasses define the value ofWEEK_OF_YEAR
for days before the first week of the year.- See Also:
-
WEEK_OF_MONTH
public static final int WEEK_OF_MONTHField number forget
andset
indicating the week number within the current month. The first week of the month, as defined bygetFirstDayOfWeek()
andgetMinimalDaysInFirstWeek()
, has value 1. Subclasses define the value ofWEEK_OF_MONTH
for days before the first week of the month.- See Also:
-
DATE
public static final int DATEField number forget
andset
indicating the day of the month. This is a synonym forDAY_OF_MONTH
. The first day of the month has value 1.- See Also:
-
DAY_OF_MONTH
public static final int DAY_OF_MONTHField number forget
andset
indicating the day of the month. This is a synonym forDATE
. The first day of the month has value 1.- See Also:
-
DAY_OF_YEAR
public static final int DAY_OF_YEARField number forget
andset
indicating the day number within the current year. The first day of the year has value 1.- See Also:
-
DAY_OF_WEEK
public static final int DAY_OF_WEEKField number forget
andset
indicating the day of the week. This field takes valuesSUNDAY
,MONDAY
,TUESDAY
,WEDNESDAY
,THURSDAY
,FRIDAY
, andSATURDAY
.- See Also:
-
DAY_OF_WEEK_IN_MONTH
public static final int DAY_OF_WEEK_IN_MONTHField number forget
andset
indicating the ordinal number of the day of the week within the current month. Together with theDAY_OF_WEEK
field, this uniquely specifies a day within a month. UnlikeWEEK_OF_MONTH
andWEEK_OF_YEAR
, this field's value does not depend ongetFirstDayOfWeek()
orgetMinimalDaysInFirstWeek()
.DAY_OF_MONTH 1
through7
always correspond toDAY_OF_WEEK_IN_MONTH 1
;8
through15
correspond toDAY_OF_WEEK_IN_MONTH 2
, and so on.DAY_OF_WEEK_IN_MONTH 0
indicates the week beforeDAY_OF_WEEK_IN_MONTH 1
. Negative values count back from the end of the month, so the last Sunday of a month is specified asDAY_OF_WEEK = SUNDAY, DAY_OF_WEEK_IN_MONTH = -1
. Because negative values count backward they will usually be aligned differently within the month than positive values. For example, if a month has 31 days,DAY_OF_WEEK_IN_MONTH -1
will overlapDAY_OF_WEEK_IN_MONTH 5
and the end of4
.- See Also:
-
AM_PM
public static final int AM_PMField number forget
andset
indicating whether theHOUR
is before or after noon. E.g., at 10:04:15.250 PM theAM_PM
isPM
.- See Also:
-
HOUR
public static final int HOURField number forget
andset
indicating the hour of the morning or afternoon.HOUR
is used for the 12-hour clock. E.g., at 10:04:15.250 PM theHOUR
is 10.- See Also:
-
HOUR_OF_DAY
public static final int HOUR_OF_DAYField number forget
andset
indicating the hour of the day.HOUR_OF_DAY
is used for the 24-hour clock. E.g., at 10:04:15.250 PM theHOUR_OF_DAY
is 22.- See Also:
-
MINUTE
public static final int MINUTEField number forget
andset
indicating the minute within the hour. E.g., at 10:04:15.250 PM theMINUTE
is 4.- See Also:
-
SECOND
public static final int SECONDField number forget
andset
indicating the second within the minute. E.g., at 10:04:15.250 PM theSECOND
is 15.- See Also:
-
MILLISECOND
public static final int MILLISECONDField number forget
andset
indicating the millisecond within the second. E.g., at 10:04:15.250 PM theMILLISECOND
is 250.- See Also:
-
ZONE_OFFSET
public static final int ZONE_OFFSETField number forget
andset
indicating the raw offset from GMT in milliseconds.- See Also:
-
DST_OFFSET
public static final int DST_OFFSETField number forget
andset
indicating the daylight savings offset in milliseconds.- See Also:
-
YEAR_WOY
public static final int YEAR_WOYField number forget()
andset()
indicating the extended year corresponding to theWEEK_OF_YEAR
field. This may be one greater or less than the value ofEXTENDED_YEAR
.- See Also:
-
DOW_LOCAL
public static final int DOW_LOCALField number forget()
andset()
indicating the localized day of week. This will be a value from 1 to 7 inclusive, with 1 being the localized first day of the week.- See Also:
-
EXTENDED_YEAR
public static final int EXTENDED_YEARField number forget()
andset()
indicating the extended year. This is a single number designating the year of this calendar system, encompassing all supra-year fields. For example, for the Julian calendar system, year numbers are positive, with an era of BCE or CE. An extended year value for the Julian calendar system assigns positive values to CE years and negative values to BCE years, with 1 BCE being year 0.- See Also:
-
JULIAN_DAY
public static final int JULIAN_DAYField number forget()
andset()
indicating the modified Julian day number. This is different from the conventional Julian day number in two regards. First, it demarcates days at local zone midnight, rather than noon GMT. Second, it is a local number; that is, it depends on the local time zone. It can be thought of as a single number that encompasses all the date-related fields.- See Also:
-
MILLISECONDS_IN_DAY
public static final int MILLISECONDS_IN_DAYField number forget()
andset()
indicating the milliseconds in the day. This ranges from 0 to 23:59:59.999 (regardless of DST). This field behaves exactly like a composite of all time-related fields, not including the zone fields. As such, it also reflects discontinuities of those fields on DST transition days. On a day of DST onset, it will jump forward. On a day of DST cessation, it will jump backward. This reflects the fact that is must be combined with the DST_OFFSET field to obtain a unique local time value.- See Also:
-
IS_LEAP_MONTH
public static final int IS_LEAP_MONTHField indicating whether or not the current month is a leap month. Should have a value of 0 for non-leap months, and 1 for leap months.- See Also:
-
BASE_FIELD_COUNT
Deprecated.ICU 58 The numeric value may change over time, see ICU ticket #12420.The number of fields defined by this class. Subclasses may define addition fields starting with this number.- See Also:
-
MAX_FIELD_COUNT
Deprecated.ICU 58 The numeric value may change over time, see ICU ticket #12420.The maximum number of fields possible. Subclasses must not define more total fields than this number.- See Also:
-
SUNDAY
public static final int SUNDAYValue of theDAY_OF_WEEK
field indicating Sunday.- See Also:
-
MONDAY
public static final int MONDAYValue of theDAY_OF_WEEK
field indicating Monday.- See Also:
-
TUESDAY
public static final int TUESDAYValue of theDAY_OF_WEEK
field indicating Tuesday.- See Also:
-
WEDNESDAY
public static final int WEDNESDAYValue of theDAY_OF_WEEK
field indicating Wednesday.- See Also:
-
THURSDAY
public static final int THURSDAYValue of theDAY_OF_WEEK
field indicating Thursday.- See Also:
-
FRIDAY
public static final int FRIDAYValue of theDAY_OF_WEEK
field indicating Friday.- See Also:
-
SATURDAY
public static final int SATURDAYValue of theDAY_OF_WEEK
field indicating Saturday.- See Also:
-
JANUARY
public static final int JANUARYValue of theMONTH
field indicating the first month of the year.- See Also:
-
FEBRUARY
public static final int FEBRUARYValue of theMONTH
field indicating the second month of the year.- See Also:
-
MARCH
public static final int MARCHValue of theMONTH
field indicating the third month of the year.- See Also:
-
APRIL
public static final int APRILValue of theMONTH
field indicating the fourth month of the year.- See Also:
-
MAY
public static final int MAYValue of theMONTH
field indicating the fifth month of the year.- See Also:
-
JUNE
public static final int JUNEValue of theMONTH
field indicating the sixth month of the year.- See Also:
-
JULY
public static final int JULYValue of theMONTH
field indicating the seventh month of the year.- See Also:
-
AUGUST
public static final int AUGUSTValue of theMONTH
field indicating the eighth month of the year.- See Also:
-
SEPTEMBER
public static final int SEPTEMBERValue of theMONTH
field indicating the ninth month of the year.- See Also:
-
OCTOBER
public static final int OCTOBERValue of theMONTH
field indicating the tenth month of the year.- See Also:
-
NOVEMBER
public static final int NOVEMBERValue of theMONTH
field indicating the eleventh month of the year.- See Also:
-
DECEMBER
public static final int DECEMBERValue of theMONTH
field indicating the twelfth month of the year.- See Also:
-
UNDECIMBER
public static final int UNDECIMBERValue of theMONTH
field indicating the thirteenth month of the year. AlthoughGregorianCalendar
does not use this value, lunar calendars do.- See Also:
-
AM
public static final int AMValue of theAM_PM
field indicating the period of the day from midnight to just before noon.- See Also:
-
PM
public static final int PMValue of theAM_PM
field indicating the period of the day from noon to just before midnight.- See Also:
-
WEEKDAY
Deprecated.Value returned by getDayOfWeekType(int dayOfWeek) to indicate a weekday.- See Also:
-
WEEKEND
Deprecated.Value returned by getDayOfWeekType(int dayOfWeek) to indicate a weekend day.- See Also:
-
WEEKEND_ONSET
Deprecated.Value returned by getDayOfWeekType(int dayOfWeek) to indicate a day that starts as a weekday and transitions to the weekend. Call getWeekendTransition() to get the point of transition.- See Also:
-
WEEKEND_CEASE
Deprecated.Value returned by getDayOfWeekType(int dayOfWeek) to indicate a day that starts as the weekend and transitions to a weekday. Call getWeekendTransition() to get the point of transition.- See Also:
-
WALLTIME_LAST
public static final int WALLTIME_LASTOption used bysetRepeatedWallTimeOption(int)
andsetSkippedWallTimeOption(int)
specifying an ambiguous wall time to be interpreted as the latest.- See Also:
-
WALLTIME_FIRST
public static final int WALLTIME_FIRSTOption used bysetRepeatedWallTimeOption(int)
andsetSkippedWallTimeOption(int)
specifying an ambiguous wall time to be interpreted as the earliest.- See Also:
-
WALLTIME_NEXT_VALID
public static final int WALLTIME_NEXT_VALIDOption used bysetSkippedWallTimeOption(int)
specifying an ambiguous wall time to be interpreted as the next valid wall time.- See Also:
-
ONE_SECOND
protected static final int ONE_SECONDThe number of milliseconds in one second.- See Also:
-
ONE_MINUTE
protected static final int ONE_MINUTEThe number of milliseconds in one minute.- See Also:
-
ONE_HOUR
protected static final int ONE_HOURThe number of milliseconds in one hour.- See Also:
-
ONE_DAY
protected static final long ONE_DAYThe number of milliseconds in one day. Although ONE_DAY and ONE_WEEK can fit into ints, they must be longs in order to prevent arithmetic overflow when performing (bug 4173516).- See Also:
-
ONE_WEEK
protected static final long ONE_WEEKThe number of milliseconds in one week. Although ONE_DAY and ONE_WEEK can fit into ints, they must be longs in order to prevent arithmetic overflow when performing (bug 4173516).- See Also:
-
JAN_1_1_JULIAN_DAY
protected static final int JAN_1_1_JULIAN_DAYThe Julian day of the Gregorian epoch, that is, January 1, 1 on the Gregorian calendar.- See Also:
-
EPOCH_JULIAN_DAY
protected static final int EPOCH_JULIAN_DAYThe Julian day of the epoch, that is, January 1, 1970 on the Gregorian calendar.- See Also:
-
MIN_JULIAN
protected static final int MIN_JULIANThe minimum supported Julian day. This value is equivalent toMIN_MILLIS
andMIN_DATE
.- See Also:
-
MIN_MILLIS
protected static final long MIN_MILLISThe minimum supported epoch milliseconds. This value is equivalent toMIN_JULIAN
andMIN_DATE
.- See Also:
-
MIN_DATE
-
MAX_JULIAN
protected static final int MAX_JULIANThe maximum supported Julian day. This value is equivalent toMAX_MILLIS
andMAX_DATE
.- See Also:
-
MAX_MILLIS
protected static final long MAX_MILLISThe maximum supported epoch milliseconds. This value is equivalent toMAX_JULIAN
andMAX_DATE
.- See Also:
-
MAX_DATE
-
UNSET
protected static final int UNSETValue of the time stampstamp[]
indicating that a field has not been set since the last call toclear()
.- See Also:
-
INTERNALLY_SET
protected static final int INTERNALLY_SETValue of the time stampstamp[]
indicating that a field has been set via computations from the time or from other fields.- See Also:
-
MINIMUM_USER_STAMP
protected static final int MINIMUM_USER_STAMPIf the time stampstamp[]
has a value greater than or equal toMINIMUM_USER_SET
then it has been set by the user via a call toset()
.- See Also:
-
MINIMUM
protected static final int MINIMUMLimit type forgetLimit()
andhandleGetLimit()
indicating the minimum value that a field can take (least minimum).- See Also:
-
GREATEST_MINIMUM
protected static final int GREATEST_MINIMUMLimit type forgetLimit()
andhandleGetLimit()
indicating the greatest minimum value that a field can take.- See Also:
-
LEAST_MAXIMUM
protected static final int LEAST_MAXIMUMLimit type forgetLimit()
andhandleGetLimit()
indicating the least maximum value that a field can take.- See Also:
-
MAXIMUM
protected static final int MAXIMUMLimit type forgetLimit()
andhandleGetLimit()
indicating the maximum value that a field can take (greatest maximum).- See Also:
-
RESOLVE_REMAP
protected static final int RESOLVE_REMAPValue to OR against resolve table field values for remapping.- See Also:
-
-
Constructor Details
-
Calendar
protected Calendar()Constructs a Calendar with the default time zone and the defaultFORMAT
locale.- See Also:
-
Calendar
Constructs a calendar with the specified time zone and locale.- Parameters:
zone
- the time zone to useaLocale
- the locale for the week data
-
Calendar
Constructs a calendar with the specified time zone and locale.- Parameters:
zone
- the time zone to uselocale
- the ulocale for the week data
-
-
Method Details
-
getInstance
Returns a calendar using the default time zone and locale.- Returns:
- a Calendar.
-
getInstance
Returns a calendar using the specified time zone and default locale.- Parameters:
zone
- the time zone to use- Returns:
- a Calendar.
-
getInstance
Returns a calendar using the default time zone and specified locale.- Parameters:
aLocale
- the locale for the week data- Returns:
- a Calendar.
-
getInstance
Returns a calendar using the default time zone and specified locale.- Parameters:
locale
- the ulocale for the week data- Returns:
- a Calendar.
-
getInstance
Returns a calendar with the specified time zone and locale.- Parameters:
zone
- the time zone to useaLocale
- the locale for the week data- Returns:
- a Calendar.
-
getInstance
Returns a calendar with the specified time zone and locale.- Parameters:
zone
- the time zone to uselocale
- the ulocale for the week data- Returns:
- a Calendar.
-
getAvailableLocales
Returns the list of locales for which Calendars are installed.- Returns:
- the list of locales for which Calendars are installed.
-
getAvailableULocales
Returns the list of locales for which Calendars are installed.- Returns:
- the list of locales for which Calendars are installed.
-
getKeywordValuesForLocale
public static final String[] getKeywordValuesForLocale(String key, ULocale locale, boolean commonlyUsed) Given a key and a locale, returns an array of string values in a preferred order that would make a difference. These are all and only those values where the open (creation) of the service with the locale formed from the input locale plus input keyword and that value has different behavior than creation with the input locale alone.- Parameters:
key
- one of the keys supported by this service. For now, only "calendar" is supported.locale
- the localecommonlyUsed
- if set to true it will return only commonly used values with the given locale in preferred order. Otherwise, it will return all the available values for the locale.- Returns:
- an array of string values for the given key and the locale.
-
getTime
Returns this Calendar's current time.- Returns:
- the current time.
-
setTime
Sets this Calendar's current time with the given Date.Note: Calling
setTime
withDate(Long.MAX_VALUE)
orDate(Long.MIN_VALUE)
may yield incorrect field values fromget(int)
.- Parameters:
date
- the given Date.
-
getTimeInMillis
public long getTimeInMillis()Returns this Calendar's current time as a long.- Returns:
- the current time as UTC milliseconds from the epoch.
-
setTimeInMillis
public void setTimeInMillis(long millis) Sets this Calendar's current time from the given long value. An IllegalIcuArgumentException is thrown when millis is outside the range permitted by a Calendar object when in strict mode. When in lenient mode the out of range values are pinned to their respective min/max.- Parameters:
millis
- the new time in UTC milliseconds from the epoch.
-
get
public final int get(int field) Returns the value for a given time field.- Parameters:
field
- the given time field.- Returns:
- the value for the given time field.
-
internalGet
protected final int internalGet(int field) Returns the value for a given time field. This is an internal method for subclasses that does not trigger any calculations.- Parameters:
field
- the given time field.- Returns:
- the value for the given time field.
-
internalGet
protected final int internalGet(int field, int defaultValue) Returns the value for a given time field, or return the given default value if the field is not set. This is an internal method for subclasses that does not trigger any calculations.- Parameters:
field
- the given time field.defaultValue
- value to return if field is not set- Returns:
- the value for the given time field of defaultValue if the field is unset
-
set
public final void set(int field, int value) Sets the time field with the given value.- Parameters:
field
- the given time field.value
- the value to be set for the given time field.
-
set
public final void set(int year, int month, int date) Sets the values for the fields year, month, and date. Previous values of other fields are retained. If this is not desired, callclear()
first.- Parameters:
year
- the value used to set the YEAR time field.month
- the value used to set the MONTH time field. Month value is 0-based. e.g., 0 for January.date
- the value used to set the DATE time field.
-
set
public final void set(int year, int month, int date, int hour, int minute) Sets the values for the fields year, month, date, hour, and minute. Previous values of other fields are retained. If this is not desired, callclear()
first.- Parameters:
year
- the value used to set the YEAR time field.month
- the value used to set the MONTH time field. Month value is 0-based. e.g., 0 for January.date
- the value used to set the DATE time field.hour
- the value used to set the HOUR_OF_DAY time field.minute
- the value used to set the MINUTE time field.
-
set
public final void set(int year, int month, int date, int hour, int minute, int second) Sets the values for the fields year, month, date, hour, minute, and second. Previous values of other fields are retained. If this is not desired, callclear()
first.- Parameters:
year
- the value used to set the YEAR time field.month
- the value used to set the MONTH time field. Month value is 0-based. e.g., 0 for January.date
- the value used to set the DATE time field.hour
- the value used to set the HOUR_OF_DAY time field.minute
- the value used to set the MINUTE time field.second
- the value used to set the SECOND time field.
-
getRelatedYear
Deprecated.This API is ICU internal only. -
setRelatedYear
Deprecated.This API is ICU internal only. -
clear
public final void clear()Clears the values of all the time fields. -
clear
public final void clear(int field) Clears the value in the given time field.- Parameters:
field
- the time field to be cleared.
-
isSet
public final boolean isSet(int field) Determines if the given time field has a value set.- Returns:
- true if the given time field has a value set; false otherwise.
-
complete
protected void complete()Fills in any unset fields in the time field list. -
equals
Compares this calendar to the specified object. The result istrue
if and only if the argument is notnull
and is aCalendar
object that represents the same calendar as this object. -
isEquivalentTo
Returns true if the given Calendar object is equivalent to this one. An equivalent Calendar will behave exactly as this one does, but it may be set to a different time. By contrast, for the equals() method to return true, the other Calendar must be set to the same time.- Parameters:
other
- the Calendar to be compared with this Calendar
-
hashCode
public int hashCode()Returns a hash code for this calendar. -
before
Compares the time field records. Equivalent to comparing result of conversion to UTC.- Parameters:
when
- the Calendar to be compared with this Calendar.- Returns:
- true if the current time of this Calendar is before the time of Calendar when; false otherwise.
-
after
Compares the time field records. Equivalent to comparing result of conversion to UTC.- Parameters:
when
- the Calendar to be compared with this Calendar.- Returns:
- true if the current time of this Calendar is after the time of Calendar when; false otherwise.
-
getActualMaximum
public int getActualMaximum(int field) Returns the maximum value that this field could have, given the current date. For example, with the Gregorian date February 3, 1997 and theDAY_OF_MONTH
field, the actual maximum is 28; for February 3, 1996 it is 29.The actual maximum computation ignores smaller fields and the current value of like-sized fields. For example, the actual maximum of the DAY_OF_YEAR or MONTH depends only on the year and supra-year fields. The actual maximum of the DAY_OF_MONTH depends, in addition, on the MONTH field and any other fields at that granularity (such as IS_LEAP_MONTH). The DAY_OF_WEEK_IN_MONTH field does not depend on the current DAY_OF_WEEK; it returns the maximum for any day of week in the current month. Likewise for the WEEK_OF_MONTH and WEEK_OF_YEAR fields.
- Parameters:
field
- the field whose maximum is desired- Returns:
- the maximum of the given field for the current date of this calendar
- See Also:
-
getActualMinimum
public int getActualMinimum(int field) Returns the minimum value that this field could have, given the current date. For most fields, this is the same asgetMinimum
andgetGreatestMinimum
. However, some fields, especially those related to week number, are more complicated.For example, assume
getMinimalDaysInFirstWeek
returns 4 andgetFirstDayOfWeek
returns SUNDAY. If the first day of the month is Sunday, Monday, Tuesday, or Wednesday there will be four or more days in the first week, so it will be week number 1, andgetActualMinimum(WEEK_OF_MONTH)
will return 1. However, if the first of the month is a Thursday, Friday, or Saturday, there are not four days in that week, so it is week number 0, andgetActualMinimum(WEEK_OF_MONTH)
will return 0.- Parameters:
field
- the field whose actual minimum value is desired.- Returns:
- the minimum of the given field for the current date of this calendar
- See Also:
-
prepareGetActual
protected void prepareGetActual(int field, boolean isMinimum) Prepare this calendar for computing the actual minimum or maximum. This method modifies this calendar's fields; it is called on a temporary calendar.Rationale: The semantics of getActualXxx() is to return the maximum or minimum value that the given field can take, taking into account other relevant fields. In general these other fields are larger fields. For example, when computing the actual maximum DAY_OF_MONTH, the current value of DAY_OF_MONTH itself is ignored, as is the value of any field smaller.
The time fields all have fixed minima and maxima, so we don't need to worry about them. This also lets us set the MILLISECONDS_IN_DAY to zero to erase any effects the time fields might have when computing date fields.
DAY_OF_WEEK is adjusted specially for the WEEK_OF_MONTH and WEEK_OF_YEAR fields to ensure that they are computed correctly.
-
roll
public final void roll(int field, boolean up) Rolls (up/down) a single unit of time on the given field. If the field is rolled past its maximum allowable value, it will "wrap" back to its minimum and continue rolling. For example, to roll the current date up by one day, you can call:roll(
DATE
, true)When rolling on the
YEAR
field, it will roll the year value in the range between 1 and the value returned by callinggetMaximum
(YEAR
).When rolling on certain fields, the values of other fields may conflict and need to be changed. For example, when rolling the
MONTH
field for the Gregorian date 1/31/96 upward, theDAY_OF_MONTH
field must be adjusted so that the result is 2/29/96 rather than the invalid 2/31/96.Rolling up always means rolling forward in time (unless the limit of the field is reached, in which case it may pin or wrap), so for the Gregorian calendar, starting with 100 BC and rolling the year up results in 99 BC. When eras have a definite beginning and end (as in the Chinese calendar, or as in most eras in the Japanese calendar) then rolling the year past either limit of the era will cause the year to wrap around. When eras only have a limit at one end, then attempting to roll the year past that limit will result in pinning the year at that limit. Note that for most calendars in which era 0 years move forward in time (such as Buddhist, Hebrew, or Islamic), it is possible for add or roll to result in negative years for era 0 (that is the only way to represent years before the calendar epoch in such calendars).
Note: Calling roll(field, true) N times is not necessarily equivalent to calling roll(field, N). For example, imagine that you start with the date Gregorian date January 31, 1995. If you call roll(Calendar.MONTH, 2), the result will be March 31, 1995. But if you call roll(Calendar.MONTH, true), the result will be February 28, 1995. Calling it one more time will give March 28, 1995, which is usually not the desired result.
Note: You should always use roll and add rather than 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.
- Parameters:
field
- the calendar field to roll.up
- indicates if the value of the specified time field is to be rolled up or rolled down. Usetrue
if rolling up,false
otherwise.- Throws:
IllegalArgumentException
- if the field is invalid or refers to a field that cannot be handled by this method.- See Also:
-
roll
public void roll(int field, int amount) Rolls (up/down) a specified amount time on the given field. For example, to roll the current date up by three days, you can callroll(Calendar.DATE, 3)
. If the field is rolled past its maximum allowable value, it will "wrap" back to its minimum and continue rolling. For example, callingroll(Calendar.DATE, 10)
on a Gregorian calendar set to 4/25/96 will result in the date 4/5/96.When rolling on certain fields, the values of other fields may conflict and need to be changed. For example, when rolling the
MONTH
field for the Gregorian date 1/31/96 by +1, theDAY_OF_MONTH
field must be adjusted so that the result is 2/29/96 rather than the invalid 2/31/96.Rolling by a positive value always means rolling forward in time (unless the limit of the field is reached, in which case it may pin or wrap), so for the Gregorian calendar, starting with 100 BC and rolling the year by + 1 results in 99 BC. When eras have a definite beginning and end (as in the Chinese calendar, or as in most eras in the Japanese calendar) then rolling the year past either limit of the era will cause the year to wrap around. When eras only have a limit at one end, then attempting to roll the year past that limit will result in pinning the year at that limit. Note that for most calendars in which era 0 years move forward in time (such as Buddhist, Hebrew, or Islamic), it is possible for add or roll to result in negative years for era 0 (that is the only way to represent years before the calendar epoch in such calendars).
the ICU implementation of this method is able to roll all fields except for
ERA
,DST_OFFSET
, andZONE_OFFSET
. Subclasses may, of course, add support for additional fields in their overrides ofroll
.Note: You should always use roll and add rather than 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.
Subclassing:
This implementation ofroll
assumes that the behavior of the field is continuous between its minimum and maximum, which are found by callinggetActualMinimum
andgetActualMaximum
. For most such fields, simple addition, subtraction, and modulus operations are sufficient to perform the roll. For week-related fields, the results ofgetFirstDayOfWeek
andgetMinimalDaysInFirstWeek
are also necessary. Subclasses can override these two methods if their values differ from the defaults.Subclasses that have fields for which the assumption of continuity breaks down must override
roll
to handle those fields specially. For example, in the Hebrew calendar the month "Adar I" only occurs in leap years; in other years the calendar jumps from Shevat (month #4) to Adar (month #6). TheHebrewCalendar.roll
method takes this into account, so that rolling the month of Shevat by one gives the proper result (Adar) in a non-leap year.- Parameters:
field
- the calendar field to roll.amount
- the amount by which the field should be rolled.- Throws:
IllegalArgumentException
- if the field is invalid or refers to a field that cannot be handled by this method.- See Also:
-
add
public void add(int field, int amount) Add a signed amount to a specified field, using this calendar's rules. For example, to add three days to the current date, you can calladd(Calendar.DATE, 3)
.When adding to certain fields, the values of other fields may conflict and need to be changed. For example, when adding one to the
MONTH
field for the Gregorian date 1/31/96, theDAY_OF_MONTH
field must be adjusted so that the result is 2/29/96 rather than the invalid 2/31/96.Adding a positive value always means moving forward in time, so for the Gregorian calendar, starting with 100 BC and adding +1 to year results in 99 BC (even though this actually reduces the numeric value of the field itself).
The ICU implementation of this method is able to add to all fields except for
ERA
,DST_OFFSET
, andZONE_OFFSET
. Subclasses may, of course, add support for additional fields in their overrides ofadd
.Note: You should always use roll and add rather than 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.
Subclassing:
This implementation ofadd
assumes that the behavior of the field is continuous between its minimum and maximum, which are found by callinggetActualMinimum
andgetActualMaximum
. For such fields, simple arithmetic operations are sufficient to perform the add.Subclasses that have fields for which this assumption of continuity breaks down must override
add
to handle those fields specially. For example, in the Hebrew calendar the month "Adar I" only occurs in leap years; in other years the calendar jumps from Shevat (month #4) to Adar (month #6). TheHebrewCalendar.add
method takes this into account, so that adding one month to a date in Shevat gives the proper result (Adar) in a non-leap year.- Parameters:
field
- the time field.amount
- the amount to add to the field.- Throws:
IllegalArgumentException
- if the field is invalid or refers to a field that cannot be handled by this method.- See Also:
-
getDisplayName
Returns the name of this calendar in the language of the given locale. -
getDisplayName
Returns the name of this calendar in the language of the given locale. -
compareTo
Compares the times (in millis) represented by twoCalendar
objects.- Specified by:
compareTo
in interfaceComparable<Calendar>
- Parameters:
that
- theCalendar
to compare to this.- Returns:
0
if the time represented by thisCalendar
is equal to the time represented by thatCalendar
, a value less than0
if the time represented by this is before the time represented by that, and a value greater than0
if the time represented by this is after the time represented by that.- Throws:
NullPointerException
- if thatCalendar
is null.IllegalArgumentException
- if the time of thatCalendar
can't be obtained because of invalid calendar values.
-
getDateTimeFormat
Returns aDateFormat
appropriate to this calendar. Subclasses wishing to specialize this behavior should overridehandleGetDateFormat(java.lang.String, java.util.Locale)
. -
getDateTimeFormat
Returns aDateFormat
appropriate to this calendar. Subclasses wishing to specialize this behavior should overridehandleGetDateFormat(java.lang.String, java.util.Locale)
. -
handleGetDateFormat
Creates aDateFormat
appropriate to this calendar. This is a framework method for subclasses to override. This method is responsible for creating the calendar-specific DateFormat and DateFormatSymbols objects as needed.- Parameters:
pattern
- the pattern, specific to theDateFormat
subclasslocale
- the locale for which the symbols should be drawn- Returns:
- a
DateFormat
appropriate to this calendar
-
handleGetDateFormat
Creates aDateFormat
appropriate to this calendar. This is a framework method for subclasses to override. This method is responsible for creating the calendar-specific DateFormat and DateFormatSymbols objects as needed.- Parameters:
pattern
- the pattern, specific to theDateFormat
subclassoverride
- The override string. A numbering system override string can take one of the following forms: 1). If just a numbering system name is specified, it applies to all numeric fields in the date format pattern. 2). To specify an alternate numbering system on a field by field basis, use the field letters from the pattern followed by an = sign, followed by the numbering system name. For example, to specify that just the year be formatted using Hebrew digits, use the override "y=hebr". Multiple overrides can be specified in a single string by separating them with a semi-colon. For example, the override string "m=thai;y=deva" would format using Thai digits for the month and Devanagari digits for the year.locale
- the locale for which the symbols should be drawn- Returns:
- a
DateFormat
appropriate to this calendar
-
handleGetDateFormat
Creates aDateFormat
appropriate to this calendar. This is a framework method for subclasses to override. This method is responsible for creating the calendar-specific DateFormat and DateFormatSymbols objects as needed.- Parameters:
pattern
- the pattern, specific to theDateFormat
subclasslocale
- the locale for which the symbols should be drawn- Returns:
- a
DateFormat
appropriate to this calendar
-
handleGetDateFormat
Creates aDateFormat
appropriate to this calendar. This is a framework method for subclasses to override. This method is responsible for creating the calendar-specific DateFormat and DateFormatSymbols objects as needed.- Parameters:
pattern
- the pattern, specific to theDateFormat
subclasslocale
- the locale for which the symbols should be drawn- Returns:
- a
DateFormat
appropriate to this calendar
-
getDateTimePattern
Deprecated.This API is ICU internal only. -
getDateAtTimePattern
Deprecated.This API is ICU internal only. -
pinField
protected void pinField(int field) Adjust the specified field so that it is within the allowable range for the date to which this calendar is set. For example, in a Gregorian calendar pinning theDAY_OF_MONTH
field for a calendar set to April 31 would cause it to be set to April 30.Subclassing:
This utility method is intended for use by subclasses that need to implement their own overrides ofroll
andadd
.Note:
pinField
is implemented in terms ofgetActualMinimum
andgetActualMaximum
. If either of those methods uses a slow, iterative algorithm for a particular field, it would be unwise to attempt to callpinField
for that field. If you really do need to do so, you should override this method to do something more efficient for that field.- Parameters:
field
- The calendar field whose value should be pinned.- See Also:
-
weekNumber
protected int weekNumber(int desiredDay, int dayOfPeriod, int dayOfWeek) Returns the week number of a day, within a period. This may be the week number in a year or the week number in a month. Usually this will be a value >= 1, but if some initial days of the period are excluded from week 1, becausegetMinimalDaysInFirstWeek
is > 1, then the week number will be zero for those initial days. This method requires the day number and day of week for some known date in the period in order to determine the day of week on the desired day.Subclassing:
This method is intended for use by subclasses in implementing theircomputeTime
and/orcomputeFields
methods. It is often useful ingetActualMinimum
andgetActualMaximum
as well.This variant is handy for computing the week number of some other day of a period (often the first or last day of the period) when its day of the week is not known but the day number and day of week for some other day in the period (e.g. the current date) is known.
- Parameters:
desiredDay
- TheDAY_OF_YEAR
orDAY_OF_MONTH
whose week number is desired. Should be 1 for the first day of the period.dayOfPeriod
- TheDAY_OF_YEAR
orDAY_OF_MONTH
for a day in the period whoseDAY_OF_WEEK
is specified by thedayOfWeek
parameter. Should be 1 for first day of period.dayOfWeek
- TheDAY_OF_WEEK
for the day corresponding to thedayOfPeriod
parameter. 1-based with 1=Sunday.- Returns:
- The week number (one-based), or zero if the day falls before
the first week because
getMinimalDaysInFirstWeek
is more than one.
-
weekNumber
protected final int weekNumber(int dayOfPeriod, int dayOfWeek) Returns the week number of a day, within a period. This may be the week number in a year, or the week number in a month. Usually this will be a value >= 1, but if some initial days of the period are excluded from week 1, becausegetMinimalDaysInFirstWeek
is > 1, then the week number will be zero for those initial days. This method requires the day of week for the given date in order to determine the result.Subclassing:
This method is intended for use by subclasses in implementing theircomputeTime
and/orcomputeFields
methods. It is often useful ingetActualMinimum
andgetActualMaximum
as well.- Parameters:
dayOfPeriod
- TheDAY_OF_YEAR
orDAY_OF_MONTH
whose week number is desired. Should be 1 for the first day of the period.dayOfWeek
- TheDAY_OF_WEEK
for the day corresponding to thedayOfPeriod
parameter. 1-based with 1=Sunday.- Returns:
- The week number (one-based), or zero if the day falls before
the first week because
getMinimalDaysInFirstWeek
is more than one.
-
fieldDifference
Returns the difference between the given time and the time this calendar object is set to. If this calendar is set before the given time, the returned value will be positive. If this calendar is set after the given time, the returned value will be negative. Thefield
parameter specifies the units of the return value. For example, iffieldDifference(when, Calendar.MONTH)
returns 3, then this calendar is set to 3 months beforewhen
, and possibly some additional time less than one month.As a side effect of this call, this calendar is advanced toward
when
by the given amount. That is, calling this method has the side effect of callingadd(field, n)
, wheren
is the return value.Usage: To use this method, call it first with the largest field of interest, then with progressively smaller fields. For example:
int y = cal.fieldDifference(when, Calendar.YEAR); int m = cal.fieldDifference(when, Calendar.MONTH); int d = cal.fieldDifference(when, Calendar.DATE);
computes the difference betweencal
andwhen
in years, months, and days.Note:
fieldDifference()
is asymmetrical. That is, in the following code:cal.setTime(date1); int m1 = cal.fieldDifference(date2, Calendar.MONTH); int d1 = cal.fieldDifference(date2, Calendar.DATE); cal.setTime(date2); int m2 = cal.fieldDifference(date1, Calendar.MONTH); int d2 = cal.fieldDifference(date1, Calendar.DATE);
one might expect thatm1 == -m2 && d1 == -d2
. However, this is not generally the case, because of irregularities in the underlying calendar system (e.g., the Gregorian calendar has a varying number of days per month).- Parameters:
when
- the date to compare this calendar's time tofield
- the field in which to compute the result- Returns:
- the difference, either positive or negative, between
this calendar's time and
when
, in terms offield
.
-
setTimeZone
Sets the time zone with the given time zone value.- Parameters:
value
- the given time zone.
-
getTimeZone
Returns the time zone.- Returns:
- the time zone object associated with this calendar.
-
setLenient
public void setLenient(boolean lenient) Specify whether or not date/time interpretation is to be lenient. With lenient interpretation, a date such as "February 942, 1996" will be treated as being equivalent to the 941st day after February 1, 1996. With strict interpretation, such dates will cause an exception to be thrown.- See Also:
-
isLenient
public boolean isLenient()Tell whether date/time interpretation is to be lenient. -
setRepeatedWallTimeOption
public void setRepeatedWallTimeOption(int option) Sets the behavior for handling wall time repeating multiple times at negative time zone offset transitions. For example, 1:30 AM on November 6, 2011 in US Eastern time (America/New_York) occurs twice; 1:30 AM EDT, then 1:30 AM EST one hour later. WhenWALLTIME_FIRST
is used, the wall time 1:30AM in this example will be interpreted as 1:30 AM EDT (first occurrence). WhenWALLTIME_LAST
is used, it will be interpreted as 1:30 AM EST (last occurrence). The default value isWALLTIME_LAST
.- Parameters:
option
- the behavior for handling repeating wall time, eitherWALLTIME_FIRST
orWALLTIME_LAST
.- Throws:
IllegalArgumentException
- whenoption
is neitherWALLTIME_FIRST
norWALLTIME_LAST
.- See Also:
-
getRepeatedWallTimeOption
public int getRepeatedWallTimeOption()Gets the behavior for handling wall time repeating multiple times at negative time zone offset transitions.- Returns:
- the behavior for handling repeating wall time, either
WALLTIME_FIRST
orWALLTIME_LAST
. - See Also:
-
setSkippedWallTimeOption
public void setSkippedWallTimeOption(int option) Sets the behavior for handling skipped wall time at positive time zone offset transitions. For example, 2:30 AM on March 13, 2011 in US Eastern time (America/New_York) does not exist because the wall time jump from 1:59 AM EST to 3:00 AM EDT. WhenWALLTIME_FIRST
is used, 2:30 AM is interpreted as 30 minutes before 3:00 AM EDT, therefore, it will be resolved as 1:30 AM EST. WhenWALLTIME_LAST
is used, 2:30 AM is interpreted as 31 minutes after 1:59 AM EST, therefore, it will be resolved as 3:30 AM EDT. WhenWALLTIME_NEXT_VALID
is used, 2:30 AM will be resolved as next valid wall time, that is 3:00 AM EDT. The default value isWALLTIME_LAST
.Note:This option is effective only when this calendar is
lenient
. When the calendar is strict, such non-existing wall time will cause an exception.- Parameters:
option
- the behavior for handling skipped wall time at positive time zone offset transitions, one ofWALLTIME_FIRST
,WALLTIME_LAST
andWALLTIME_NEXT_VALID
.- Throws:
IllegalArgumentException
- whenoption
is not any ofWALLTIME_FIRST
,WALLTIME_LAST
andWALLTIME_NEXT_VALID
.- See Also:
-
getSkippedWallTimeOption
public int getSkippedWallTimeOption()Gets the behavior for handling skipped wall time at positive time zone offset transitions.- Returns:
- the behavior for handling skipped wall time, one of
WALLTIME_FIRST
,WALLTIME_LAST
andWALLTIME_NEXT_VALID
. - See Also:
-
setFirstDayOfWeek
public void setFirstDayOfWeek(int value) -
getFirstDayOfWeek
public int getFirstDayOfWeek() -
setMinimalDaysInFirstWeek
public void setMinimalDaysInFirstWeek(int value) Sets what the minimal days required in the first week of the year are. For example, if the first week is defined as one that contains the first day of the first month of a year, call the method with value 1. If it must be a full week, use value 7.- Parameters:
value
- the given minimal days required in the first week of the year.
-
getMinimalDaysInFirstWeek
public int getMinimalDaysInFirstWeek()Returns what the minimal days required in the first week of the year are. That is, if the first week is defined as one that contains the first day of the first month of a year, getMinimalDaysInFirstWeek returns 1. If the minimal days required must be a full week, getMinimalDaysInFirstWeek returns 7.- Returns:
- the minimal days required in the first week of the year.
-
handleGetLimit
protected abstract int handleGetLimit(int field, int limitType) Subclass API for defining limits of different types. Subclasses must implement this method to return limits for the following fields:ERA YEAR MONTH WEEK_OF_YEAR WEEK_OF_MONTH DAY_OF_MONTH DAY_OF_YEAR DAY_OF_WEEK_IN_MONTH YEAR_WOY EXTENDED_YEAR
- Parameters:
field
- one of the above field numberslimitType
- one ofMINIMUM
,GREATEST_MINIMUM
,LEAST_MAXIMUM
, orMAXIMUM
-
getLimit
protected int getLimit(int field, int limitType) Returns a limit for a field.- Parameters:
field
- the field, from 0..getFieldCount()-1
limitType
- the type specifier for the limit- See Also:
-
getMinimum
public final int getMinimum(int field) Returns the minimum value for the given time field. e.g., for Gregorian DAY_OF_MONTH, 1.- Parameters:
field
- the given time field.- Returns:
- the minimum value for the given time field.
-
getMaximum
public final int getMaximum(int field) Returns the maximum value for the given time field. e.g. for Gregorian DAY_OF_MONTH, 31.- Parameters:
field
- the given time field.- Returns:
- the maximum value for the given time field.
-
getGreatestMinimum
public final int getGreatestMinimum(int field) Returns the highest minimum value for the given field if varies. Otherwise same as getMinimum(). For Gregorian, no difference.- Parameters:
field
- the given time field.- Returns:
- the highest minimum value for the given time field.
-
getLeastMaximum
public final int getLeastMaximum(int field) Returns the lowest maximum value for the given field if varies. Otherwise same as getMaximum(). e.g., for Gregorian DAY_OF_MONTH, 28.- Parameters:
field
- the given time field.- Returns:
- the lowest maximum value for the given time field.
-
getDayOfWeekType
Deprecated.Returns whether the given day of the week is a weekday, a weekend day, or a day that transitions from one to the other, for the locale and calendar system associated with this Calendar (the locale's region is often the most determinant factor). If a transition occurs at midnight, then the days before and after the transition will have the type WEEKDAY or WEEKEND. If a transition occurs at a time other than midnight, then the day of the transition will have the type WEEKEND_ONSET or WEEKEND_CEASE. In this case, the method getWeekendTransition() will return the point of transition.- Parameters:
dayOfWeek
- either SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, or SATURDAY- Returns:
- either WEEKDAY, WEEKEND, WEEKEND_ONSET, or WEEKEND_CEASE
- Throws:
IllegalArgumentException
- if dayOfWeek is not between SUNDAY and SATURDAY, inclusive- See Also:
-
getWeekendTransition
Deprecated.Returns the time during the day at which the weekend begins or end in this calendar system. If getDayOfWeekType(dayOfWeek) == WEEKEND_ONSET return the time at which the weekend begins. If getDayOfWeekType(dayOfWeek) == WEEKEND_CEASE return the time at which the weekend ends. If getDayOfWeekType(dayOfWeek) has some other value, then throw an exception.- Parameters:
dayOfWeek
- either SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, or SATURDAY- Returns:
- the milliseconds after midnight at which the weekend begins or ends
- Throws:
IllegalArgumentException
- if dayOfWeek is not WEEKEND_ONSET or WEEKEND_CEASE- See Also:
-
isWeekend
Returns true if the given date and time is in the weekend in this calendar system. Equivalent to calling setTime() followed by isWeekend(). Note: This method changes the time this calendar is set to.- Parameters:
date
- the date and time- Returns:
- true if the given date and time is part of the weekend
- See Also:
-
isWeekend
public boolean isWeekend()Returns true if this Calendar's current date and time is in the weekend in this calendar system.- Returns:
- true if the given date and time is part of the weekend
- See Also:
-
clone
Overrides Cloneable -
toString
Returns a string representation of this calendar. This method is intended to be used only for debugging purposes, and the format of the returned string may vary between implementations. The returned string may be empty but may not benull
. -
getWeekDataForRegion
Return simple, immutable struct-like class for access to the CLDR week data.- Parameters:
region
- The input region. The results are undefined if the region code is not valid.- Returns:
- the WeekData for the input region. It is never null.
-
getWeekData
Return simple, immutable struct-like class for access to the week data in this calendar.- Returns:
- the WeekData for this calendar.
-
setWeekData
Set data in this calendar based on the WeekData input.- Parameters:
wdata
- The week data to use- Returns:
- this, for chaining
-
computeFields
protected void computeFields()Converts the current millisecond time valuetime
to field values infields[]
. This synchronizes the time field values with a new time that is set for the calendar. The time is not recomputed first; to recompute the time, then the fields, call thecomplete
method.- See Also:
-
computeGregorianFields
protected final void computeGregorianFields(int julianDay) Compute the Gregorian calendar year, month, and day of month from the Julian day. These values are not stored in fields, but in member variables gregorianXxx. They are used for time zone computations and by subclasses that are Gregorian derivatives. Subclasses may call this method to perform a Gregorian calendar millis->fields computation. To perform a Gregorian calendar fields->millis computation, call computeGregorianMonthStart().- See Also:
-
resolveFields
protected int resolveFields(int[][][] precedenceTable) Given a precedence table, return the newest field combination in the table, or -1 if none is found.The precedence table is a 3-dimensional array of integers. It may be thought of as an array of groups. Each group is an array of lines. Each line is an array of field numbers. Within a line, if all fields are set, then the time stamp of the line is taken to be the stamp of the most recently set field. If any field of a line is unset, then the line fails to match. Within a group, the line with the newest time stamp is selected. The first field of the line is returned to indicate which line matched.
In some cases, it may be desirable to map a line to field that whose stamp is NOT examined. For example, if the best field is DAY_OF_WEEK then the DAY_OF_WEEK_IN_MONTH algorithm may be used. In order to do this, insert the value
REMAP_RESOLVE | F
at the start of the line, whereF
is the desired return field value. This field will NOT be examined; it only determines the return value if the other fields in the line are the newest.If all lines of a group contain at least one unset field, then no line will match, and the group as a whole will fail to match. In that case, the next group will be processed. If all groups fail to match, then -1 is returned.
-
newestStamp
protected int newestStamp(int first, int last, int bestStampSoFar) Returns the newest stamp of a given range of fields. -
getStamp
protected final int getStamp(int field) Returns the timestamp of a field. -
newerField
protected int newerField(int defaultField, int alternateField) Returns the field that is newer, either defaultField, or alternateField. If neither is newer or neither is set, return defaultField. -
validateFields
protected void validateFields()Ensure that each field is within its valid range by callingvalidateField(int)
on each field that has been set. This method should only be called if this calendar is not lenient.- See Also:
-
validateField
protected void validateField(int field) Validate a single field of this calendar. Subclasses should override this method to validate any calendar-specific fields. Generic fields can be handled byCalendar.validateField()
.- See Also:
-
validateField
protected final void validateField(int field, int min, int max) Validate a single field of this calendar given its minimum and maximum allowed value. If the field is out of range, throw a descriptiveIllegalArgumentException
. Subclasses may use this method in their implementation ofvalidateField(int)
. -
computeTime
protected void computeTime()Converts the current field values infields[]
to the millisecond time valuetime
. -
computeMillisInDay
Deprecated.ICU 60Compute the milliseconds in the day from the fields. This is a value from 0 to 23:59:59.999 inclusive, unless fields are out of range, in which case it can be an arbitrary value. This value reflects local zone wall time. -
computeMillisInDayLong
Deprecated.This API is ICU internal only.Compute the milliseconds in the day from the fields. The standard value range is from 0 to 23:59:59.999 inclusive. This value reflects local zone wall time. -
computeZoneOffset
Deprecated.ICU 60This method can assume EXTENDED_YEAR has been set.- Parameters:
millis
- milliseconds of the date fields (local midnight millis)millisInDay
- milliseconds of the time fields; may be out or range.- Returns:
- total zone offset (raw + DST) for the given moment
-
computeZoneOffset
Deprecated.This API is ICU internal only.This method can assume EXTENDED_YEAR has been set.- Parameters:
millis
- milliseconds of the date fields (local midnight millis)millisInDay
- milliseconds of the time fields- Returns:
- total zone offset (raw + DST) for the given moment
-
computeJulianDay
protected int computeJulianDay()Compute the Julian day number as specified by this calendar's fields. -
getFieldResolutionTable
protected int[][][] getFieldResolutionTable()Returns the field resolution array for this calendar. Calendars that define additional fields or change the semantics of existing fields should override this method to adjust the field resolution semantics accordingly. Other subclasses should not override this method.- See Also:
-
handleComputeMonthStart
protected abstract int handleComputeMonthStart(int eyear, int month, boolean useMonth) Returns the Julian day number of day before the first day of the given month in the given extended year. Subclasses should override this method to implement their calendar system.- Parameters:
eyear
- the extended yearmonth
- the zero-based month, or 0 if useMonth is falseuseMonth
- if false, compute the day before the first day of the given year, otherwise, compute the day before the first day of the given month- Returns:
- the Julian day number of the day before the first day of the given month and year
-
handleGetExtendedYear
protected abstract int handleGetExtendedYear()Returns the extended year defined by the current fields. This will use the EXTENDED_YEAR field or the YEAR and supra-year fields (such as ERA) specific to the calendar system, depending on which set of fields is newer.- Returns:
- the extended year
-
handleGetMonthLength
protected int handleGetMonthLength(int extendedYear, int month) Returns the number of days in the given month of the given extended year of this calendar system. Subclasses should override this method if they can provide a more correct or more efficient implementation than the default implementation in Calendar. -
handleGetYearLength
protected int handleGetYearLength(int eyear) Returns the number of days in the given extended year of this calendar system. Subclasses should override this method if they can provide a more correct or more efficient implementation than the default implementation in Calendar. -
handleCreateFields
protected int[] handleCreateFields()Subclasses that use additional fields beyond those defined inCalendar
should override this method to return anint[]
array of the appropriate length. The length must be at leastBASE_FIELD_COUNT
and no more thanMAX_FIELD_COUNT
. -
getDefaultMonthInYear
protected int getDefaultMonthInYear(int extendedYear) Subclasses may override this. Called by handleComputeJulianDay. Returns the default month (0-based) for the year, taking year and era into account. Defaults to 0 (JANUARY) for Gregorian.- Parameters:
extendedYear
- the extendedYear, as returned by handleGetExtendedYear- Returns:
- the default month
- See Also:
-
getDefaultDayInMonth
protected int getDefaultDayInMonth(int extendedYear, int month) Subclasses may override this. Called by handleComputeJulianDay. Returns the default day (1-based) for the month, taking currently-set year and era into account. Defaults to 1 for Gregorian.- Parameters:
extendedYear
- the extendedYear, as returned by handleGetExtendedYearmonth
- the month, as returned by getDefaultMonthInYear- Returns:
- the default day of the month
- See Also:
-
handleComputeJulianDay
protected int handleComputeJulianDay(int bestField) Subclasses may override this. This method calls handleGetMonthLength() to obtain the calendar-specific month length. -
computeGregorianMonthStart
protected int computeGregorianMonthStart(int year, int month) Compute the Julian day of a month of the Gregorian calendar. Subclasses may call this method to perform a Gregorian calendar fields->millis computation. To perform a Gregorian calendar millis->fields computation, call computeGregorianFields().- Parameters:
year
- extended Gregorian yearmonth
- zero-based Gregorian month- Returns:
- the Julian day number of the day before the first day of the given month in the given extended year
- See Also:
-
handleComputeFields
protected void handleComputeFields(int julianDay) Subclasses may override this method to compute several fields specific to each calendar system. These are:- ERA
- YEAR
- MONTH
- DAY_OF_MONTH
- DAY_OF_YEAR
- EXTENDED_YEAR
In addition, subclasses should compute any subclass-specific fields, that is, fields from BASE_FIELD_COUNT to getFieldCount() - 1.
The default implementation in
Calendar
implements a pure proleptic Gregorian calendar. -
getGregorianYear
protected final int getGregorianYear()Returns the extended year on the Gregorian calendar as computed bycomputeGregorianFields()
.- See Also:
-
getGregorianMonth
protected final int getGregorianMonth()Returns the month (0-based) on the Gregorian calendar as computed bycomputeGregorianFields()
.- See Also:
-
getGregorianDayOfYear
protected final int getGregorianDayOfYear()Returns the day of year (1-based) on the Gregorian calendar as computed bycomputeGregorianFields()
.- See Also:
-
getGregorianDayOfMonth
protected final int getGregorianDayOfMonth()Returns the day of month (1-based) on the Gregorian calendar as computed bycomputeGregorianFields()
.- See Also:
-
getFieldCount
public final int getFieldCount()Returns the number of fields defined by this calendar. Valid field arguments toset()
andget()
are0..getFieldCount()-1
. -
internalSet
protected final void internalSet(int field, int value) Set a field to a value. Subclasses should use this method when computing fields. It sets the time stamp in thestamp[]
array toINTERNALLY_SET
. If a field that may not be set by subclasses is passed in, anIllegalArgumentException
is thrown. This prevents subclasses from modifying fields that are intended to be calendar-system invariant. -
isGregorianLeapYear
protected static final boolean isGregorianLeapYear(int year) Determines if the given year is a leap year. Returns true if the given year is a leap year.- Parameters:
year
- the given year.- Returns:
- true if the given year is a leap year; false otherwise.
-
gregorianMonthLength
protected static final int gregorianMonthLength(int y, int m) Returns the length of a month of the Gregorian calendar.- Parameters:
y
- the extended yearm
- the 0-based month number- Returns:
- the number of days in the given month
-
gregorianPreviousMonthLength
protected static final int gregorianPreviousMonthLength(int y, int m) Returns the length of a previous month of the Gregorian calendar.- Parameters:
y
- the extended yearm
- the 0-based month number- Returns:
- the number of days in the month previous to the given month
-
floorDivide
protected static final long floorDivide(long numerator, long denominator) Divide two long integers, returning the floor of the quotient.Unlike the built-in division, this is mathematically well-behaved. E.g.,
-1/4
=> 0 butfloorDivide(-1,4)
=> -1.- Parameters:
numerator
- the numeratordenominator
- a divisor which must be > 0- Returns:
- the floor of the quotient.
-
floorDivide
protected static final int floorDivide(int numerator, int denominator) Divide two integers, returning the floor of the quotient.Unlike the built-in division, this is mathematically well-behaved. E.g.,
-1/4
=> 0 butfloorDivide(-1,4)
=> -1.- Parameters:
numerator
- the numeratordenominator
- a divisor which must be > 0- Returns:
- the floor of the quotient.
-
floorDivide
protected static final int floorDivide(int numerator, int denominator, int[] remainder) Divide two integers, returning the floor of the quotient, and the modulus remainder.Unlike the built-in division, this is mathematically well-behaved. E.g.,
-1/4
=> 0 and-1%4
=> -1, butfloorDivide(-1,4)
=> -1 withremainder[0]
=> 3.- Parameters:
numerator
- the numeratordenominator
- a divisor which must be > 0remainder
- an array of at least one element in which the valuenumerator mod denominator
is returned. Unlikenumerator % denominator
, this will always be non-negative.- Returns:
- the floor of the quotient.
-
floorDivide
protected static final int floorDivide(long numerator, int denominator, int[] remainder) Divide two integers, returning the floor of the quotient, and the modulus remainder.Unlike the built-in division, this is mathematically well-behaved. E.g.,
-1/4
=> 0 and-1%4
=> -1, butfloorDivide(-1,4)
=> -1 withremainder[0]
=> 3.- Parameters:
numerator
- the numeratordenominator
- a divisor which must be > 0remainder
- an array of at least one element in which the valuenumerator mod denominator
is returned. Unlikenumerator % denominator
, this will always be non-negative.- Returns:
- the floor of the quotient.
-
fieldName
Returns a string name for a field, for debugging and exceptions. -
millisToJulianDay
protected static final int millisToJulianDay(long millis) Converts time as milliseconds to Julian day.- Parameters:
millis
- the given milliseconds.- Returns:
- the Julian day number.
-
julianDayToMillis
protected static final long julianDayToMillis(int julian) Converts Julian day to time as milliseconds.- Parameters:
julian
- the given Julian day number.- Returns:
- time as milliseconds.
-
julianDayToDayOfWeek
protected static final int julianDayToDayOfWeek(int julian) Returns the day of week, from SUNDAY to SATURDAY, given a Julian day. -
internalGetTimeInMillis
protected final long internalGetTimeInMillis()Returns the current milliseconds without recomputing. -
getType
Returns the calendar type name string for this Calendar object. The returned string is the legacy ICU calendar attribute value, for example, "gregorian" or "japanese".See type="old type name" for the calendar attribute of locale IDs at http://www.unicode.org/reports/tr35/#Key_Type_Definitions
- Returns:
- legacy calendar type name string
-
haveDefaultCentury
Deprecated.This API is ICU internal only.Returns if two digit representation of year in this calendar type customarily implies a default century (i.e. 03 -> 2003). The default implementation returnstrue
. A subclass may returnfalse
if such practice is not applicable (for example, Chinese calendar and Japanese calendar).- Returns:
true
if this calendar has a default century.
-
getLocale
Returns the locale that was used to create this object, or null. This may may differ from the locale requested at the time of this object's creation. For example, if an object is created for locale en_US_CALIFORNIA, the actual data may be drawn from en (the actual locale), and en_US may be the most specific locale that exists (the valid locale).Note: This method will be implemented in ICU 3.0; ICU 2.8 contains a partial preview implementation. The actual locale is returned correctly, but the valid locale is not, in most cases.
- Parameters:
type
- type of information requested, eitherULocale.VALID_LOCALE
orULocale.ACTUAL_LOCALE
.- Returns:
- the information specified by type, or null if this object was not constructed from locale data.
- See Also:
-