Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/util/Calendar.java
38829 views
/*1* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* (C) Copyright Taligent, Inc. 1996-1998 - All Rights Reserved27* (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved28*29* The original version of this source code and documentation is copyrighted30* and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These31* materials are provided under terms of a License Agreement between Taligent32* and Sun. This technology is protected by multiple US and International33* patents. This notice and attribution to Taligent may not be removed.34* Taligent is a registered trademark of Taligent, Inc.35*36*/3738package java.util;3940import java.io.IOException;41import java.io.ObjectInputStream;42import java.io.ObjectOutputStream;43import java.io.OptionalDataException;44import java.io.Serializable;45import java.security.AccessControlContext;46import java.security.AccessController;47import java.security.PermissionCollection;48import java.security.PrivilegedActionException;49import java.security.PrivilegedExceptionAction;50import java.security.ProtectionDomain;51import java.text.DateFormat;52import java.text.DateFormatSymbols;53import java.time.Instant;54import java.util.concurrent.ConcurrentHashMap;55import java.util.concurrent.ConcurrentMap;56import sun.util.BuddhistCalendar;57import sun.util.calendar.ZoneInfo;58import sun.util.locale.provider.CalendarDataUtility;59import sun.util.locale.provider.LocaleProviderAdapter;60import sun.util.spi.CalendarProvider;6162/**63* The <code>Calendar</code> class is an abstract class that provides methods64* for converting between a specific instant in time and a set of {@link65* #fields calendar fields} such as <code>YEAR</code>, <code>MONTH</code>,66* <code>DAY_OF_MONTH</code>, <code>HOUR</code>, and so on, and for67* manipulating the calendar fields, such as getting the date of the next68* week. An instant in time can be represented by a millisecond value that is69* an offset from the <a name="Epoch"><em>Epoch</em></a>, January 1, 197070* 00:00:00.000 GMT (Gregorian).71*72* <p>The class also provides additional fields and methods for73* implementing a concrete calendar system outside the package. Those74* fields and methods are defined as <code>protected</code>.75*76* <p>77* Like other locale-sensitive classes, <code>Calendar</code> provides a78* class method, <code>getInstance</code>, for getting a generally useful79* object of this type. <code>Calendar</code>'s <code>getInstance</code> method80* returns a <code>Calendar</code> object whose81* calendar fields have been initialized with the current date and time:82* <blockquote>83* <pre>84* Calendar rightNow = Calendar.getInstance();85* </pre>86* </blockquote>87*88* <p>A <code>Calendar</code> object can produce all the calendar field values89* needed to implement the date-time formatting for a particular language and90* calendar style (for example, Japanese-Gregorian, Japanese-Traditional).91* <code>Calendar</code> defines the range of values returned by92* certain calendar fields, as well as their meaning. For example,93* the first month of the calendar system has value <code>MONTH ==94* JANUARY</code> for all calendars. Other values are defined by the95* concrete subclass, such as <code>ERA</code>. See individual field96* documentation and subclass documentation for details.97*98* <h3>Getting and Setting Calendar Field Values</h3>99*100* <p>The calendar field values can be set by calling the <code>set</code>101* methods. Any field values set in a <code>Calendar</code> will not be102* interpreted until it needs to calculate its time value (milliseconds from103* the Epoch) or values of the calendar fields. Calling the104* <code>get</code>, <code>getTimeInMillis</code>, <code>getTime</code>,105* <code>add</code> and <code>roll</code> involves such calculation.106*107* <h4>Leniency</h4>108*109* <p><code>Calendar</code> has two modes for interpreting the calendar110* fields, <em>lenient</em> and <em>non-lenient</em>. When a111* <code>Calendar</code> is in lenient mode, it accepts a wider range of112* calendar field values than it produces. When a <code>Calendar</code>113* recomputes calendar field values for return by <code>get()</code>, all of114* the calendar fields are normalized. For example, a lenient115* <code>GregorianCalendar</code> interprets <code>MONTH == JANUARY</code>,116* <code>DAY_OF_MONTH == 32</code> as February 1.117118* <p>When a <code>Calendar</code> is in non-lenient mode, it throws an119* exception if there is any inconsistency in its calendar fields. For120* example, a <code>GregorianCalendar</code> always produces121* <code>DAY_OF_MONTH</code> values between 1 and the length of the month. A122* non-lenient <code>GregorianCalendar</code> throws an exception upon123* calculating its time or calendar field values if any out-of-range field124* value has been set.125*126* <h4><a name="first_week">First Week</a></h4>127*128* <code>Calendar</code> defines a locale-specific seven day week using two129* parameters: the first day of the week and the minimal days in first week130* (from 1 to 7). These numbers are taken from the locale resource data when a131* <code>Calendar</code> is constructed. They may also be specified explicitly132* through the methods for setting their values.133*134* <p>When setting or getting the <code>WEEK_OF_MONTH</code> or135* <code>WEEK_OF_YEAR</code> fields, <code>Calendar</code> must determine the136* first week of the month or year as a reference point. The first week of a137* month or year is defined as the earliest seven day period beginning on138* <code>getFirstDayOfWeek()</code> and containing at least139* <code>getMinimalDaysInFirstWeek()</code> days of that month or year. Weeks140* numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow141* it. Note that the normalized numbering returned by <code>get()</code> may be142* different. For example, a specific <code>Calendar</code> subclass may143* designate the week before week 1 of a year as week <code><i>n</i></code> of144* the previous year.145*146* <h4>Calendar Fields Resolution</h4>147*148* When computing a date and time from the calendar fields, there149* may be insufficient information for the computation (such as only150* year and month with no day of month), or there may be inconsistent151* information (such as Tuesday, July 15, 1996 (Gregorian) -- July 15,152* 1996 is actually a Monday). <code>Calendar</code> will resolve153* calendar field values to determine the date and time in the154* following way.155*156* <p><a name="resolution">If there is any conflict in calendar field values,157* <code>Calendar</code> gives priorities to calendar fields that have been set158* more recently.</a> The following are the default combinations of the159* calendar fields. The most recent combination, as determined by the160* most recently set single field, will be used.161*162* <p><a name="date_resolution">For the date fields</a>:163* <blockquote>164* <pre>165* YEAR + MONTH + DAY_OF_MONTH166* YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK167* YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK168* YEAR + DAY_OF_YEAR169* YEAR + DAY_OF_WEEK + WEEK_OF_YEAR170* </pre></blockquote>171*172* <a name="time_resolution">For the time of day fields</a>:173* <blockquote>174* <pre>175* HOUR_OF_DAY176* AM_PM + HOUR177* </pre></blockquote>178*179* <p>If there are any calendar fields whose values haven't been set in the selected180* field combination, <code>Calendar</code> uses their default values. The default181* value of each field may vary by concrete calendar systems. For example, in182* <code>GregorianCalendar</code>, the default of a field is the same as that183* of the start of the Epoch: i.e., <code>YEAR = 1970</code>, <code>MONTH =184* JANUARY</code>, <code>DAY_OF_MONTH = 1</code>, etc.185*186* <p>187* <strong>Note:</strong> There are certain possible ambiguities in188* interpretation of certain singular times, which are resolved in the189* following ways:190* <ol>191* <li> 23:59 is the last minute of the day and 00:00 is the first192* minute of the next day. Thus, 23:59 on Dec 31, 1999 < 00:00 on193* Jan 1, 2000 < 00:01 on Jan 1, 2000.194*195* <li> Although historically not precise, midnight also belongs to "am",196* and noon belongs to "pm", so on the same day,197* 12:00 am (midnight) < 12:01 am, and 12:00 pm (noon) < 12:01 pm198* </ol>199*200* <p>201* The date or time format strings are not part of the definition of a202* calendar, as those must be modifiable or overridable by the user at203* runtime. Use {@link DateFormat}204* to format dates.205*206* <h4>Field Manipulation</h4>207*208* The calendar fields can be changed using three methods:209* <code>set()</code>, <code>add()</code>, and <code>roll()</code>.210*211* <p><strong><code>set(f, value)</code></strong> changes calendar field212* <code>f</code> to <code>value</code>. In addition, it sets an213* internal member variable to indicate that calendar field <code>f</code> has214* been changed. Although calendar field <code>f</code> is changed immediately,215* the calendar's time value in milliseconds is not recomputed until the next call to216* <code>get()</code>, <code>getTime()</code>, <code>getTimeInMillis()</code>,217* <code>add()</code>, or <code>roll()</code> is made. Thus, multiple calls to218* <code>set()</code> do not trigger multiple, unnecessary219* computations. As a result of changing a calendar field using220* <code>set()</code>, other calendar fields may also change, depending on the221* calendar field, the calendar field value, and the calendar system. In addition,222* <code>get(f)</code> will not necessarily return <code>value</code> set by223* the call to the <code>set</code> method224* after the calendar fields have been recomputed. The specifics are determined by225* the concrete calendar class.</p>226*227* <p><em>Example</em>: Consider a <code>GregorianCalendar</code>228* originally set to August 31, 1999. Calling <code>set(Calendar.MONTH,229* Calendar.SEPTEMBER)</code> sets the date to September 31,230* 1999. This is a temporary internal representation that resolves to231* October 1, 1999 if <code>getTime()</code>is then called. However, a232* call to <code>set(Calendar.DAY_OF_MONTH, 30)</code> before the call to233* <code>getTime()</code> sets the date to September 30, 1999, since234* no recomputation occurs after <code>set()</code> itself.</p>235*236* <p><strong><code>add(f, delta)</code></strong> adds <code>delta</code>237* to field <code>f</code>. This is equivalent to calling <code>set(f,238* get(f) + delta)</code> with two adjustments:</p>239*240* <blockquote>241* <p><strong>Add rule 1</strong>. The value of field <code>f</code>242* after the call minus the value of field <code>f</code> before the243* call is <code>delta</code>, modulo any overflow that has occurred in244* field <code>f</code>. Overflow occurs when a field value exceeds its245* range and, as a result, the next larger field is incremented or246* decremented and the field value is adjusted back into its range.</p>247*248* <p><strong>Add rule 2</strong>. If a smaller field is expected to be249* invariant, but it is impossible for it to be equal to its250* prior value because of changes in its minimum or maximum after field251* <code>f</code> is changed or other constraints, such as time zone252* offset changes, then its value is adjusted to be as close253* as possible to its expected value. A smaller field represents a254* smaller unit of time. <code>HOUR</code> is a smaller field than255* <code>DAY_OF_MONTH</code>. No adjustment is made to smaller fields256* that are not expected to be invariant. The calendar system257* determines what fields are expected to be invariant.</p>258* </blockquote>259*260* <p>In addition, unlike <code>set()</code>, <code>add()</code> forces261* an immediate recomputation of the calendar's milliseconds and all262* fields.</p>263*264* <p><em>Example</em>: Consider a <code>GregorianCalendar</code>265* originally set to August 31, 1999. Calling <code>add(Calendar.MONTH,266* 13)</code> sets the calendar to September 30, 2000. <strong>Add rule267* 1</strong> sets the <code>MONTH</code> field to September, since268* adding 13 months to August gives September of the next year. Since269* <code>DAY_OF_MONTH</code> cannot be 31 in September in a270* <code>GregorianCalendar</code>, <strong>add rule 2</strong> sets the271* <code>DAY_OF_MONTH</code> to 30, the closest possible value. Although272* it is a smaller field, <code>DAY_OF_WEEK</code> is not adjusted by273* rule 2, since it is expected to change when the month changes in a274* <code>GregorianCalendar</code>.</p>275*276* <p><strong><code>roll(f, delta)</code></strong> adds277* <code>delta</code> to field <code>f</code> without changing larger278* fields. This is equivalent to calling <code>add(f, delta)</code> with279* the following adjustment:</p>280*281* <blockquote>282* <p><strong>Roll rule</strong>. Larger fields are unchanged after the283* call. A larger field represents a larger unit of284* time. <code>DAY_OF_MONTH</code> is a larger field than285* <code>HOUR</code>.</p>286* </blockquote>287*288* <p><em>Example</em>: See {@link java.util.GregorianCalendar#roll(int, int)}.289*290* <p><strong>Usage model</strong>. To motivate the behavior of291* <code>add()</code> and <code>roll()</code>, consider a user interface292* component with increment and decrement buttons for the month, day, and293* year, and an underlying <code>GregorianCalendar</code>. If the294* interface reads January 31, 1999 and the user presses the month295* increment button, what should it read? If the underlying296* implementation uses <code>set()</code>, it might read March 3, 1999. A297* better result would be February 28, 1999. Furthermore, if the user298* presses the month increment button again, it should read March 31,299* 1999, not March 28, 1999. By saving the original date and using either300* <code>add()</code> or <code>roll()</code>, depending on whether larger301* fields should be affected, the user interface can behave as most users302* will intuitively expect.</p>303*304* @see java.lang.System#currentTimeMillis()305* @see Date306* @see GregorianCalendar307* @see TimeZone308* @see java.text.DateFormat309* @author Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu310* @since JDK1.1311*/312public abstract class Calendar implements Serializable, Cloneable, Comparable<Calendar> {313314// Data flow in Calendar315// ---------------------316317// The current time is represented in two ways by Calendar: as UTC318// milliseconds from the epoch (1 January 1970 0:00 UTC), and as local319// fields such as MONTH, HOUR, AM_PM, etc. It is possible to compute the320// millis from the fields, and vice versa. The data needed to do this321// conversion is encapsulated by a TimeZone object owned by the Calendar.322// The data provided by the TimeZone object may also be overridden if the323// user sets the ZONE_OFFSET and/or DST_OFFSET fields directly. The class324// keeps track of what information was most recently set by the caller, and325// uses that to compute any other information as needed.326327// If the user sets the fields using set(), the data flow is as follows.328// This is implemented by the Calendar subclass's computeTime() method.329// During this process, certain fields may be ignored. The disambiguation330// algorithm for resolving which fields to pay attention to is described331// in the class documentation.332333// local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)334// |335// | Using Calendar-specific algorithm336// V337// local standard millis338// |339// | Using TimeZone or user-set ZONE_OFFSET / DST_OFFSET340// V341// UTC millis (in time data member)342343// If the user sets the UTC millis using setTime() or setTimeInMillis(),344// the data flow is as follows. This is implemented by the Calendar345// subclass's computeFields() method.346347// UTC millis (in time data member)348// |349// | Using TimeZone getOffset()350// V351// local standard millis352// |353// | Using Calendar-specific algorithm354// V355// local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)356357// In general, a round trip from fields, through local and UTC millis, and358// back out to fields is made when necessary. This is implemented by the359// complete() method. Resolving a partial set of fields into a UTC millis360// value allows all remaining fields to be generated from that value. If361// the Calendar is lenient, the fields are also renormalized to standard362// ranges when they are regenerated.363364/**365* Field number for <code>get</code> and <code>set</code> indicating the366* era, e.g., AD or BC in the Julian calendar. This is a calendar-specific367* value; see subclass documentation.368*369* @see GregorianCalendar#AD370* @see GregorianCalendar#BC371*/372public final static int ERA = 0;373374/**375* Field number for <code>get</code> and <code>set</code> indicating the376* year. This is a calendar-specific value; see subclass documentation.377*/378public final static int YEAR = 1;379380/**381* Field number for <code>get</code> and <code>set</code> indicating the382* month. This is a calendar-specific value. The first month of383* the year in the Gregorian and Julian calendars is384* <code>JANUARY</code> which is 0; the last depends on the number385* of months in a year.386*387* @see #JANUARY388* @see #FEBRUARY389* @see #MARCH390* @see #APRIL391* @see #MAY392* @see #JUNE393* @see #JULY394* @see #AUGUST395* @see #SEPTEMBER396* @see #OCTOBER397* @see #NOVEMBER398* @see #DECEMBER399* @see #UNDECIMBER400*/401public final static int MONTH = 2;402403/**404* Field number for <code>get</code> and <code>set</code> indicating the405* week number within the current year. The first week of the year, as406* defined by <code>getFirstDayOfWeek()</code> and407* <code>getMinimalDaysInFirstWeek()</code>, has value 1. Subclasses define408* the value of <code>WEEK_OF_YEAR</code> for days before the first week of409* the year.410*411* @see #getFirstDayOfWeek412* @see #getMinimalDaysInFirstWeek413*/414public final static int WEEK_OF_YEAR = 3;415416/**417* Field number for <code>get</code> and <code>set</code> indicating the418* week number within the current month. The first week of the month, as419* defined by <code>getFirstDayOfWeek()</code> and420* <code>getMinimalDaysInFirstWeek()</code>, has value 1. Subclasses define421* the value of <code>WEEK_OF_MONTH</code> for days before the first week of422* the month.423*424* @see #getFirstDayOfWeek425* @see #getMinimalDaysInFirstWeek426*/427public final static int WEEK_OF_MONTH = 4;428429/**430* Field number for <code>get</code> and <code>set</code> indicating the431* day of the month. This is a synonym for <code>DAY_OF_MONTH</code>.432* The first day of the month has value 1.433*434* @see #DAY_OF_MONTH435*/436public final static int DATE = 5;437438/**439* Field number for <code>get</code> and <code>set</code> indicating the440* day of the month. This is a synonym for <code>DATE</code>.441* The first day of the month has value 1.442*443* @see #DATE444*/445public final static int DAY_OF_MONTH = 5;446447/**448* Field number for <code>get</code> and <code>set</code> indicating the day449* number within the current year. The first day of the year has value 1.450*/451public final static int DAY_OF_YEAR = 6;452453/**454* Field number for <code>get</code> and <code>set</code> indicating the day455* of the week. This field takes values <code>SUNDAY</code>,456* <code>MONDAY</code>, <code>TUESDAY</code>, <code>WEDNESDAY</code>,457* <code>THURSDAY</code>, <code>FRIDAY</code>, and <code>SATURDAY</code>.458*459* @see #SUNDAY460* @see #MONDAY461* @see #TUESDAY462* @see #WEDNESDAY463* @see #THURSDAY464* @see #FRIDAY465* @see #SATURDAY466*/467public final static int DAY_OF_WEEK = 7;468469/**470* Field number for <code>get</code> and <code>set</code> indicating the471* ordinal number of the day of the week within the current month. Together472* with the <code>DAY_OF_WEEK</code> field, this uniquely specifies a day473* within a month. Unlike <code>WEEK_OF_MONTH</code> and474* <code>WEEK_OF_YEAR</code>, this field's value does <em>not</em> depend on475* <code>getFirstDayOfWeek()</code> or476* <code>getMinimalDaysInFirstWeek()</code>. <code>DAY_OF_MONTH 1</code>477* through <code>7</code> always correspond to <code>DAY_OF_WEEK_IN_MONTH478* 1</code>; <code>8</code> through <code>14</code> correspond to479* <code>DAY_OF_WEEK_IN_MONTH 2</code>, and so on.480* <code>DAY_OF_WEEK_IN_MONTH 0</code> indicates the week before481* <code>DAY_OF_WEEK_IN_MONTH 1</code>. Negative values count back from the482* end of the month, so the last Sunday of a month is specified as483* <code>DAY_OF_WEEK = SUNDAY, DAY_OF_WEEK_IN_MONTH = -1</code>. Because484* negative values count backward they will usually be aligned differently485* within the month than positive values. For example, if a month has 31486* days, <code>DAY_OF_WEEK_IN_MONTH -1</code> will overlap487* <code>DAY_OF_WEEK_IN_MONTH 5</code> and the end of <code>4</code>.488*489* @see #DAY_OF_WEEK490* @see #WEEK_OF_MONTH491*/492public final static int DAY_OF_WEEK_IN_MONTH = 8;493494/**495* Field number for <code>get</code> and <code>set</code> indicating496* whether the <code>HOUR</code> is before or after noon.497* E.g., at 10:04:15.250 PM the <code>AM_PM</code> is <code>PM</code>.498*499* @see #AM500* @see #PM501* @see #HOUR502*/503public final static int AM_PM = 9;504505/**506* Field number for <code>get</code> and <code>set</code> indicating the507* hour of the morning or afternoon. <code>HOUR</code> is used for the508* 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12.509* E.g., at 10:04:15.250 PM the <code>HOUR</code> is 10.510*511* @see #AM_PM512* @see #HOUR_OF_DAY513*/514public final static int HOUR = 10;515516/**517* Field number for <code>get</code> and <code>set</code> indicating the518* hour of the day. <code>HOUR_OF_DAY</code> is used for the 24-hour clock.519* E.g., at 10:04:15.250 PM the <code>HOUR_OF_DAY</code> is 22.520*521* @see #HOUR522*/523public final static int HOUR_OF_DAY = 11;524525/**526* Field number for <code>get</code> and <code>set</code> indicating the527* minute within the hour.528* E.g., at 10:04:15.250 PM the <code>MINUTE</code> is 4.529*/530public final static int MINUTE = 12;531532/**533* Field number for <code>get</code> and <code>set</code> indicating the534* second within the minute.535* E.g., at 10:04:15.250 PM the <code>SECOND</code> is 15.536*/537public final static int SECOND = 13;538539/**540* Field number for <code>get</code> and <code>set</code> indicating the541* millisecond within the second.542* E.g., at 10:04:15.250 PM the <code>MILLISECOND</code> is 250.543*/544public final static int MILLISECOND = 14;545546/**547* Field number for <code>get</code> and <code>set</code>548* indicating the raw offset from GMT in milliseconds.549* <p>550* This field reflects the correct GMT offset value of the time551* zone of this <code>Calendar</code> if the552* <code>TimeZone</code> implementation subclass supports553* historical GMT offset changes.554*/555public final static int ZONE_OFFSET = 15;556557/**558* Field number for <code>get</code> and <code>set</code> indicating the559* daylight saving offset in milliseconds.560* <p>561* This field reflects the correct daylight saving offset value of562* the time zone of this <code>Calendar</code> if the563* <code>TimeZone</code> implementation subclass supports564* historical Daylight Saving Time schedule changes.565*/566public final static int DST_OFFSET = 16;567568/**569* The number of distinct fields recognized by <code>get</code> and <code>set</code>.570* Field numbers range from <code>0..FIELD_COUNT-1</code>.571*/572public final static int FIELD_COUNT = 17;573574/**575* Value of the {@link #DAY_OF_WEEK} field indicating576* Sunday.577*/578public final static int SUNDAY = 1;579580/**581* Value of the {@link #DAY_OF_WEEK} field indicating582* Monday.583*/584public final static int MONDAY = 2;585586/**587* Value of the {@link #DAY_OF_WEEK} field indicating588* Tuesday.589*/590public final static int TUESDAY = 3;591592/**593* Value of the {@link #DAY_OF_WEEK} field indicating594* Wednesday.595*/596public final static int WEDNESDAY = 4;597598/**599* Value of the {@link #DAY_OF_WEEK} field indicating600* Thursday.601*/602public final static int THURSDAY = 5;603604/**605* Value of the {@link #DAY_OF_WEEK} field indicating606* Friday.607*/608public final static int FRIDAY = 6;609610/**611* Value of the {@link #DAY_OF_WEEK} field indicating612* Saturday.613*/614public final static int SATURDAY = 7;615616/**617* Value of the {@link #MONTH} field indicating the618* first month of the year in the Gregorian and Julian calendars.619*/620public final static int JANUARY = 0;621622/**623* Value of the {@link #MONTH} field indicating the624* second month of the year in the Gregorian and Julian calendars.625*/626public final static int FEBRUARY = 1;627628/**629* Value of the {@link #MONTH} field indicating the630* third month of the year in the Gregorian and Julian calendars.631*/632public final static int MARCH = 2;633634/**635* Value of the {@link #MONTH} field indicating the636* fourth month of the year in the Gregorian and Julian calendars.637*/638public final static int APRIL = 3;639640/**641* Value of the {@link #MONTH} field indicating the642* fifth month of the year in the Gregorian and Julian calendars.643*/644public final static int MAY = 4;645646/**647* Value of the {@link #MONTH} field indicating the648* sixth month of the year in the Gregorian and Julian calendars.649*/650public final static int JUNE = 5;651652/**653* Value of the {@link #MONTH} field indicating the654* seventh month of the year in the Gregorian and Julian calendars.655*/656public final static int JULY = 6;657658/**659* Value of the {@link #MONTH} field indicating the660* eighth month of the year in the Gregorian and Julian calendars.661*/662public final static int AUGUST = 7;663664/**665* Value of the {@link #MONTH} field indicating the666* ninth month of the year in the Gregorian and Julian calendars.667*/668public final static int SEPTEMBER = 8;669670/**671* Value of the {@link #MONTH} field indicating the672* tenth month of the year in the Gregorian and Julian calendars.673*/674public final static int OCTOBER = 9;675676/**677* Value of the {@link #MONTH} field indicating the678* eleventh month of the year in the Gregorian and Julian calendars.679*/680public final static int NOVEMBER = 10;681682/**683* Value of the {@link #MONTH} field indicating the684* twelfth month of the year in the Gregorian and Julian calendars.685*/686public final static int DECEMBER = 11;687688/**689* Value of the {@link #MONTH} field indicating the690* thirteenth month of the year. Although <code>GregorianCalendar</code>691* does not use this value, lunar calendars do.692*/693public final static int UNDECIMBER = 12;694695/**696* Value of the {@link #AM_PM} field indicating the697* period of the day from midnight to just before noon.698*/699public final static int AM = 0;700701/**702* Value of the {@link #AM_PM} field indicating the703* period of the day from noon to just before midnight.704*/705public final static int PM = 1;706707/**708* A style specifier for {@link #getDisplayNames(int, int, Locale)709* getDisplayNames} indicating names in all styles, such as710* "January" and "Jan".711*712* @see #SHORT_FORMAT713* @see #LONG_FORMAT714* @see #SHORT_STANDALONE715* @see #LONG_STANDALONE716* @see #SHORT717* @see #LONG718* @since 1.6719*/720public static final int ALL_STYLES = 0;721722static final int STANDALONE_MASK = 0x8000;723724/**725* A style specifier for {@link #getDisplayName(int, int, Locale)726* getDisplayName} and {@link #getDisplayNames(int, int, Locale)727* getDisplayNames} equivalent to {@link #SHORT_FORMAT}.728*729* @see #SHORT_STANDALONE730* @see #LONG731* @since 1.6732*/733public static final int SHORT = 1;734735/**736* A style specifier for {@link #getDisplayName(int, int, Locale)737* getDisplayName} and {@link #getDisplayNames(int, int, Locale)738* getDisplayNames} equivalent to {@link #LONG_FORMAT}.739*740* @see #LONG_STANDALONE741* @see #SHORT742* @since 1.6743*/744public static final int LONG = 2;745746/**747* A style specifier for {@link #getDisplayName(int, int, Locale)748* getDisplayName} and {@link #getDisplayNames(int, int, Locale)749* getDisplayNames} indicating a narrow name used for format. Narrow names750* are typically single character strings, such as "M" for Monday.751*752* @see #NARROW_STANDALONE753* @see #SHORT_FORMAT754* @see #LONG_FORMAT755* @since 1.8756*/757public static final int NARROW_FORMAT = 4;758759/**760* A style specifier for {@link #getDisplayName(int, int, Locale)761* getDisplayName} and {@link #getDisplayNames(int, int, Locale)762* getDisplayNames} indicating a narrow name independently. Narrow names763* are typically single character strings, such as "M" for Monday.764*765* @see #NARROW_FORMAT766* @see #SHORT_STANDALONE767* @see #LONG_STANDALONE768* @since 1.8769*/770public static final int NARROW_STANDALONE = NARROW_FORMAT | STANDALONE_MASK;771772/**773* A style specifier for {@link #getDisplayName(int, int, Locale)774* getDisplayName} and {@link #getDisplayNames(int, int, Locale)775* getDisplayNames} indicating a short name used for format.776*777* @see #SHORT_STANDALONE778* @see #LONG_FORMAT779* @see #LONG_STANDALONE780* @since 1.8781*/782public static final int SHORT_FORMAT = 1;783784/**785* A style specifier for {@link #getDisplayName(int, int, Locale)786* getDisplayName} and {@link #getDisplayNames(int, int, Locale)787* getDisplayNames} indicating a long name used for format.788*789* @see #LONG_STANDALONE790* @see #SHORT_FORMAT791* @see #SHORT_STANDALONE792* @since 1.8793*/794public static final int LONG_FORMAT = 2;795796/**797* A style specifier for {@link #getDisplayName(int, int, Locale)798* getDisplayName} and {@link #getDisplayNames(int, int, Locale)799* getDisplayNames} indicating a short name used independently,800* such as a month abbreviation as calendar headers.801*802* @see #SHORT_FORMAT803* @see #LONG_FORMAT804* @see #LONG_STANDALONE805* @since 1.8806*/807public static final int SHORT_STANDALONE = SHORT | STANDALONE_MASK;808809/**810* A style specifier for {@link #getDisplayName(int, int, Locale)811* getDisplayName} and {@link #getDisplayNames(int, int, Locale)812* getDisplayNames} indicating a long name used independently,813* such as a month name as calendar headers.814*815* @see #LONG_FORMAT816* @see #SHORT_FORMAT817* @see #SHORT_STANDALONE818* @since 1.8819*/820public static final int LONG_STANDALONE = LONG | STANDALONE_MASK;821822// Internal notes:823// Calendar contains two kinds of time representations: current "time" in824// milliseconds, and a set of calendar "fields" representing the current time.825// The two representations are usually in sync, but can get out of sync826// as follows.827// 1. Initially, no fields are set, and the time is invalid.828// 2. If the time is set, all fields are computed and in sync.829// 3. If a single field is set, the time is invalid.830// Recomputation of the time and fields happens when the object needs831// to return a result to the user, or use a result for a computation.832833/**834* The calendar field values for the currently set time for this calendar.835* This is an array of <code>FIELD_COUNT</code> integers, with index values836* <code>ERA</code> through <code>DST_OFFSET</code>.837* @serial838*/839@SuppressWarnings("ProtectedField")840protected int fields[];841842/**843* The flags which tell if a specified calendar field for the calendar is set.844* A new object has no fields set. After the first call to a method845* which generates the fields, they all remain set after that.846* This is an array of <code>FIELD_COUNT</code> booleans, with index values847* <code>ERA</code> through <code>DST_OFFSET</code>.848* @serial849*/850@SuppressWarnings("ProtectedField")851protected boolean isSet[];852853/**854* Pseudo-time-stamps which specify when each field was set. There855* are two special values, UNSET and COMPUTED. Values from856* MINIMUM_USER_SET to Integer.MAX_VALUE are legal user set values.857*/858transient private int stamp[];859860/**861* The currently set time for this calendar, expressed in milliseconds after862* January 1, 1970, 0:00:00 GMT.863* @see #isTimeSet864* @serial865*/866@SuppressWarnings("ProtectedField")867protected long time;868869/**870* True if then the value of <code>time</code> is valid.871* The time is made invalid by a change to an item of <code>field[]</code>.872* @see #time873* @serial874*/875@SuppressWarnings("ProtectedField")876protected boolean isTimeSet;877878/**879* True if <code>fields[]</code> are in sync with the currently set time.880* If false, then the next attempt to get the value of a field will881* force a recomputation of all fields from the current value of882* <code>time</code>.883* @serial884*/885@SuppressWarnings("ProtectedField")886protected boolean areFieldsSet;887888/**889* True if all fields have been set.890* @serial891*/892transient boolean areAllFieldsSet;893894/**895* <code>True</code> if this calendar allows out-of-range field values during computation896* of <code>time</code> from <code>fields[]</code>.897* @see #setLenient898* @see #isLenient899* @serial900*/901private boolean lenient = true;902903/**904* The <code>TimeZone</code> used by this calendar. <code>Calendar</code>905* uses the time zone data to translate between locale and GMT time.906* @serial907*/908private TimeZone zone;909910/**911* <code>True</code> if zone references to a shared TimeZone object.912*/913transient private boolean sharedZone = false;914915/**916* The first day of the week, with possible values <code>SUNDAY</code>,917* <code>MONDAY</code>, etc. This is a locale-dependent value.918* @serial919*/920private int firstDayOfWeek;921922/**923* The number of days required for the first week in a month or year,924* with possible values from 1 to 7. This is a locale-dependent value.925* @serial926*/927private int minimalDaysInFirstWeek;928929/**930* Cache to hold the firstDayOfWeek and minimalDaysInFirstWeek931* of a Locale.932*/933private static final ConcurrentMap<Locale, int[]> cachedLocaleData934= new ConcurrentHashMap<>(3);935936// Special values of stamp[]937/**938* The corresponding fields[] has no value.939*/940private static final int UNSET = 0;941942/**943* The value of the corresponding fields[] has been calculated internally.944*/945private static final int COMPUTED = 1;946947/**948* The value of the corresponding fields[] has been set externally. Stamp949* values which are greater than 1 represents the (pseudo) time when the950* corresponding fields[] value was set.951*/952private static final int MINIMUM_USER_STAMP = 2;953954/**955* The mask value that represents all of the fields.956*/957static final int ALL_FIELDS = (1 << FIELD_COUNT) - 1;958959/**960* The next available value for <code>stamp[]</code>, an internal array.961* This actually should not be written out to the stream, and will probably962* be removed from the stream in the near future. In the meantime,963* a value of <code>MINIMUM_USER_STAMP</code> should be used.964* @serial965*/966private int nextStamp = MINIMUM_USER_STAMP;967968// the internal serial version which says which version was written969// - 0 (default) for version up to JDK 1.1.5970// - 1 for version from JDK 1.1.6, which writes a correct 'time' value971// as well as compatible values for other fields. This is a972// transitional format.973// - 2 (not implemented yet) a future version, in which fields[],974// areFieldsSet, and isTimeSet become transient, and isSet[] is975// removed. In JDK 1.1.6 we write a format compatible with version 2.976static final int currentSerialVersion = 1;977978/**979* The version of the serialized data on the stream. Possible values:980* <dl>981* <dt><b>0</b> or not present on stream</dt>982* <dd>983* JDK 1.1.5 or earlier.984* </dd>985* <dt><b>1</b></dt>986* <dd>987* JDK 1.1.6 or later. Writes a correct 'time' value988* as well as compatible values for other fields. This is a989* transitional format.990* </dd>991* </dl>992* When streaming out this class, the most recent format993* and the highest allowable <code>serialVersionOnStream</code>994* is written.995* @serial996* @since JDK1.1.6997*/998private int serialVersionOnStream = currentSerialVersion;9991000// Proclaim serialization compatibility with JDK 1.11001static final long serialVersionUID = -1807547505821590642L;10021003// Mask values for calendar fields1004@SuppressWarnings("PointlessBitwiseExpression")1005final static int ERA_MASK = (1 << ERA);1006final static int YEAR_MASK = (1 << YEAR);1007final static int MONTH_MASK = (1 << MONTH);1008final static int WEEK_OF_YEAR_MASK = (1 << WEEK_OF_YEAR);1009final static int WEEK_OF_MONTH_MASK = (1 << WEEK_OF_MONTH);1010final static int DAY_OF_MONTH_MASK = (1 << DAY_OF_MONTH);1011final static int DATE_MASK = DAY_OF_MONTH_MASK;1012final static int DAY_OF_YEAR_MASK = (1 << DAY_OF_YEAR);1013final static int DAY_OF_WEEK_MASK = (1 << DAY_OF_WEEK);1014final static int DAY_OF_WEEK_IN_MONTH_MASK = (1 << DAY_OF_WEEK_IN_MONTH);1015final static int AM_PM_MASK = (1 << AM_PM);1016final static int HOUR_MASK = (1 << HOUR);1017final static int HOUR_OF_DAY_MASK = (1 << HOUR_OF_DAY);1018final static int MINUTE_MASK = (1 << MINUTE);1019final static int SECOND_MASK = (1 << SECOND);1020final static int MILLISECOND_MASK = (1 << MILLISECOND);1021final static int ZONE_OFFSET_MASK = (1 << ZONE_OFFSET);1022final static int DST_OFFSET_MASK = (1 << DST_OFFSET);10231024/**1025* {@code Calendar.Builder} is used for creating a {@code Calendar} from1026* various date-time parameters.1027*1028* <p>There are two ways to set a {@code Calendar} to a date-time value. One1029* is to set the instant parameter to a millisecond offset from the <a1030* href="Calendar.html#Epoch">Epoch</a>. The other is to set individual1031* field parameters, such as {@link Calendar#YEAR YEAR}, to their desired1032* values. These two ways can't be mixed. Trying to set both the instant and1033* individual fields will cause an {@link IllegalStateException} to be1034* thrown. However, it is permitted to override previous values of the1035* instant or field parameters.1036*1037* <p>If no enough field parameters are given for determining date and/or1038* time, calendar specific default values are used when building a1039* {@code Calendar}. For example, if the {@link Calendar#YEAR YEAR} value1040* isn't given for the Gregorian calendar, 1970 will be used. If there are1041* any conflicts among field parameters, the <a1042* href="Calendar.html#resolution"> resolution rules</a> are applied.1043* Therefore, the order of field setting matters.1044*1045* <p>In addition to the date-time parameters,1046* the {@linkplain #setLocale(Locale) locale},1047* {@linkplain #setTimeZone(TimeZone) time zone},1048* {@linkplain #setWeekDefinition(int, int) week definition}, and1049* {@linkplain #setLenient(boolean) leniency mode} parameters can be set.1050*1051* <p><b>Examples</b>1052* <p>The following are sample usages. Sample code assumes that the1053* {@code Calendar} constants are statically imported.1054*1055* <p>The following code produces a {@code Calendar} with date 2012-12-311056* (Gregorian) because Monday is the first day of a week with the <a1057* href="GregorianCalendar.html#iso8601_compatible_setting"> ISO 86011058* compatible week parameters</a>.1059* <pre>1060* Calendar cal = new Calendar.Builder().setCalendarType("iso8601")1061* .setWeekDate(2013, 1, MONDAY).build();</pre>1062* <p>The following code produces a Japanese {@code Calendar} with date1063* 1989-01-08 (Gregorian), assuming that the default {@link Calendar#ERA ERA}1064* is <em>Heisei</em> that started on that day.1065* <pre>1066* Calendar cal = new Calendar.Builder().setCalendarType("japanese")1067* .setFields(YEAR, 1, DAY_OF_YEAR, 1).build();</pre>1068*1069* @since 1.81070* @see Calendar#getInstance(TimeZone, Locale)1071* @see Calendar#fields1072*/1073public static class Builder {1074private static final int NFIELDS = FIELD_COUNT + 1; // +1 for WEEK_YEAR1075private static final int WEEK_YEAR = FIELD_COUNT;10761077private long instant;1078// Calendar.stamp[] (lower half) and Calendar.fields[] (upper half) combined1079private int[] fields;1080// Pseudo timestamp starting from MINIMUM_USER_STAMP.1081// (COMPUTED is used to indicate that the instant has been set.)1082private int nextStamp;1083// maxFieldIndex keeps the max index of fields which have been set.1084// (WEEK_YEAR is never included.)1085private int maxFieldIndex;1086private String type;1087private TimeZone zone;1088private boolean lenient = true;1089private Locale locale;1090private int firstDayOfWeek, minimalDaysInFirstWeek;10911092/**1093* Constructs a {@code Calendar.Builder}.1094*/1095public Builder() {1096}10971098/**1099* Sets the instant parameter to the given {@code instant} value that is1100* a millisecond offset from <a href="Calendar.html#Epoch">the1101* Epoch</a>.1102*1103* @param instant a millisecond offset from the Epoch1104* @return this {@code Calendar.Builder}1105* @throws IllegalStateException if any of the field parameters have1106* already been set1107* @see Calendar#setTime(Date)1108* @see Calendar#setTimeInMillis(long)1109* @see Calendar#time1110*/1111public Builder setInstant(long instant) {1112if (fields != null) {1113throw new IllegalStateException();1114}1115this.instant = instant;1116nextStamp = COMPUTED;1117return this;1118}11191120/**1121* Sets the instant parameter to the {@code instant} value given by a1122* {@link Date}. This method is equivalent to a call to1123* {@link #setInstant(long) setInstant(instant.getTime())}.1124*1125* @param instant a {@code Date} representing a millisecond offset from1126* the Epoch1127* @return this {@code Calendar.Builder}1128* @throws NullPointerException if {@code instant} is {@code null}1129* @throws IllegalStateException if any of the field parameters have1130* already been set1131* @see Calendar#setTime(Date)1132* @see Calendar#setTimeInMillis(long)1133* @see Calendar#time1134*/1135public Builder setInstant(Date instant) {1136return setInstant(instant.getTime()); // NPE if instant == null1137}11381139/**1140* Sets the {@code field} parameter to the given {@code value}.1141* {@code field} is an index to the {@link Calendar#fields}, such as1142* {@link Calendar#DAY_OF_MONTH DAY_OF_MONTH}. Field value validation is1143* not performed in this method. Any out of range values are either1144* normalized in lenient mode or detected as an invalid value in1145* non-lenient mode when building a {@code Calendar}.1146*1147* @param field an index to the {@code Calendar} fields1148* @param value the field value1149* @return this {@code Calendar.Builder}1150* @throws IllegalArgumentException if {@code field} is invalid1151* @throws IllegalStateException if the instant value has already been set,1152* or if fields have been set too many1153* (approximately {@link Integer#MAX_VALUE}) times.1154* @see Calendar#set(int, int)1155*/1156public Builder set(int field, int value) {1157// Note: WEEK_YEAR can't be set with this method.1158if (field < 0 || field >= FIELD_COUNT) {1159throw new IllegalArgumentException("field is invalid");1160}1161if (isInstantSet()) {1162throw new IllegalStateException("instant has been set");1163}1164allocateFields();1165internalSet(field, value);1166return this;1167}11681169/**1170* Sets field parameters to their values given by1171* {@code fieldValuePairs} that are pairs of a field and its value.1172* For example,1173* <pre>1174* setFeilds(Calendar.YEAR, 2013,1175* Calendar.MONTH, Calendar.DECEMBER,1176* Calendar.DAY_OF_MONTH, 23);</pre>1177* is equivalent to the sequence of the following1178* {@link #set(int, int) set} calls:1179* <pre>1180* set(Calendar.YEAR, 2013)1181* .set(Calendar.MONTH, Calendar.DECEMBER)1182* .set(Calendar.DAY_OF_MONTH, 23);</pre>1183*1184* @param fieldValuePairs field-value pairs1185* @return this {@code Calendar.Builder}1186* @throws NullPointerException if {@code fieldValuePairs} is {@code null}1187* @throws IllegalArgumentException if any of fields are invalid,1188* or if {@code fieldValuePairs.length} is an odd number.1189* @throws IllegalStateException if the instant value has been set,1190* or if fields have been set too many (approximately1191* {@link Integer#MAX_VALUE}) times.1192*/1193public Builder setFields(int... fieldValuePairs) {1194int len = fieldValuePairs.length;1195if ((len % 2) != 0) {1196throw new IllegalArgumentException();1197}1198if (isInstantSet()) {1199throw new IllegalStateException("instant has been set");1200}1201if ((nextStamp + len / 2) < 0) {1202throw new IllegalStateException("stamp counter overflow");1203}1204allocateFields();1205for (int i = 0; i < len; ) {1206int field = fieldValuePairs[i++];1207// Note: WEEK_YEAR can't be set with this method.1208if (field < 0 || field >= FIELD_COUNT) {1209throw new IllegalArgumentException("field is invalid");1210}1211internalSet(field, fieldValuePairs[i++]);1212}1213return this;1214}12151216/**1217* Sets the date field parameters to the values given by {@code year},1218* {@code month}, and {@code dayOfMonth}. This method is equivalent to1219* a call to:1220* <pre>1221* setFields(Calendar.YEAR, year,1222* Calendar.MONTH, month,1223* Calendar.DAY_OF_MONTH, dayOfMonth);</pre>1224*1225* @param year the {@link Calendar#YEAR YEAR} value1226* @param month the {@link Calendar#MONTH MONTH} value1227* (the month numbering is <em>0-based</em>).1228* @param dayOfMonth the {@link Calendar#DAY_OF_MONTH DAY_OF_MONTH} value1229* @return this {@code Calendar.Builder}1230*/1231public Builder setDate(int year, int month, int dayOfMonth) {1232return setFields(YEAR, year, MONTH, month, DAY_OF_MONTH, dayOfMonth);1233}12341235/**1236* Sets the time of day field parameters to the values given by1237* {@code hourOfDay}, {@code minute}, and {@code second}. This method is1238* equivalent to a call to:1239* <pre>1240* setTimeOfDay(hourOfDay, minute, second, 0);</pre>1241*1242* @param hourOfDay the {@link Calendar#HOUR_OF_DAY HOUR_OF_DAY} value1243* (24-hour clock)1244* @param minute the {@link Calendar#MINUTE MINUTE} value1245* @param second the {@link Calendar#SECOND SECOND} value1246* @return this {@code Calendar.Builder}1247*/1248public Builder setTimeOfDay(int hourOfDay, int minute, int second) {1249return setTimeOfDay(hourOfDay, minute, second, 0);1250}12511252/**1253* Sets the time of day field parameters to the values given by1254* {@code hourOfDay}, {@code minute}, {@code second}, and1255* {@code millis}. This method is equivalent to a call to:1256* <pre>1257* setFields(Calendar.HOUR_OF_DAY, hourOfDay,1258* Calendar.MINUTE, minute,1259* Calendar.SECOND, second,1260* Calendar.MILLISECOND, millis);</pre>1261*1262* @param hourOfDay the {@link Calendar#HOUR_OF_DAY HOUR_OF_DAY} value1263* (24-hour clock)1264* @param minute the {@link Calendar#MINUTE MINUTE} value1265* @param second the {@link Calendar#SECOND SECOND} value1266* @param millis the {@link Calendar#MILLISECOND MILLISECOND} value1267* @return this {@code Calendar.Builder}1268*/1269public Builder setTimeOfDay(int hourOfDay, int minute, int second, int millis) {1270return setFields(HOUR_OF_DAY, hourOfDay, MINUTE, minute,1271SECOND, second, MILLISECOND, millis);1272}12731274/**1275* Sets the week-based date parameters to the values with the given1276* date specifiers - week year, week of year, and day of week.1277*1278* <p>If the specified calendar doesn't support week dates, the1279* {@link #build() build} method will throw an {@link IllegalArgumentException}.1280*1281* @param weekYear the week year1282* @param weekOfYear the week number based on {@code weekYear}1283* @param dayOfWeek the day of week value: one of the constants1284* for the {@link Calendar#DAY_OF_WEEK DAY_OF_WEEK} field:1285* {@link Calendar#SUNDAY SUNDAY}, ..., {@link Calendar#SATURDAY SATURDAY}.1286* @return this {@code Calendar.Builder}1287* @see Calendar#setWeekDate(int, int, int)1288* @see Calendar#isWeekDateSupported()1289*/1290public Builder setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) {1291allocateFields();1292internalSet(WEEK_YEAR, weekYear);1293internalSet(WEEK_OF_YEAR, weekOfYear);1294internalSet(DAY_OF_WEEK, dayOfWeek);1295return this;1296}12971298/**1299* Sets the time zone parameter to the given {@code zone}. If no time1300* zone parameter is given to this {@code Caledar.Builder}, the1301* {@linkplain TimeZone#getDefault() default1302* <code>TimeZone</code>} will be used in the {@link #build() build}1303* method.1304*1305* @param zone the {@link TimeZone}1306* @return this {@code Calendar.Builder}1307* @throws NullPointerException if {@code zone} is {@code null}1308* @see Calendar#setTimeZone(TimeZone)1309*/1310public Builder setTimeZone(TimeZone zone) {1311if (zone == null) {1312throw new NullPointerException();1313}1314this.zone = zone;1315return this;1316}13171318/**1319* Sets the lenient mode parameter to the value given by {@code lenient}.1320* If no lenient parameter is given to this {@code Calendar.Builder},1321* lenient mode will be used in the {@link #build() build} method.1322*1323* @param lenient {@code true} for lenient mode;1324* {@code false} for non-lenient mode1325* @return this {@code Calendar.Builder}1326* @see Calendar#setLenient(boolean)1327*/1328public Builder setLenient(boolean lenient) {1329this.lenient = lenient;1330return this;1331}13321333/**1334* Sets the calendar type parameter to the given {@code type}. The1335* calendar type given by this method has precedence over any explicit1336* or implicit calendar type given by the1337* {@linkplain #setLocale(Locale) locale}.1338*1339* <p>In addition to the available calendar types returned by the1340* {@link Calendar#getAvailableCalendarTypes() Calendar.getAvailableCalendarTypes}1341* method, {@code "gregorian"} and {@code "iso8601"} as aliases of1342* {@code "gregory"} can be used with this method.1343*1344* @param type the calendar type1345* @return this {@code Calendar.Builder}1346* @throws NullPointerException if {@code type} is {@code null}1347* @throws IllegalArgumentException if {@code type} is unknown1348* @throws IllegalStateException if another calendar type has already been set1349* @see Calendar#getCalendarType()1350* @see Calendar#getAvailableCalendarTypes()1351*/1352public Builder setCalendarType(String type) {1353if (type.equals("gregorian")) { // NPE if type == null1354type = "gregory";1355}1356if (!Calendar.getAvailableCalendarTypes().contains(type)1357&& !type.equals("iso8601")) {1358throw new IllegalArgumentException("unknown calendar type: " + type);1359}1360if (this.type == null) {1361this.type = type;1362} else {1363if (!this.type.equals(type)) {1364throw new IllegalStateException("calendar type override");1365}1366}1367return this;1368}13691370/**1371* Sets the locale parameter to the given {@code locale}. If no locale1372* is given to this {@code Calendar.Builder}, the {@linkplain1373* Locale#getDefault(Locale.Category) default <code>Locale</code>}1374* for {@link Locale.Category#FORMAT} will be used.1375*1376* <p>If no calendar type is explicitly given by a call to the1377* {@link #setCalendarType(String) setCalendarType} method,1378* the {@code Locale} value is used to determine what type of1379* {@code Calendar} to be built.1380*1381* <p>If no week definition parameters are explicitly given by a call to1382* the {@link #setWeekDefinition(int,int) setWeekDefinition} method, the1383* {@code Locale}'s default values are used.1384*1385* @param locale the {@link Locale}1386* @throws NullPointerException if {@code locale} is {@code null}1387* @return this {@code Calendar.Builder}1388* @see Calendar#getInstance(Locale)1389*/1390public Builder setLocale(Locale locale) {1391if (locale == null) {1392throw new NullPointerException();1393}1394this.locale = locale;1395return this;1396}13971398/**1399* Sets the week definition parameters to the values given by1400* {@code firstDayOfWeek} and {@code minimalDaysInFirstWeek} that are1401* used to determine the <a href="Calendar.html#First_Week">first1402* week</a> of a year. The parameters given by this method have1403* precedence over the default values given by the1404* {@linkplain #setLocale(Locale) locale}.1405*1406* @param firstDayOfWeek the first day of a week; one of1407* {@link Calendar#SUNDAY} to {@link Calendar#SATURDAY}1408* @param minimalDaysInFirstWeek the minimal number of days in the first1409* week (1..7)1410* @return this {@code Calendar.Builder}1411* @throws IllegalArgumentException if {@code firstDayOfWeek} or1412* {@code minimalDaysInFirstWeek} is invalid1413* @see Calendar#getFirstDayOfWeek()1414* @see Calendar#getMinimalDaysInFirstWeek()1415*/1416public Builder setWeekDefinition(int firstDayOfWeek, int minimalDaysInFirstWeek) {1417if (!isValidWeekParameter(firstDayOfWeek)1418|| !isValidWeekParameter(minimalDaysInFirstWeek)) {1419throw new IllegalArgumentException();1420}1421this.firstDayOfWeek = firstDayOfWeek;1422this.minimalDaysInFirstWeek = minimalDaysInFirstWeek;1423return this;1424}14251426/**1427* Returns a {@code Calendar} built from the parameters set by the1428* setter methods. The calendar type given by the {@link #setCalendarType(String)1429* setCalendarType} method or the {@linkplain #setLocale(Locale) locale} is1430* used to determine what {@code Calendar} to be created. If no explicit1431* calendar type is given, the locale's default calendar is created.1432*1433* <p>If the calendar type is {@code "iso8601"}, the1434* {@linkplain GregorianCalendar#setGregorianChange(Date) Gregorian change date}1435* of a {@link GregorianCalendar} is set to {@code Date(Long.MIN_VALUE)}1436* to be the <em>proleptic</em> Gregorian calendar. Its week definition1437* parameters are also set to be <a1438* href="GregorianCalendar.html#iso8601_compatible_setting">compatible1439* with the ISO 8601 standard</a>. Note that the1440* {@link GregorianCalendar#getCalendarType() getCalendarType} method of1441* a {@code GregorianCalendar} created with {@code "iso8601"} returns1442* {@code "gregory"}.1443*1444* <p>The default values are used for locale and time zone if these1445* parameters haven't been given explicitly.1446*1447* <p>Any out of range field values are either normalized in lenient1448* mode or detected as an invalid value in non-lenient mode.1449*1450* @return a {@code Calendar} built with parameters of this {@code1451* Calendar.Builder}1452* @throws IllegalArgumentException if the calendar type is unknown, or1453* if any invalid field values are given in non-lenient mode, or1454* if a week date is given for the calendar type that doesn't1455* support week dates.1456* @see Calendar#getInstance(TimeZone, Locale)1457* @see Locale#getDefault(Locale.Category)1458* @see TimeZone#getDefault()1459*/1460public Calendar build() {1461if (locale == null) {1462locale = Locale.getDefault();1463}1464if (zone == null) {1465zone = TimeZone.getDefault();1466}1467Calendar cal;1468if (type == null) {1469type = locale.getUnicodeLocaleType("ca");1470}1471if (type == null) {1472if (locale.getCountry() == "TH"1473&& locale.getLanguage() == "th") {1474type = "buddhist";1475} else {1476type = "gregory";1477}1478}1479switch (type) {1480case "gregory":1481cal = new GregorianCalendar(zone, locale, true);1482break;1483case "iso8601":1484GregorianCalendar gcal = new GregorianCalendar(zone, locale, true);1485// make gcal a proleptic Gregorian1486gcal.setGregorianChange(new Date(Long.MIN_VALUE));1487// and week definition to be compatible with ISO 86011488setWeekDefinition(MONDAY, 4);1489cal = gcal;1490break;1491case "buddhist":1492cal = new BuddhistCalendar(zone, locale);1493cal.clear();1494break;1495case "japanese":1496cal = new JapaneseImperialCalendar(zone, locale, true);1497break;1498default:1499throw new IllegalArgumentException("unknown calendar type: " + type);1500}1501cal.setLenient(lenient);1502if (firstDayOfWeek != 0) {1503cal.setFirstDayOfWeek(firstDayOfWeek);1504cal.setMinimalDaysInFirstWeek(minimalDaysInFirstWeek);1505}1506if (isInstantSet()) {1507cal.setTimeInMillis(instant);1508cal.complete();1509return cal;1510}15111512if (fields != null) {1513boolean weekDate = isSet(WEEK_YEAR)1514&& fields[WEEK_YEAR] > fields[YEAR];1515if (weekDate && !cal.isWeekDateSupported()) {1516throw new IllegalArgumentException("week date is unsupported by " + type);1517}15181519// Set the fields from the min stamp to the max stamp so that1520// the fields resolution works in the Calendar.1521for (int stamp = MINIMUM_USER_STAMP; stamp < nextStamp; stamp++) {1522for (int index = 0; index <= maxFieldIndex; index++) {1523if (fields[index] == stamp) {1524cal.set(index, fields[NFIELDS + index]);1525break;1526}1527}1528}15291530if (weekDate) {1531int weekOfYear = isSet(WEEK_OF_YEAR) ? fields[NFIELDS + WEEK_OF_YEAR] : 1;1532int dayOfWeek = isSet(DAY_OF_WEEK)1533? fields[NFIELDS + DAY_OF_WEEK] : cal.getFirstDayOfWeek();1534cal.setWeekDate(fields[NFIELDS + WEEK_YEAR], weekOfYear, dayOfWeek);1535}1536cal.complete();1537}15381539return cal;1540}15411542private void allocateFields() {1543if (fields == null) {1544fields = new int[NFIELDS * 2];1545nextStamp = MINIMUM_USER_STAMP;1546maxFieldIndex = -1;1547}1548}15491550private void internalSet(int field, int value) {1551fields[field] = nextStamp++;1552if (nextStamp < 0) {1553throw new IllegalStateException("stamp counter overflow");1554}1555fields[NFIELDS + field] = value;1556if (field > maxFieldIndex && field < WEEK_YEAR) {1557maxFieldIndex = field;1558}1559}15601561private boolean isInstantSet() {1562return nextStamp == COMPUTED;1563}15641565private boolean isSet(int index) {1566return fields != null && fields[index] > UNSET;1567}15681569private boolean isValidWeekParameter(int value) {1570return value > 0 && value <= 7;1571}1572}15731574/**1575* Constructs a Calendar with the default time zone1576* and the default {@link java.util.Locale.Category#FORMAT FORMAT}1577* locale.1578* @see TimeZone#getDefault1579*/1580protected Calendar()1581{1582this(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));1583sharedZone = true;1584}15851586/**1587* Constructs a calendar with the specified time zone and locale.1588*1589* @param zone the time zone to use1590* @param aLocale the locale for the week data1591*/1592protected Calendar(TimeZone zone, Locale aLocale)1593{1594fields = new int[FIELD_COUNT];1595isSet = new boolean[FIELD_COUNT];1596stamp = new int[FIELD_COUNT];15971598this.zone = zone;1599setWeekCountData(aLocale);1600}16011602/**1603* Gets a calendar using the default time zone and locale. The1604* <code>Calendar</code> returned is based on the current time1605* in the default time zone with the default1606* {@link Locale.Category#FORMAT FORMAT} locale.1607*1608* @return a Calendar.1609*/1610public static Calendar getInstance()1611{1612return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT));1613}16141615/**1616* Gets a calendar using the specified time zone and default locale.1617* The <code>Calendar</code> returned is based on the current time1618* in the given time zone with the default1619* {@link Locale.Category#FORMAT FORMAT} locale.1620*1621* @param zone the time zone to use1622* @return a Calendar.1623*/1624public static Calendar getInstance(TimeZone zone)1625{1626return createCalendar(zone, Locale.getDefault(Locale.Category.FORMAT));1627}16281629/**1630* Gets a calendar using the default time zone and specified locale.1631* The <code>Calendar</code> returned is based on the current time1632* in the default time zone with the given locale.1633*1634* @param aLocale the locale for the week data1635* @return a Calendar.1636*/1637public static Calendar getInstance(Locale aLocale)1638{1639return createCalendar(TimeZone.getDefault(), aLocale);1640}16411642/**1643* Gets a calendar with the specified time zone and locale.1644* The <code>Calendar</code> returned is based on the current time1645* in the given time zone with the given locale.1646*1647* @param zone the time zone to use1648* @param aLocale the locale for the week data1649* @return a Calendar.1650*/1651public static Calendar getInstance(TimeZone zone,1652Locale aLocale)1653{1654return createCalendar(zone, aLocale);1655}16561657private static Calendar createCalendar(TimeZone zone,1658Locale aLocale)1659{1660CalendarProvider provider =1661LocaleProviderAdapter.getAdapter(CalendarProvider.class, aLocale)1662.getCalendarProvider();1663if (provider != null) {1664try {1665return provider.getInstance(zone, aLocale);1666} catch (IllegalArgumentException iae) {1667// fall back to the default instantiation1668}1669}16701671Calendar cal = null;16721673if (aLocale.hasExtensions()) {1674String caltype = aLocale.getUnicodeLocaleType("ca");1675if (caltype != null) {1676switch (caltype) {1677case "buddhist":1678cal = new BuddhistCalendar(zone, aLocale);1679break;1680case "japanese":1681cal = new JapaneseImperialCalendar(zone, aLocale);1682break;1683case "gregory":1684cal = new GregorianCalendar(zone, aLocale);1685break;1686}1687}1688}1689if (cal == null) {1690// If no known calendar type is explicitly specified,1691// perform the traditional way to create a Calendar:1692// create a BuddhistCalendar for th_TH locale,1693// a JapaneseImperialCalendar for ja_JP_JP locale, or1694// a GregorianCalendar for any other locales.1695// NOTE: The language, country and variant strings are interned.1696if (aLocale.getLanguage() == "th" && aLocale.getCountry() == "TH") {1697cal = new BuddhistCalendar(zone, aLocale);1698} else if (aLocale.getVariant() == "JP" && aLocale.getLanguage() == "ja"1699&& aLocale.getCountry() == "JP") {1700cal = new JapaneseImperialCalendar(zone, aLocale);1701} else {1702cal = new GregorianCalendar(zone, aLocale);1703}1704}1705return cal;1706}17071708/**1709* Returns an array of all locales for which the <code>getInstance</code>1710* methods of this class can return localized instances.1711* The array returned must contain at least a <code>Locale</code>1712* instance equal to {@link java.util.Locale#US Locale.US}.1713*1714* @return An array of locales for which localized1715* <code>Calendar</code> instances are available.1716*/1717public static synchronized Locale[] getAvailableLocales()1718{1719return DateFormat.getAvailableLocales();1720}17211722/**1723* Converts the current calendar field values in {@link #fields fields[]}1724* to the millisecond time value1725* {@link #time}.1726*1727* @see #complete()1728* @see #computeFields()1729*/1730protected abstract void computeTime();17311732/**1733* Converts the current millisecond time value {@link #time}1734* to calendar field values in {@link #fields fields[]}.1735* This allows you to sync up the calendar field values with1736* a new time that is set for the calendar. The time is <em>not</em>1737* recomputed first; to recompute the time, then the fields, call the1738* {@link #complete()} method.1739*1740* @see #computeTime()1741*/1742protected abstract void computeFields();17431744/**1745* Returns a <code>Date</code> object representing this1746* <code>Calendar</code>'s time value (millisecond offset from the <a1747* href="#Epoch">Epoch</a>").1748*1749* @return a <code>Date</code> representing the time value.1750* @see #setTime(Date)1751* @see #getTimeInMillis()1752*/1753public final Date getTime() {1754return new Date(getTimeInMillis());1755}17561757/**1758* Sets this Calendar's time with the given <code>Date</code>.1759* <p>1760* Note: Calling <code>setTime()</code> with1761* <code>Date(Long.MAX_VALUE)</code> or <code>Date(Long.MIN_VALUE)</code>1762* may yield incorrect field values from <code>get()</code>.1763*1764* @param date the given Date.1765* @see #getTime()1766* @see #setTimeInMillis(long)1767*/1768public final void setTime(Date date) {1769setTimeInMillis(date.getTime());1770}17711772/**1773* Returns this Calendar's time value in milliseconds.1774*1775* @return the current time as UTC milliseconds from the epoch.1776* @see #getTime()1777* @see #setTimeInMillis(long)1778*/1779public long getTimeInMillis() {1780if (!isTimeSet) {1781updateTime();1782}1783return time;1784}17851786/**1787* Sets this Calendar's current time from the given long value.1788*1789* @param millis the new time in UTC milliseconds from the epoch.1790* @see #setTime(Date)1791* @see #getTimeInMillis()1792*/1793public void setTimeInMillis(long millis) {1794// If we don't need to recalculate the calendar field values,1795// do nothing.1796if (time == millis && isTimeSet && areFieldsSet && areAllFieldsSet1797&& (zone instanceof ZoneInfo) && !((ZoneInfo)zone).isDirty()) {1798return;1799}1800time = millis;1801isTimeSet = true;1802areFieldsSet = false;1803computeFields();1804areAllFieldsSet = areFieldsSet = true;1805}18061807/**1808* Returns the value of the given calendar field. In lenient mode,1809* all calendar fields are normalized. In non-lenient mode, all1810* calendar fields are validated and this method throws an1811* exception if any calendar fields have out-of-range values. The1812* normalization and validation are handled by the1813* {@link #complete()} method, which process is calendar1814* system dependent.1815*1816* @param field the given calendar field.1817* @return the value for the given calendar field.1818* @throws ArrayIndexOutOfBoundsException if the specified field is out of range1819* (<code>field < 0 || field >= FIELD_COUNT</code>).1820* @see #set(int,int)1821* @see #complete()1822*/1823public int get(int field)1824{1825complete();1826return internalGet(field);1827}18281829/**1830* Returns the value of the given calendar field. This method does1831* not involve normalization or validation of the field value.1832*1833* @param field the given calendar field.1834* @return the value for the given calendar field.1835* @see #get(int)1836*/1837protected final int internalGet(int field)1838{1839return fields[field];1840}18411842/**1843* Sets the value of the given calendar field. This method does1844* not affect any setting state of the field in this1845* <code>Calendar</code> instance.1846*1847* @throws IndexOutOfBoundsException if the specified field is out of range1848* (<code>field < 0 || field >= FIELD_COUNT</code>).1849* @see #areFieldsSet1850* @see #isTimeSet1851* @see #areAllFieldsSet1852* @see #set(int,int)1853*/1854final void internalSet(int field, int value)1855{1856fields[field] = value;1857}18581859/**1860* Sets the given calendar field to the given value. The value is not1861* interpreted by this method regardless of the leniency mode.1862*1863* @param field the given calendar field.1864* @param value the value to be set for the given calendar field.1865* @throws ArrayIndexOutOfBoundsException if the specified field is out of range1866* (<code>field < 0 || field >= FIELD_COUNT</code>).1867* in non-lenient mode.1868* @see #set(int,int,int)1869* @see #set(int,int,int,int,int)1870* @see #set(int,int,int,int,int,int)1871* @see #get(int)1872*/1873public void set(int field, int value)1874{1875// If the fields are partially normalized, calculate all the1876// fields before changing any fields.1877if (areFieldsSet && !areAllFieldsSet) {1878computeFields();1879}1880internalSet(field, value);1881isTimeSet = false;1882areFieldsSet = false;1883isSet[field] = true;1884stamp[field] = nextStamp++;1885if (nextStamp == Integer.MAX_VALUE) {1886adjustStamp();1887}1888}18891890/**1891* Sets the values for the calendar fields <code>YEAR</code>,1892* <code>MONTH</code>, and <code>DAY_OF_MONTH</code>.1893* Previous values of other calendar fields are retained. If this is not desired,1894* call {@link #clear()} first.1895*1896* @param year the value used to set the <code>YEAR</code> calendar field.1897* @param month the value used to set the <code>MONTH</code> calendar field.1898* Month value is 0-based. e.g., 0 for January.1899* @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.1900* @see #set(int,int)1901* @see #set(int,int,int,int,int)1902* @see #set(int,int,int,int,int,int)1903*/1904public final void set(int year, int month, int date)1905{1906set(YEAR, year);1907set(MONTH, month);1908set(DATE, date);1909}19101911/**1912* Sets the values for the calendar fields <code>YEAR</code>,1913* <code>MONTH</code>, <code>DAY_OF_MONTH</code>,1914* <code>HOUR_OF_DAY</code>, and <code>MINUTE</code>.1915* Previous values of other fields are retained. If this is not desired,1916* call {@link #clear()} first.1917*1918* @param year the value used to set the <code>YEAR</code> calendar field.1919* @param month the value used to set the <code>MONTH</code> calendar field.1920* Month value is 0-based. e.g., 0 for January.1921* @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.1922* @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field.1923* @param minute the value used to set the <code>MINUTE</code> calendar field.1924* @see #set(int,int)1925* @see #set(int,int,int)1926* @see #set(int,int,int,int,int,int)1927*/1928public final void set(int year, int month, int date, int hourOfDay, int minute)1929{1930set(YEAR, year);1931set(MONTH, month);1932set(DATE, date);1933set(HOUR_OF_DAY, hourOfDay);1934set(MINUTE, minute);1935}19361937/**1938* Sets the values for the fields <code>YEAR</code>, <code>MONTH</code>,1939* <code>DAY_OF_MONTH</code>, <code>HOUR_OF_DAY</code>, <code>MINUTE</code>, and1940* <code>SECOND</code>.1941* Previous values of other fields are retained. If this is not desired,1942* call {@link #clear()} first.1943*1944* @param year the value used to set the <code>YEAR</code> calendar field.1945* @param month the value used to set the <code>MONTH</code> calendar field.1946* Month value is 0-based. e.g., 0 for January.1947* @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.1948* @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field.1949* @param minute the value used to set the <code>MINUTE</code> calendar field.1950* @param second the value used to set the <code>SECOND</code> calendar field.1951* @see #set(int,int)1952* @see #set(int,int,int)1953* @see #set(int,int,int,int,int)1954*/1955public final void set(int year, int month, int date, int hourOfDay, int minute,1956int second)1957{1958set(YEAR, year);1959set(MONTH, month);1960set(DATE, date);1961set(HOUR_OF_DAY, hourOfDay);1962set(MINUTE, minute);1963set(SECOND, second);1964}19651966/**1967* Sets all the calendar field values and the time value1968* (millisecond offset from the <a href="#Epoch">Epoch</a>) of1969* this <code>Calendar</code> undefined. This means that {@link1970* #isSet(int) isSet()} will return <code>false</code> for all the1971* calendar fields, and the date and time calculations will treat1972* the fields as if they had never been set. A1973* <code>Calendar</code> implementation class may use its specific1974* default field values for date/time calculations. For example,1975* <code>GregorianCalendar</code> uses 1970 if the1976* <code>YEAR</code> field value is undefined.1977*1978* @see #clear(int)1979*/1980public final void clear()1981{1982for (int i = 0; i < fields.length; ) {1983stamp[i] = fields[i] = 0; // UNSET == 01984isSet[i++] = false;1985}1986areAllFieldsSet = areFieldsSet = false;1987isTimeSet = false;1988}19891990/**1991* Sets the given calendar field value and the time value1992* (millisecond offset from the <a href="#Epoch">Epoch</a>) of1993* this <code>Calendar</code> undefined. This means that {@link1994* #isSet(int) isSet(field)} will return <code>false</code>, and1995* the date and time calculations will treat the field as if it1996* had never been set. A <code>Calendar</code> implementation1997* class may use the field's specific default value for date and1998* time calculations.1999*2000* <p>The {@link #HOUR_OF_DAY}, {@link #HOUR} and {@link #AM_PM}2001* fields are handled independently and the <a2002* href="#time_resolution">the resolution rule for the time of2003* day</a> is applied. Clearing one of the fields doesn't reset2004* the hour of day value of this <code>Calendar</code>. Use {@link2005* #set(int,int) set(Calendar.HOUR_OF_DAY, 0)} to reset the hour2006* value.2007*2008* @param field the calendar field to be cleared.2009* @see #clear()2010*/2011public final void clear(int field)2012{2013fields[field] = 0;2014stamp[field] = UNSET;2015isSet[field] = false;20162017areAllFieldsSet = areFieldsSet = false;2018isTimeSet = false;2019}20202021/**2022* Determines if the given calendar field has a value set,2023* including cases that the value has been set by internal fields2024* calculations triggered by a <code>get</code> method call.2025*2026* @param field the calendar field to test2027* @return <code>true</code> if the given calendar field has a value set;2028* <code>false</code> otherwise.2029*/2030public final boolean isSet(int field)2031{2032return stamp[field] != UNSET;2033}20342035/**2036* Returns the string representation of the calendar2037* <code>field</code> value in the given <code>style</code> and2038* <code>locale</code>. If no string representation is2039* applicable, <code>null</code> is returned. This method calls2040* {@link Calendar#get(int) get(field)} to get the calendar2041* <code>field</code> value if the string representation is2042* applicable to the given calendar <code>field</code>.2043*2044* <p>For example, if this <code>Calendar</code> is a2045* <code>GregorianCalendar</code> and its date is 2005-01-01, then2046* the string representation of the {@link #MONTH} field would be2047* "January" in the long style in an English locale or "Jan" in2048* the short style. However, no string representation would be2049* available for the {@link #DAY_OF_MONTH} field, and this method2050* would return <code>null</code>.2051*2052* <p>The default implementation supports the calendar fields for2053* which a {@link DateFormatSymbols} has names in the given2054* <code>locale</code>.2055*2056* @param field2057* the calendar field for which the string representation2058* is returned2059* @param style2060* the style applied to the string representation; one of {@link2061* #SHORT_FORMAT} ({@link #SHORT}), {@link #SHORT_STANDALONE},2062* {@link #LONG_FORMAT} ({@link #LONG}), {@link #LONG_STANDALONE},2063* {@link #NARROW_FORMAT}, or {@link #NARROW_STANDALONE}.2064* @param locale2065* the locale for the string representation2066* (any calendar types specified by {@code locale} are ignored)2067* @return the string representation of the given2068* {@code field} in the given {@code style}, or2069* {@code null} if no string representation is2070* applicable.2071* @exception IllegalArgumentException2072* if {@code field} or {@code style} is invalid,2073* or if this {@code Calendar} is non-lenient and any2074* of the calendar fields have invalid values2075* @exception NullPointerException2076* if {@code locale} is null2077* @since 1.62078*/2079public String getDisplayName(int field, int style, Locale locale) {2080if (!checkDisplayNameParams(field, style, SHORT, NARROW_FORMAT, locale,2081ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {2082return null;2083}20842085String calendarType = getCalendarType();2086int fieldValue = get(field);2087// the standalone and narrow styles are supported only through CalendarDataProviders.2088if (isStandaloneStyle(style) || isNarrowFormatStyle(style)) {2089String val = CalendarDataUtility.retrieveFieldValueName(calendarType,2090field, fieldValue,2091style, locale);2092// Perform fallback here to follow the CLDR rules2093if (val == null) {2094if (isNarrowFormatStyle(style)) {2095val = CalendarDataUtility.retrieveFieldValueName(calendarType,2096field, fieldValue,2097toStandaloneStyle(style),2098locale);2099} else if (isStandaloneStyle(style)) {2100val = CalendarDataUtility.retrieveFieldValueName(calendarType,2101field, fieldValue,2102getBaseStyle(style),2103locale);2104}2105}2106return val;2107}21082109DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);2110String[] strings = getFieldStrings(field, style, symbols);2111if (strings != null) {2112if (fieldValue < strings.length) {2113return strings[fieldValue];2114}2115}2116return null;2117}21182119/**2120* Returns a {@code Map} containing all names of the calendar2121* {@code field} in the given {@code style} and2122* {@code locale} and their corresponding field values. For2123* example, if this {@code Calendar} is a {@link2124* GregorianCalendar}, the returned map would contain "Jan" to2125* {@link #JANUARY}, "Feb" to {@link #FEBRUARY}, and so on, in the2126* {@linkplain #SHORT short} style in an English locale.2127*2128* <p>Narrow names may not be unique due to use of single characters,2129* such as "S" for Sunday and Saturday. In that case narrow names are not2130* included in the returned {@code Map}.2131*2132* <p>The values of other calendar fields may be taken into2133* account to determine a set of display names. For example, if2134* this {@code Calendar} is a lunisolar calendar system and2135* the year value given by the {@link #YEAR} field has a leap2136* month, this method would return month names containing the leap2137* month name, and month names are mapped to their values specific2138* for the year.2139*2140* <p>The default implementation supports display names contained in2141* a {@link DateFormatSymbols}. For example, if {@code field}2142* is {@link #MONTH} and {@code style} is {@link2143* #ALL_STYLES}, this method returns a {@code Map} containing2144* all strings returned by {@link DateFormatSymbols#getShortMonths()}2145* and {@link DateFormatSymbols#getMonths()}.2146*2147* @param field2148* the calendar field for which the display names are returned2149* @param style2150* the style applied to the string representation; one of {@link2151* #SHORT_FORMAT} ({@link #SHORT}), {@link #SHORT_STANDALONE},2152* {@link #LONG_FORMAT} ({@link #LONG}), {@link #LONG_STANDALONE},2153* {@link #NARROW_FORMAT}, or {@link #NARROW_STANDALONE}2154* @param locale2155* the locale for the display names2156* @return a {@code Map} containing all display names in2157* {@code style} and {@code locale} and their2158* field values, or {@code null} if no display names2159* are defined for {@code field}2160* @exception IllegalArgumentException2161* if {@code field} or {@code style} is invalid,2162* or if this {@code Calendar} is non-lenient and any2163* of the calendar fields have invalid values2164* @exception NullPointerException2165* if {@code locale} is null2166* @since 1.62167*/2168public Map<String, Integer> getDisplayNames(int field, int style, Locale locale) {2169if (!checkDisplayNameParams(field, style, ALL_STYLES, NARROW_FORMAT, locale,2170ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {2171return null;2172}21732174String calendarType = getCalendarType();2175if (style == ALL_STYLES || isStandaloneStyle(style) || isNarrowFormatStyle(style)) {2176Map<String, Integer> map;2177map = CalendarDataUtility.retrieveFieldValueNames(calendarType, field, style, locale);21782179// Perform fallback here to follow the CLDR rules2180if (map == null) {2181if (isNarrowFormatStyle(style)) {2182map = CalendarDataUtility.retrieveFieldValueNames(calendarType, field,2183toStandaloneStyle(style), locale);2184} else if (style != ALL_STYLES) {2185map = CalendarDataUtility.retrieveFieldValueNames(calendarType, field,2186getBaseStyle(style), locale);2187}2188}2189return map;2190}21912192// SHORT or LONG2193return getDisplayNamesImpl(field, style, locale);2194}21952196private Map<String,Integer> getDisplayNamesImpl(int field, int style, Locale locale) {2197DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);2198String[] strings = getFieldStrings(field, style, symbols);2199if (strings != null) {2200Map<String,Integer> names = new HashMap<>();2201for (int i = 0; i < strings.length; i++) {2202if (strings[i].length() == 0) {2203continue;2204}2205names.put(strings[i], i);2206}2207return names;2208}2209return null;2210}22112212boolean checkDisplayNameParams(int field, int style, int minStyle, int maxStyle,2213Locale locale, int fieldMask) {2214int baseStyle = getBaseStyle(style); // Ignore the standalone mask2215if (field < 0 || field >= fields.length ||2216baseStyle < minStyle || baseStyle > maxStyle) {2217throw new IllegalArgumentException();2218}2219if (locale == null) {2220throw new NullPointerException();2221}2222return isFieldSet(fieldMask, field);2223}22242225private String[] getFieldStrings(int field, int style, DateFormatSymbols symbols) {2226int baseStyle = getBaseStyle(style); // ignore the standalone mask22272228// DateFormatSymbols doesn't support any narrow names.2229if (baseStyle == NARROW_FORMAT) {2230return null;2231}22322233String[] strings = null;2234switch (field) {2235case ERA:2236strings = symbols.getEras();2237break;22382239case MONTH:2240strings = (baseStyle == LONG) ? symbols.getMonths() : symbols.getShortMonths();2241break;22422243case DAY_OF_WEEK:2244strings = (baseStyle == LONG) ? symbols.getWeekdays() : symbols.getShortWeekdays();2245break;22462247case AM_PM:2248strings = symbols.getAmPmStrings();2249break;2250}2251return strings;2252}22532254/**2255* Fills in any unset fields in the calendar fields. First, the {@link2256* #computeTime()} method is called if the time value (millisecond offset2257* from the <a href="#Epoch">Epoch</a>) has not been calculated from2258* calendar field values. Then, the {@link #computeFields()} method is2259* called to calculate all calendar field values.2260*/2261protected void complete()2262{2263if (!isTimeSet) {2264updateTime();2265}2266if (!areFieldsSet || !areAllFieldsSet) {2267computeFields(); // fills in unset fields2268areAllFieldsSet = areFieldsSet = true;2269}2270}22712272/**2273* Returns whether the value of the specified calendar field has been set2274* externally by calling one of the setter methods rather than by the2275* internal time calculation.2276*2277* @return <code>true</code> if the field has been set externally,2278* <code>false</code> otherwise.2279* @exception IndexOutOfBoundsException if the specified2280* <code>field</code> is out of range2281* (<code>field < 0 || field >= FIELD_COUNT</code>).2282* @see #selectFields()2283* @see #setFieldsComputed(int)2284*/2285final boolean isExternallySet(int field) {2286return stamp[field] >= MINIMUM_USER_STAMP;2287}22882289/**2290* Returns a field mask (bit mask) indicating all calendar fields that2291* have the state of externally or internally set.2292*2293* @return a bit mask indicating set state fields2294*/2295final int getSetStateFields() {2296int mask = 0;2297for (int i = 0; i < fields.length; i++) {2298if (stamp[i] != UNSET) {2299mask |= 1 << i;2300}2301}2302return mask;2303}23042305/**2306* Sets the state of the specified calendar fields to2307* <em>computed</em>. This state means that the specified calendar fields2308* have valid values that have been set by internal time calculation2309* rather than by calling one of the setter methods.2310*2311* @param fieldMask the field to be marked as computed.2312* @exception IndexOutOfBoundsException if the specified2313* <code>field</code> is out of range2314* (<code>field < 0 || field >= FIELD_COUNT</code>).2315* @see #isExternallySet(int)2316* @see #selectFields()2317*/2318final void setFieldsComputed(int fieldMask) {2319if (fieldMask == ALL_FIELDS) {2320for (int i = 0; i < fields.length; i++) {2321stamp[i] = COMPUTED;2322isSet[i] = true;2323}2324areFieldsSet = areAllFieldsSet = true;2325} else {2326for (int i = 0; i < fields.length; i++) {2327if ((fieldMask & 1) == 1) {2328stamp[i] = COMPUTED;2329isSet[i] = true;2330} else {2331if (areAllFieldsSet && !isSet[i]) {2332areAllFieldsSet = false;2333}2334}2335fieldMask >>>= 1;2336}2337}2338}23392340/**2341* Sets the state of the calendar fields that are <em>not</em> specified2342* by <code>fieldMask</code> to <em>unset</em>. If <code>fieldMask</code>2343* specifies all the calendar fields, then the state of this2344* <code>Calendar</code> becomes that all the calendar fields are in sync2345* with the time value (millisecond offset from the Epoch).2346*2347* @param fieldMask the field mask indicating which calendar fields are in2348* sync with the time value.2349* @exception IndexOutOfBoundsException if the specified2350* <code>field</code> is out of range2351* (<code>field < 0 || field >= FIELD_COUNT</code>).2352* @see #isExternallySet(int)2353* @see #selectFields()2354*/2355final void setFieldsNormalized(int fieldMask) {2356if (fieldMask != ALL_FIELDS) {2357for (int i = 0; i < fields.length; i++) {2358if ((fieldMask & 1) == 0) {2359stamp[i] = fields[i] = 0; // UNSET == 02360isSet[i] = false;2361}2362fieldMask >>= 1;2363}2364}23652366// Some or all of the fields are in sync with the2367// milliseconds, but the stamp values are not normalized yet.2368areFieldsSet = true;2369areAllFieldsSet = false;2370}23712372/**2373* Returns whether the calendar fields are partially in sync with the time2374* value or fully in sync but not stamp values are not normalized yet.2375*/2376final boolean isPartiallyNormalized() {2377return areFieldsSet && !areAllFieldsSet;2378}23792380/**2381* Returns whether the calendar fields are fully in sync with the time2382* value.2383*/2384final boolean isFullyNormalized() {2385return areFieldsSet && areAllFieldsSet;2386}23872388/**2389* Marks this Calendar as not sync'd.2390*/2391final void setUnnormalized() {2392areFieldsSet = areAllFieldsSet = false;2393}23942395/**2396* Returns whether the specified <code>field</code> is on in the2397* <code>fieldMask</code>.2398*/2399static boolean isFieldSet(int fieldMask, int field) {2400return (fieldMask & (1 << field)) != 0;2401}24022403/**2404* Returns a field mask indicating which calendar field values2405* to be used to calculate the time value. The calendar fields are2406* returned as a bit mask, each bit of which corresponds to a field, i.e.,2407* the mask value of <code>field</code> is <code>(1 <<2408* field)</code>. For example, 0x26 represents the <code>YEAR</code>,2409* <code>MONTH</code>, and <code>DAY_OF_MONTH</code> fields (i.e., 0x26 is2410* equal to2411* <code>(1<<YEAR)|(1<<MONTH)|(1<<DAY_OF_MONTH))</code>.2412*2413* <p>This method supports the calendar fields resolution as described in2414* the class description. If the bit mask for a given field is on and its2415* field has not been set (i.e., <code>isSet(field)</code> is2416* <code>false</code>), then the default value of the field has to be2417* used, which case means that the field has been selected because the2418* selected combination involves the field.2419*2420* @return a bit mask of selected fields2421* @see #isExternallySet(int)2422*/2423final int selectFields() {2424// This implementation has been taken from the GregorianCalendar class.24252426// The YEAR field must always be used regardless of its SET2427// state because YEAR is a mandatory field to determine the date2428// and the default value (EPOCH_YEAR) may change through the2429// normalization process.2430int fieldMask = YEAR_MASK;24312432if (stamp[ERA] != UNSET) {2433fieldMask |= ERA_MASK;2434}2435// Find the most recent group of fields specifying the day within2436// the year. These may be any of the following combinations:2437// MONTH + DAY_OF_MONTH2438// MONTH + WEEK_OF_MONTH + DAY_OF_WEEK2439// MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK2440// DAY_OF_YEAR2441// WEEK_OF_YEAR + DAY_OF_WEEK2442// We look for the most recent of the fields in each group to determine2443// the age of the group. For groups involving a week-related field such2444// as WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR, both the2445// week-related field and the DAY_OF_WEEK must be set for the group as a2446// whole to be considered. (See bug 4153860 - liu 7/24/98.)2447int dowStamp = stamp[DAY_OF_WEEK];2448int monthStamp = stamp[MONTH];2449int domStamp = stamp[DAY_OF_MONTH];2450int womStamp = aggregateStamp(stamp[WEEK_OF_MONTH], dowStamp);2451int dowimStamp = aggregateStamp(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);2452int doyStamp = stamp[DAY_OF_YEAR];2453int woyStamp = aggregateStamp(stamp[WEEK_OF_YEAR], dowStamp);24542455int bestStamp = domStamp;2456if (womStamp > bestStamp) {2457bestStamp = womStamp;2458}2459if (dowimStamp > bestStamp) {2460bestStamp = dowimStamp;2461}2462if (doyStamp > bestStamp) {2463bestStamp = doyStamp;2464}2465if (woyStamp > bestStamp) {2466bestStamp = woyStamp;2467}24682469/* No complete combination exists. Look for WEEK_OF_MONTH,2470* DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR alone. Treat DAY_OF_WEEK alone2471* as DAY_OF_WEEK_IN_MONTH.2472*/2473if (bestStamp == UNSET) {2474womStamp = stamp[WEEK_OF_MONTH];2475dowimStamp = Math.max(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);2476woyStamp = stamp[WEEK_OF_YEAR];2477bestStamp = Math.max(Math.max(womStamp, dowimStamp), woyStamp);24782479/* Treat MONTH alone or no fields at all as DAY_OF_MONTH. This may2480* result in bestStamp = domStamp = UNSET if no fields are set,2481* which indicates DAY_OF_MONTH.2482*/2483if (bestStamp == UNSET) {2484bestStamp = domStamp = monthStamp;2485}2486}24872488if (bestStamp == domStamp ||2489(bestStamp == womStamp && stamp[WEEK_OF_MONTH] >= stamp[WEEK_OF_YEAR]) ||2490(bestStamp == dowimStamp && stamp[DAY_OF_WEEK_IN_MONTH] >= stamp[WEEK_OF_YEAR])) {2491fieldMask |= MONTH_MASK;2492if (bestStamp == domStamp) {2493fieldMask |= DAY_OF_MONTH_MASK;2494} else {2495assert (bestStamp == womStamp || bestStamp == dowimStamp);2496if (dowStamp != UNSET) {2497fieldMask |= DAY_OF_WEEK_MASK;2498}2499if (womStamp == dowimStamp) {2500// When they are equal, give the priority to2501// WEEK_OF_MONTH for compatibility.2502if (stamp[WEEK_OF_MONTH] >= stamp[DAY_OF_WEEK_IN_MONTH]) {2503fieldMask |= WEEK_OF_MONTH_MASK;2504} else {2505fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK;2506}2507} else {2508if (bestStamp == womStamp) {2509fieldMask |= WEEK_OF_MONTH_MASK;2510} else {2511assert (bestStamp == dowimStamp);2512if (stamp[DAY_OF_WEEK_IN_MONTH] != UNSET) {2513fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK;2514}2515}2516}2517}2518} else {2519assert (bestStamp == doyStamp || bestStamp == woyStamp ||2520bestStamp == UNSET);2521if (bestStamp == doyStamp) {2522fieldMask |= DAY_OF_YEAR_MASK;2523} else {2524assert (bestStamp == woyStamp);2525if (dowStamp != UNSET) {2526fieldMask |= DAY_OF_WEEK_MASK;2527}2528fieldMask |= WEEK_OF_YEAR_MASK;2529}2530}25312532// Find the best set of fields specifying the time of day. There2533// are only two possibilities here; the HOUR_OF_DAY or the2534// AM_PM and the HOUR.2535int hourOfDayStamp = stamp[HOUR_OF_DAY];2536int hourStamp = aggregateStamp(stamp[HOUR], stamp[AM_PM]);2537bestStamp = (hourStamp > hourOfDayStamp) ? hourStamp : hourOfDayStamp;25382539// if bestStamp is still UNSET, then take HOUR or AM_PM. (See 4846659)2540if (bestStamp == UNSET) {2541bestStamp = Math.max(stamp[HOUR], stamp[AM_PM]);2542}25432544// Hours2545if (bestStamp != UNSET) {2546if (bestStamp == hourOfDayStamp) {2547fieldMask |= HOUR_OF_DAY_MASK;2548} else {2549fieldMask |= HOUR_MASK;2550if (stamp[AM_PM] != UNSET) {2551fieldMask |= AM_PM_MASK;2552}2553}2554}2555if (stamp[MINUTE] != UNSET) {2556fieldMask |= MINUTE_MASK;2557}2558if (stamp[SECOND] != UNSET) {2559fieldMask |= SECOND_MASK;2560}2561if (stamp[MILLISECOND] != UNSET) {2562fieldMask |= MILLISECOND_MASK;2563}2564if (stamp[ZONE_OFFSET] >= MINIMUM_USER_STAMP) {2565fieldMask |= ZONE_OFFSET_MASK;2566}2567if (stamp[DST_OFFSET] >= MINIMUM_USER_STAMP) {2568fieldMask |= DST_OFFSET_MASK;2569}25702571return fieldMask;2572}25732574int getBaseStyle(int style) {2575return style & ~STANDALONE_MASK;2576}25772578private int toStandaloneStyle(int style) {2579return style | STANDALONE_MASK;2580}25812582private boolean isStandaloneStyle(int style) {2583return (style & STANDALONE_MASK) != 0;2584}25852586private boolean isNarrowStyle(int style) {2587return style == NARROW_FORMAT || style == NARROW_STANDALONE;2588}25892590private boolean isNarrowFormatStyle(int style) {2591return style == NARROW_FORMAT;2592}25932594/**2595* Returns the pseudo-time-stamp for two fields, given their2596* individual pseudo-time-stamps. If either of the fields2597* is unset, then the aggregate is unset. Otherwise, the2598* aggregate is the later of the two stamps.2599*/2600private static int aggregateStamp(int stamp_a, int stamp_b) {2601if (stamp_a == UNSET || stamp_b == UNSET) {2602return UNSET;2603}2604return (stamp_a > stamp_b) ? stamp_a : stamp_b;2605}26062607/**2608* Returns an unmodifiable {@code Set} containing all calendar types2609* supported by {@code Calendar} in the runtime environment. The available2610* calendar types can be used for the <a2611* href="Locale.html#def_locale_extension">Unicode locale extensions</a>.2612* The {@code Set} returned contains at least {@code "gregory"}. The2613* calendar types don't include aliases, such as {@code "gregorian"} for2614* {@code "gregory"}.2615*2616* @return an unmodifiable {@code Set} containing all available calendar types2617* @since 1.82618* @see #getCalendarType()2619* @see Calendar.Builder#setCalendarType(String)2620* @see Locale#getUnicodeLocaleType(String)2621*/2622public static Set<String> getAvailableCalendarTypes() {2623return AvailableCalendarTypes.SET;2624}26252626private static class AvailableCalendarTypes {2627private static final Set<String> SET;2628static {2629Set<String> set = new HashSet<>(3);2630set.add("gregory");2631set.add("buddhist");2632set.add("japanese");2633SET = Collections.unmodifiableSet(set);2634}2635private AvailableCalendarTypes() {2636}2637}26382639/**2640* Returns the calendar type of this {@code Calendar}. Calendar types are2641* defined by the <em>Unicode Locale Data Markup Language (LDML)</em>2642* specification.2643*2644* <p>The default implementation of this method returns the class name of2645* this {@code Calendar} instance. Any subclasses that implement2646* LDML-defined calendar systems should override this method to return2647* appropriate calendar types.2648*2649* @return the LDML-defined calendar type or the class name of this2650* {@code Calendar} instance2651* @since 1.82652* @see <a href="Locale.html#def_extensions">Locale extensions</a>2653* @see Locale.Builder#setLocale(Locale)2654* @see Locale.Builder#setUnicodeLocaleKeyword(String, String)2655*/2656public String getCalendarType() {2657return this.getClass().getName();2658}26592660/**2661* Compares this <code>Calendar</code> to the specified2662* <code>Object</code>. The result is <code>true</code> if and only if2663* the argument is a <code>Calendar</code> object of the same calendar2664* system that represents the same time value (millisecond offset from the2665* <a href="#Epoch">Epoch</a>) under the same2666* <code>Calendar</code> parameters as this object.2667*2668* <p>The <code>Calendar</code> parameters are the values represented2669* by the <code>isLenient</code>, <code>getFirstDayOfWeek</code>,2670* <code>getMinimalDaysInFirstWeek</code> and <code>getTimeZone</code>2671* methods. If there is any difference in those parameters2672* between the two <code>Calendar</code>s, this method returns2673* <code>false</code>.2674*2675* <p>Use the {@link #compareTo(Calendar) compareTo} method to2676* compare only the time values.2677*2678* @param obj the object to compare with.2679* @return <code>true</code> if this object is equal to <code>obj</code>;2680* <code>false</code> otherwise.2681*/2682@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")2683@Override2684public boolean equals(Object obj) {2685if (this == obj) {2686return true;2687}2688try {2689Calendar that = (Calendar)obj;2690return compareTo(getMillisOf(that)) == 0 &&2691lenient == that.lenient &&2692firstDayOfWeek == that.firstDayOfWeek &&2693minimalDaysInFirstWeek == that.minimalDaysInFirstWeek &&2694(zone instanceof ZoneInfo ?2695zone.equals(that.zone) :2696zone.equals(that.getTimeZone()));2697} catch (Exception e) {2698// Note: GregorianCalendar.computeTime throws2699// IllegalArgumentException if the ERA value is invalid2700// even it's in lenient mode.2701}2702return false;2703}27042705/**2706* Returns a hash code for this calendar.2707*2708* @return a hash code value for this object.2709* @since 1.22710*/2711@Override2712public int hashCode() {2713// 'otheritems' represents the hash code for the previous versions.2714int otheritems = (lenient ? 1 : 0)2715| (firstDayOfWeek << 1)2716| (minimalDaysInFirstWeek << 4)2717| (zone.hashCode() << 7);2718long t = getMillisOf(this);2719return (int) t ^ (int)(t >> 32) ^ otheritems;2720}27212722/**2723* Returns whether this <code>Calendar</code> represents a time2724* before the time represented by the specified2725* <code>Object</code>. This method is equivalent to:2726* <pre>{@code2727* compareTo(when) < 02728* }</pre>2729* if and only if <code>when</code> is a <code>Calendar</code>2730* instance. Otherwise, the method returns <code>false</code>.2731*2732* @param when the <code>Object</code> to be compared2733* @return <code>true</code> if the time of this2734* <code>Calendar</code> is before the time represented by2735* <code>when</code>; <code>false</code> otherwise.2736* @see #compareTo(Calendar)2737*/2738public boolean before(Object when) {2739return when instanceof Calendar2740&& compareTo((Calendar)when) < 0;2741}27422743/**2744* Returns whether this <code>Calendar</code> represents a time2745* after the time represented by the specified2746* <code>Object</code>. This method is equivalent to:2747* <pre>{@code2748* compareTo(when) > 02749* }</pre>2750* if and only if <code>when</code> is a <code>Calendar</code>2751* instance. Otherwise, the method returns <code>false</code>.2752*2753* @param when the <code>Object</code> to be compared2754* @return <code>true</code> if the time of this <code>Calendar</code> is2755* after the time represented by <code>when</code>; <code>false</code>2756* otherwise.2757* @see #compareTo(Calendar)2758*/2759public boolean after(Object when) {2760return when instanceof Calendar2761&& compareTo((Calendar)when) > 0;2762}27632764/**2765* Compares the time values (millisecond offsets from the <a2766* href="#Epoch">Epoch</a>) represented by two2767* <code>Calendar</code> objects.2768*2769* @param anotherCalendar the <code>Calendar</code> to be compared.2770* @return the value <code>0</code> if the time represented by the argument2771* is equal to the time represented by this <code>Calendar</code>; a value2772* less than <code>0</code> if the time of this <code>Calendar</code> is2773* before the time represented by the argument; and a value greater than2774* <code>0</code> if the time of this <code>Calendar</code> is after the2775* time represented by the argument.2776* @exception NullPointerException if the specified <code>Calendar</code> is2777* <code>null</code>.2778* @exception IllegalArgumentException if the time value of the2779* specified <code>Calendar</code> object can't be obtained due to2780* any invalid calendar values.2781* @since 1.52782*/2783@Override2784public int compareTo(Calendar anotherCalendar) {2785return compareTo(getMillisOf(anotherCalendar));2786}27872788/**2789* Adds or subtracts the specified amount of time to the given calendar field,2790* based on the calendar's rules. For example, to subtract 5 days from2791* the current time of the calendar, you can achieve it by calling:2792* <p><code>add(Calendar.DAY_OF_MONTH, -5)</code>.2793*2794* @param field the calendar field.2795* @param amount the amount of date or time to be added to the field.2796* @see #roll(int,int)2797* @see #set(int,int)2798*/2799abstract public void add(int field, int amount);28002801/**2802* Adds or subtracts (up/down) a single unit of time on the given time2803* field without changing larger fields. For example, to roll the current2804* date up by one day, you can achieve it by calling:2805* <p>roll(Calendar.DATE, true).2806* When rolling on the year or Calendar.YEAR field, it will roll the year2807* value in the range between 1 and the value returned by calling2808* <code>getMaximum(Calendar.YEAR)</code>.2809* When rolling on the month or Calendar.MONTH field, other fields like2810* date might conflict and, need to be changed. For instance,2811* rolling the month on the date 01/31/96 will result in 02/29/96.2812* When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field, it will2813* roll the hour value in the range between 0 and 23, which is zero-based.2814*2815* @param field the time field.2816* @param up indicates if the value of the specified time field is to be2817* rolled up or rolled down. Use true if rolling up, false otherwise.2818* @see Calendar#add(int,int)2819* @see Calendar#set(int,int)2820*/2821abstract public void roll(int field, boolean up);28222823/**2824* Adds the specified (signed) amount to the specified calendar field2825* without changing larger fields. A negative amount means to roll2826* down.2827*2828* <p>NOTE: This default implementation on <code>Calendar</code> just repeatedly calls the2829* version of {@link #roll(int,boolean) roll()} that rolls by one unit. This may not2830* always do the right thing. For example, if the <code>DAY_OF_MONTH</code> field is 31,2831* rolling through February will leave it set to 28. The <code>GregorianCalendar</code>2832* version of this function takes care of this problem. Other subclasses2833* should also provide overrides of this function that do the right thing.2834*2835* @param field the calendar field.2836* @param amount the signed amount to add to the calendar <code>field</code>.2837* @since 1.22838* @see #roll(int,boolean)2839* @see #add(int,int)2840* @see #set(int,int)2841*/2842public void roll(int field, int amount)2843{2844while (amount > 0) {2845roll(field, true);2846amount--;2847}2848while (amount < 0) {2849roll(field, false);2850amount++;2851}2852}28532854/**2855* Sets the time zone with the given time zone value.2856*2857* @param value the given time zone.2858*/2859public void setTimeZone(TimeZone value)2860{2861zone = value;2862sharedZone = false;2863/* Recompute the fields from the time using the new zone. This also2864* works if isTimeSet is false (after a call to set()). In that case2865* the time will be computed from the fields using the new zone, then2866* the fields will get recomputed from that. Consider the sequence of2867* calls: cal.setTimeZone(EST); cal.set(HOUR, 1); cal.setTimeZone(PST).2868* Is cal set to 1 o'clock EST or 1 o'clock PST? Answer: PST. More2869* generally, a call to setTimeZone() affects calls to set() BEFORE AND2870* AFTER it up to the next call to complete().2871*/2872areAllFieldsSet = areFieldsSet = false;2873}28742875/**2876* Gets the time zone.2877*2878* @return the time zone object associated with this calendar.2879*/2880public TimeZone getTimeZone()2881{2882// If the TimeZone object is shared by other Calendar instances, then2883// create a clone.2884if (sharedZone) {2885zone = (TimeZone) zone.clone();2886sharedZone = false;2887}2888return zone;2889}28902891/**2892* Returns the time zone (without cloning).2893*/2894TimeZone getZone() {2895return zone;2896}28972898/**2899* Sets the sharedZone flag to <code>shared</code>.2900*/2901void setZoneShared(boolean shared) {2902sharedZone = shared;2903}29042905/**2906* Specifies whether or not date/time interpretation is to be lenient. With2907* lenient interpretation, a date such as "February 942, 1996" will be2908* treated as being equivalent to the 941st day after February 1, 1996.2909* With strict (non-lenient) interpretation, such dates will cause an exception to be2910* thrown. The default is lenient.2911*2912* @param lenient <code>true</code> if the lenient mode is to be turned2913* on; <code>false</code> if it is to be turned off.2914* @see #isLenient()2915* @see java.text.DateFormat#setLenient2916*/2917public void setLenient(boolean lenient)2918{2919this.lenient = lenient;2920}29212922/**2923* Tells whether date/time interpretation is to be lenient.2924*2925* @return <code>true</code> if the interpretation mode of this calendar is lenient;2926* <code>false</code> otherwise.2927* @see #setLenient(boolean)2928*/2929public boolean isLenient()2930{2931return lenient;2932}29332934/**2935* Sets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,2936* <code>MONDAY</code> in France.2937*2938* @param value the given first day of the week.2939* @see #getFirstDayOfWeek()2940* @see #getMinimalDaysInFirstWeek()2941*/2942public void setFirstDayOfWeek(int value)2943{2944if (firstDayOfWeek == value) {2945return;2946}2947firstDayOfWeek = value;2948invalidateWeekFields();2949}29502951/**2952* Gets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,2953* <code>MONDAY</code> in France.2954*2955* @return the first day of the week.2956* @see #setFirstDayOfWeek(int)2957* @see #getMinimalDaysInFirstWeek()2958*/2959public int getFirstDayOfWeek()2960{2961return firstDayOfWeek;2962}29632964/**2965* Sets what the minimal days required in the first week of the year are;2966* For example, if the first week is defined as one that contains the first2967* day of the first month of a year, call this method with value 1. If it2968* must be a full week, use value 7.2969*2970* @param value the given minimal days required in the first week2971* of the year.2972* @see #getMinimalDaysInFirstWeek()2973*/2974public void setMinimalDaysInFirstWeek(int value)2975{2976if (minimalDaysInFirstWeek == value) {2977return;2978}2979minimalDaysInFirstWeek = value;2980invalidateWeekFields();2981}29822983/**2984* Gets what the minimal days required in the first week of the year are;2985* e.g., if the first week is defined as one that contains the first day2986* of the first month of a year, this method returns 1. If2987* the minimal days required must be a full week, this method2988* returns 7.2989*2990* @return the minimal days required in the first week of the year.2991* @see #setMinimalDaysInFirstWeek(int)2992*/2993public int getMinimalDaysInFirstWeek()2994{2995return minimalDaysInFirstWeek;2996}29972998/**2999* Returns whether this {@code Calendar} supports week dates.3000*3001* <p>The default implementation of this method returns {@code false}.3002*3003* @return {@code true} if this {@code Calendar} supports week dates;3004* {@code false} otherwise.3005* @see #getWeekYear()3006* @see #setWeekDate(int,int,int)3007* @see #getWeeksInWeekYear()3008* @since 1.73009*/3010public boolean isWeekDateSupported() {3011return false;3012}30133014/**3015* Returns the week year represented by this {@code Calendar}. The3016* week year is in sync with the week cycle. The {@linkplain3017* #getFirstDayOfWeek() first day of the first week} is the first3018* day of the week year.3019*3020* <p>The default implementation of this method throws an3021* {@link UnsupportedOperationException}.3022*3023* @return the week year of this {@code Calendar}3024* @exception UnsupportedOperationException3025* if any week year numbering isn't supported3026* in this {@code Calendar}.3027* @see #isWeekDateSupported()3028* @see #getFirstDayOfWeek()3029* @see #getMinimalDaysInFirstWeek()3030* @since 1.73031*/3032public int getWeekYear() {3033throw new UnsupportedOperationException();3034}30353036/**3037* Sets the date of this {@code Calendar} with the the given date3038* specifiers - week year, week of year, and day of week.3039*3040* <p>Unlike the {@code set} method, all of the calendar fields3041* and {@code time} values are calculated upon return.3042*3043* <p>If {@code weekOfYear} is out of the valid week-of-year range3044* in {@code weekYear}, the {@code weekYear} and {@code3045* weekOfYear} values are adjusted in lenient mode, or an {@code3046* IllegalArgumentException} is thrown in non-lenient mode.3047*3048* <p>The default implementation of this method throws an3049* {@code UnsupportedOperationException}.3050*3051* @param weekYear the week year3052* @param weekOfYear the week number based on {@code weekYear}3053* @param dayOfWeek the day of week value: one of the constants3054* for the {@link #DAY_OF_WEEK} field: {@link3055* #SUNDAY}, ..., {@link #SATURDAY}.3056* @exception IllegalArgumentException3057* if any of the given date specifiers is invalid3058* or any of the calendar fields are inconsistent3059* with the given date specifiers in non-lenient mode3060* @exception UnsupportedOperationException3061* if any week year numbering isn't supported in this3062* {@code Calendar}.3063* @see #isWeekDateSupported()3064* @see #getFirstDayOfWeek()3065* @see #getMinimalDaysInFirstWeek()3066* @since 1.73067*/3068public void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) {3069throw new UnsupportedOperationException();3070}30713072/**3073* Returns the number of weeks in the week year represented by this3074* {@code Calendar}.3075*3076* <p>The default implementation of this method throws an3077* {@code UnsupportedOperationException}.3078*3079* @return the number of weeks in the week year.3080* @exception UnsupportedOperationException3081* if any week year numbering isn't supported in this3082* {@code Calendar}.3083* @see #WEEK_OF_YEAR3084* @see #isWeekDateSupported()3085* @see #getWeekYear()3086* @see #getActualMaximum(int)3087* @since 1.73088*/3089public int getWeeksInWeekYear() {3090throw new UnsupportedOperationException();3091}30923093/**3094* Returns the minimum value for the given calendar field of this3095* <code>Calendar</code> instance. The minimum value is defined as3096* the smallest value returned by the {@link #get(int) get} method3097* for any possible time value. The minimum value depends on3098* calendar system specific parameters of the instance.3099*3100* @param field the calendar field.3101* @return the minimum value for the given calendar field.3102* @see #getMaximum(int)3103* @see #getGreatestMinimum(int)3104* @see #getLeastMaximum(int)3105* @see #getActualMinimum(int)3106* @see #getActualMaximum(int)3107*/3108abstract public int getMinimum(int field);31093110/**3111* Returns the maximum value for the given calendar field of this3112* <code>Calendar</code> instance. The maximum value is defined as3113* the largest value returned by the {@link #get(int) get} method3114* for any possible time value. The maximum value depends on3115* calendar system specific parameters of the instance.3116*3117* @param field the calendar field.3118* @return the maximum value for the given calendar field.3119* @see #getMinimum(int)3120* @see #getGreatestMinimum(int)3121* @see #getLeastMaximum(int)3122* @see #getActualMinimum(int)3123* @see #getActualMaximum(int)3124*/3125abstract public int getMaximum(int field);31263127/**3128* Returns the highest minimum value for the given calendar field3129* of this <code>Calendar</code> instance. The highest minimum3130* value is defined as the largest value returned by {@link3131* #getActualMinimum(int)} for any possible time value. The3132* greatest minimum value depends on calendar system specific3133* parameters of the instance.3134*3135* @param field the calendar field.3136* @return the highest minimum value for the given calendar field.3137* @see #getMinimum(int)3138* @see #getMaximum(int)3139* @see #getLeastMaximum(int)3140* @see #getActualMinimum(int)3141* @see #getActualMaximum(int)3142*/3143abstract public int getGreatestMinimum(int field);31443145/**3146* Returns the lowest maximum value for the given calendar field3147* of this <code>Calendar</code> instance. The lowest maximum3148* value is defined as the smallest value returned by {@link3149* #getActualMaximum(int)} for any possible time value. The least3150* maximum value depends on calendar system specific parameters of3151* the instance. For example, a <code>Calendar</code> for the3152* Gregorian calendar system returns 28 for the3153* <code>DAY_OF_MONTH</code> field, because the 28th is the last3154* day of the shortest month of this calendar, February in a3155* common year.3156*3157* @param field the calendar field.3158* @return the lowest maximum value for the given calendar field.3159* @see #getMinimum(int)3160* @see #getMaximum(int)3161* @see #getGreatestMinimum(int)3162* @see #getActualMinimum(int)3163* @see #getActualMaximum(int)3164*/3165abstract public int getLeastMaximum(int field);31663167/**3168* Returns the minimum value that the specified calendar field3169* could have, given the time value of this <code>Calendar</code>.3170*3171* <p>The default implementation of this method uses an iterative3172* algorithm to determine the actual minimum value for the3173* calendar field. Subclasses should, if possible, override this3174* with a more efficient implementation - in many cases, they can3175* simply return <code>getMinimum()</code>.3176*3177* @param field the calendar field3178* @return the minimum of the given calendar field for the time3179* value of this <code>Calendar</code>3180* @see #getMinimum(int)3181* @see #getMaximum(int)3182* @see #getGreatestMinimum(int)3183* @see #getLeastMaximum(int)3184* @see #getActualMaximum(int)3185* @since 1.23186*/3187public int getActualMinimum(int field) {3188int fieldValue = getGreatestMinimum(field);3189int endValue = getMinimum(field);31903191// if we know that the minimum value is always the same, just return it3192if (fieldValue == endValue) {3193return fieldValue;3194}31953196// clone the calendar so we don't mess with the real one, and set it to3197// accept anything for the field values3198Calendar work = (Calendar)this.clone();3199work.setLenient(true);32003201// now try each value from getLeastMaximum() to getMaximum() one by one until3202// we get a value that normalizes to another value. The last value that3203// normalizes to itself is the actual minimum for the current date3204int result = fieldValue;32053206do {3207work.set(field, fieldValue);3208if (work.get(field) != fieldValue) {3209break;3210} else {3211result = fieldValue;3212fieldValue--;3213}3214} while (fieldValue >= endValue);32153216return result;3217}32183219/**3220* Returns the maximum value that the specified calendar field3221* could have, given the time value of this3222* <code>Calendar</code>. For example, the actual maximum value of3223* the <code>MONTH</code> field is 12 in some years, and 13 in3224* other years in the Hebrew calendar system.3225*3226* <p>The default implementation of this method uses an iterative3227* algorithm to determine the actual maximum value for the3228* calendar field. Subclasses should, if possible, override this3229* with a more efficient implementation.3230*3231* @param field the calendar field3232* @return the maximum of the given calendar field for the time3233* value of this <code>Calendar</code>3234* @see #getMinimum(int)3235* @see #getMaximum(int)3236* @see #getGreatestMinimum(int)3237* @see #getLeastMaximum(int)3238* @see #getActualMinimum(int)3239* @since 1.23240*/3241public int getActualMaximum(int field) {3242int fieldValue = getLeastMaximum(field);3243int endValue = getMaximum(field);32443245// if we know that the maximum value is always the same, just return it.3246if (fieldValue == endValue) {3247return fieldValue;3248}32493250// clone the calendar so we don't mess with the real one, and set it to3251// accept anything for the field values.3252Calendar work = (Calendar)this.clone();3253work.setLenient(true);32543255// if we're counting weeks, set the day of the week to Sunday. We know the3256// last week of a month or year will contain the first day of the week.3257if (field == WEEK_OF_YEAR || field == WEEK_OF_MONTH) {3258work.set(DAY_OF_WEEK, firstDayOfWeek);3259}32603261// now try each value from getLeastMaximum() to getMaximum() one by one until3262// we get a value that normalizes to another value. The last value that3263// normalizes to itself is the actual maximum for the current date3264int result = fieldValue;32653266do {3267work.set(field, fieldValue);3268if (work.get(field) != fieldValue) {3269break;3270} else {3271result = fieldValue;3272fieldValue++;3273}3274} while (fieldValue <= endValue);32753276return result;3277}32783279/**3280* Creates and returns a copy of this object.3281*3282* @return a copy of this object.3283*/3284@Override3285public Object clone()3286{3287try {3288Calendar other = (Calendar) super.clone();32893290other.fields = new int[FIELD_COUNT];3291other.isSet = new boolean[FIELD_COUNT];3292other.stamp = new int[FIELD_COUNT];3293for (int i = 0; i < FIELD_COUNT; i++) {3294other.fields[i] = fields[i];3295other.stamp[i] = stamp[i];3296other.isSet[i] = isSet[i];3297}3298other.zone = (TimeZone) zone.clone();3299return other;3300}3301catch (CloneNotSupportedException e) {3302// this shouldn't happen, since we are Cloneable3303throw new InternalError(e);3304}3305}33063307private static final String[] FIELD_NAME = {3308"ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH", "DAY_OF_MONTH",3309"DAY_OF_YEAR", "DAY_OF_WEEK", "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR",3310"HOUR_OF_DAY", "MINUTE", "SECOND", "MILLISECOND", "ZONE_OFFSET",3311"DST_OFFSET"3312};33133314/**3315* Returns the name of the specified calendar field.3316*3317* @param field the calendar field3318* @return the calendar field name3319* @exception IndexOutOfBoundsException if <code>field</code> is negative,3320* equal to or greater then <code>FIELD_COUNT</code>.3321*/3322static String getFieldName(int field) {3323return FIELD_NAME[field];3324}33253326/**3327* Return a string representation of this calendar. This method3328* is intended to be used only for debugging purposes, and the3329* format of the returned string may vary between implementations.3330* The returned string may be empty but may not be <code>null</code>.3331*3332* @return a string representation of this calendar.3333*/3334@Override3335public String toString() {3336// NOTE: BuddhistCalendar.toString() interprets the string3337// produced by this method so that the Gregorian year number3338// is substituted by its B.E. year value. It relies on3339// "...,YEAR=<year>,..." or "...,YEAR=?,...".3340StringBuilder buffer = new StringBuilder(800);3341buffer.append(getClass().getName()).append('[');3342appendValue(buffer, "time", isTimeSet, time);3343buffer.append(",areFieldsSet=").append(areFieldsSet);3344buffer.append(",areAllFieldsSet=").append(areAllFieldsSet);3345buffer.append(",lenient=").append(lenient);3346buffer.append(",zone=").append(zone);3347appendValue(buffer, ",firstDayOfWeek", true, (long) firstDayOfWeek);3348appendValue(buffer, ",minimalDaysInFirstWeek", true, (long) minimalDaysInFirstWeek);3349for (int i = 0; i < FIELD_COUNT; ++i) {3350buffer.append(',');3351appendValue(buffer, FIELD_NAME[i], isSet(i), (long) fields[i]);3352}3353buffer.append(']');3354return buffer.toString();3355}33563357// =======================privates===============================33583359private static void appendValue(StringBuilder sb, String item, boolean valid, long value) {3360sb.append(item).append('=');3361if (valid) {3362sb.append(value);3363} else {3364sb.append('?');3365}3366}33673368/**3369* Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent.3370* They are used to figure out the week count for a specific date for3371* a given locale. These must be set when a Calendar is constructed.3372* @param desiredLocale the given locale.3373*/3374private void setWeekCountData(Locale desiredLocale)3375{3376/* try to get the Locale data from the cache */3377int[] data = cachedLocaleData.get(desiredLocale);3378if (data == null) { /* cache miss */3379data = new int[2];3380data[0] = CalendarDataUtility.retrieveFirstDayOfWeek(desiredLocale);3381data[1] = CalendarDataUtility.retrieveMinimalDaysInFirstWeek(desiredLocale);3382cachedLocaleData.putIfAbsent(desiredLocale, data);3383}3384firstDayOfWeek = data[0];3385minimalDaysInFirstWeek = data[1];3386}33873388/**3389* Recomputes the time and updates the status fields isTimeSet3390* and areFieldsSet. Callers should check isTimeSet and only3391* call this method if isTimeSet is false.3392*/3393private void updateTime() {3394computeTime();3395// The areFieldsSet and areAllFieldsSet values are no longer3396// controlled here (as of 1.5).3397isTimeSet = true;3398}33993400private int compareTo(long t) {3401long thisTime = getMillisOf(this);3402return (thisTime > t) ? 1 : (thisTime == t) ? 0 : -1;3403}34043405private static long getMillisOf(Calendar calendar) {3406if (calendar.isTimeSet) {3407return calendar.time;3408}3409Calendar cal = (Calendar) calendar.clone();3410cal.setLenient(true);3411return cal.getTimeInMillis();3412}34133414/**3415* Adjusts the stamp[] values before nextStamp overflow. nextStamp3416* is set to the next stamp value upon the return.3417*/3418private void adjustStamp() {3419int max = MINIMUM_USER_STAMP;3420int newStamp = MINIMUM_USER_STAMP;34213422for (;;) {3423int min = Integer.MAX_VALUE;3424for (int i = 0; i < stamp.length; i++) {3425int v = stamp[i];3426if (v >= newStamp && min > v) {3427min = v;3428}3429if (max < v) {3430max = v;3431}3432}3433if (max != min && min == Integer.MAX_VALUE) {3434break;3435}3436for (int i = 0; i < stamp.length; i++) {3437if (stamp[i] == min) {3438stamp[i] = newStamp;3439}3440}3441newStamp++;3442if (min == max) {3443break;3444}3445}3446nextStamp = newStamp;3447}34483449/**3450* Sets the WEEK_OF_MONTH and WEEK_OF_YEAR fields to new values with the3451* new parameter value if they have been calculated internally.3452*/3453private void invalidateWeekFields()3454{3455if (stamp[WEEK_OF_MONTH] != COMPUTED &&3456stamp[WEEK_OF_YEAR] != COMPUTED) {3457return;3458}34593460// We have to check the new values of these fields after changing3461// firstDayOfWeek and/or minimalDaysInFirstWeek. If the field values3462// have been changed, then set the new values. (4822110)3463Calendar cal = (Calendar) clone();3464cal.setLenient(true);3465cal.clear(WEEK_OF_MONTH);3466cal.clear(WEEK_OF_YEAR);34673468if (stamp[WEEK_OF_MONTH] == COMPUTED) {3469int weekOfMonth = cal.get(WEEK_OF_MONTH);3470if (fields[WEEK_OF_MONTH] != weekOfMonth) {3471fields[WEEK_OF_MONTH] = weekOfMonth;3472}3473}34743475if (stamp[WEEK_OF_YEAR] == COMPUTED) {3476int weekOfYear = cal.get(WEEK_OF_YEAR);3477if (fields[WEEK_OF_YEAR] != weekOfYear) {3478fields[WEEK_OF_YEAR] = weekOfYear;3479}3480}3481}34823483/**3484* Save the state of this object to a stream (i.e., serialize it).3485*3486* Ideally, <code>Calendar</code> would only write out its state data and3487* the current time, and not write any field data out, such as3488* <code>fields[]</code>, <code>isTimeSet</code>, <code>areFieldsSet</code>,3489* and <code>isSet[]</code>. <code>nextStamp</code> also should not be part3490* of the persistent state. Unfortunately, this didn't happen before JDK 1.13491* shipped. To be compatible with JDK 1.1, we will always have to write out3492* the field values and state flags. However, <code>nextStamp</code> can be3493* removed from the serialization stream; this will probably happen in the3494* near future.3495*/3496private synchronized void writeObject(ObjectOutputStream stream)3497throws IOException3498{3499// Try to compute the time correctly, for the future (stream3500// version 2) in which we don't write out fields[] or isSet[].3501if (!isTimeSet) {3502try {3503updateTime();3504}3505catch (IllegalArgumentException e) {}3506}35073508// If this Calendar has a ZoneInfo, save it and set a3509// SimpleTimeZone equivalent (as a single DST schedule) for3510// backward compatibility.3511TimeZone savedZone = null;3512if (zone instanceof ZoneInfo) {3513SimpleTimeZone stz = ((ZoneInfo)zone).getLastRuleInstance();3514if (stz == null) {3515stz = new SimpleTimeZone(zone.getRawOffset(), zone.getID());3516}3517savedZone = zone;3518zone = stz;3519}35203521// Write out the 1.1 FCS object.3522stream.defaultWriteObject();35233524// Write out the ZoneInfo object3525// 4802409: we write out even if it is null, a temporary workaround3526// the real fix for bug 4844924 in corba-iiop3527stream.writeObject(savedZone);3528if (savedZone != null) {3529zone = savedZone;3530}3531}35323533private static class CalendarAccessControlContext {3534private static final AccessControlContext INSTANCE;3535static {3536RuntimePermission perm = new RuntimePermission("accessClassInPackage.sun.util.calendar");3537PermissionCollection perms = perm.newPermissionCollection();3538perms.add(perm);3539INSTANCE = new AccessControlContext(new ProtectionDomain[] {3540new ProtectionDomain(null, perms)3541});3542}3543private CalendarAccessControlContext() {3544}3545}35463547/**3548* Reconstitutes this object from a stream (i.e., deserialize it).3549*/3550private void readObject(ObjectInputStream stream)3551throws IOException, ClassNotFoundException3552{3553final ObjectInputStream input = stream;3554input.defaultReadObject();35553556stamp = new int[FIELD_COUNT];35573558// Starting with version 2 (not implemented yet), we expect that3559// fields[], isSet[], isTimeSet, and areFieldsSet may not be3560// streamed out anymore. We expect 'time' to be correct.3561if (serialVersionOnStream >= 2)3562{3563isTimeSet = true;3564if (fields == null) {3565fields = new int[FIELD_COUNT];3566}3567if (isSet == null) {3568isSet = new boolean[FIELD_COUNT];3569}3570}3571else if (serialVersionOnStream >= 0)3572{3573for (int i=0; i<FIELD_COUNT; ++i) {3574stamp[i] = isSet[i] ? COMPUTED : UNSET;3575}3576}35773578serialVersionOnStream = currentSerialVersion;35793580// If there's a ZoneInfo object, use it for zone.3581ZoneInfo zi = null;3582try {3583zi = AccessController.doPrivileged(3584new PrivilegedExceptionAction<ZoneInfo>() {3585@Override3586public ZoneInfo run() throws Exception {3587return (ZoneInfo) input.readObject();3588}3589},3590CalendarAccessControlContext.INSTANCE);3591} catch (PrivilegedActionException pae) {3592Exception e = pae.getException();3593if (!(e instanceof OptionalDataException)) {3594if (e instanceof RuntimeException) {3595throw (RuntimeException) e;3596} else if (e instanceof IOException) {3597throw (IOException) e;3598} else if (e instanceof ClassNotFoundException) {3599throw (ClassNotFoundException) e;3600}3601throw new RuntimeException(e);3602}3603}3604if (zi != null) {3605zone = zi;3606}36073608// If the deserialized object has a SimpleTimeZone, try to3609// replace it with a ZoneInfo equivalent (as of 1.4) in order3610// to be compatible with the SimpleTimeZone-based3611// implementation as much as possible.3612if (zone instanceof SimpleTimeZone) {3613String id = zone.getID();3614TimeZone tz = TimeZone.getTimeZone(id);3615if (tz != null && tz.hasSameRules(zone) && tz.getID().equals(id)) {3616zone = tz;3617}3618}3619}36203621/**3622* Converts this object to an {@link Instant}.3623* <p>3624* The conversion creates an {@code Instant} that represents the3625* same point on the time-line as this {@code Calendar}.3626*3627* @return the instant representing the same point on the time-line3628* @since 1.83629*/3630public final Instant toInstant() {3631return Instant.ofEpochMilli(getTimeInMillis());3632}3633}363436353636