2 * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
27 * (C) Copyright Taligent, Inc. 1996-1998 - All Rights Reserved
28 * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
30 * The original version of this source code and documentation is copyrighted
31 * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
32 * materials are provided under terms of a License Agreement between Taligent
33 * and Sun. This technology is protected by multiple US and International
34 * patents. This notice and attribution to Taligent may not be removed.
35 * Taligent is a registered trademark of Taligent, Inc.
41 import java.io.IOException;
42 import java.io.ObjectInputStream;
43 import java.io.ObjectOutputStream;
44 import java.io.OptionalDataException;
45 import java.io.Serializable;
46 import java.security.AccessController;
47 import java.security.PrivilegedActionException;
48 import java.security.PrivilegedExceptionAction;
49 import java.text.DateFormat;
50 import java.text.DateFormatSymbols;
51 import java.util.concurrent.ConcurrentHashMap;
52 import java.util.concurrent.ConcurrentMap;
55 * The <code>Calendar</code> class is an abstract class that provides methods
56 * for converting between a specific instant in time and a set of {@link
57 * #fields calendar fields} such as <code>YEAR</code>, <code>MONTH</code>,
58 * <code>DAY_OF_MONTH</code>, <code>HOUR</code>, and so on, and for
59 * manipulating the calendar fields, such as getting the date of the next
60 * week. An instant in time can be represented by a millisecond value that is
61 * an offset from the <a name="Epoch"><em>Epoch</em></a>, January 1, 1970
62 * 00:00:00.000 GMT (Gregorian).
64 * <p>The class also provides additional fields and methods for
65 * implementing a concrete calendar system outside the package. Those
66 * fields and methods are defined as <code>protected</code>.
69 * Like other locale-sensitive classes, <code>Calendar</code> provides a
70 * class method, <code>getInstance</code>, for getting a generally useful
71 * object of this type. <code>Calendar</code>'s <code>getInstance</code> method
72 * returns a <code>Calendar</code> object whose
73 * calendar fields have been initialized with the current date and time:
76 * Calendar rightNow = Calendar.getInstance();
80 * <p>A <code>Calendar</code> object can produce all the calendar field values
81 * needed to implement the date-time formatting for a particular language and
82 * calendar style (for example, Japanese-Gregorian, Japanese-Traditional).
83 * <code>Calendar</code> defines the range of values returned by
84 * certain calendar fields, as well as their meaning. For example,
85 * the first month of the calendar system has value <code>MONTH ==
86 * JANUARY</code> for all calendars. Other values are defined by the
87 * concrete subclass, such as <code>ERA</code>. See individual field
88 * documentation and subclass documentation for details.
90 * <h4>Getting and Setting Calendar Field Values</h4>
92 * <p>The calendar field values can be set by calling the <code>set</code>
93 * methods. Any field values set in a <code>Calendar</code> will not be
94 * interpreted until it needs to calculate its time value (milliseconds from
95 * the Epoch) or values of the calendar fields. Calling the
96 * <code>get</code>, <code>getTimeInMillis</code>, <code>getTime</code>,
97 * <code>add</code> and <code>roll</code> involves such calculation.
101 * <p><code>Calendar</code> has two modes for interpreting the calendar
102 * fields, <em>lenient</em> and <em>non-lenient</em>. When a
103 * <code>Calendar</code> is in lenient mode, it accepts a wider range of
104 * calendar field values than it produces. When a <code>Calendar</code>
105 * recomputes calendar field values for return by <code>get()</code>, all of
106 * the calendar fields are normalized. For example, a lenient
107 * <code>GregorianCalendar</code> interprets <code>MONTH == JANUARY</code>,
108 * <code>DAY_OF_MONTH == 32</code> as February 1.
110 * <p>When a <code>Calendar</code> is in non-lenient mode, it throws an
111 * exception if there is any inconsistency in its calendar fields. For
112 * example, a <code>GregorianCalendar</code> always produces
113 * <code>DAY_OF_MONTH</code> values between 1 and the length of the month. A
114 * non-lenient <code>GregorianCalendar</code> throws an exception upon
115 * calculating its time or calendar field values if any out-of-range field
116 * value has been set.
118 * <h4><a name="first_week">First Week</a></h4>
120 * <code>Calendar</code> defines a locale-specific seven day week using two
121 * parameters: the first day of the week and the minimal days in first week
122 * (from 1 to 7). These numbers are taken from the locale resource data when a
123 * <code>Calendar</code> is constructed. They may also be specified explicitly
124 * through the methods for setting their values.
126 * <p>When setting or getting the <code>WEEK_OF_MONTH</code> or
127 * <code>WEEK_OF_YEAR</code> fields, <code>Calendar</code> must determine the
128 * first week of the month or year as a reference point. The first week of a
129 * month or year is defined as the earliest seven day period beginning on
130 * <code>getFirstDayOfWeek()</code> and containing at least
131 * <code>getMinimalDaysInFirstWeek()</code> days of that month or year. Weeks
132 * numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow
133 * it. Note that the normalized numbering returned by <code>get()</code> may be
134 * different. For example, a specific <code>Calendar</code> subclass may
135 * designate the week before week 1 of a year as week <code><i>n</i></code> of
138 * <h4>Calendar Fields Resolution</h4>
140 * When computing a date and time from the calendar fields, there
141 * may be insufficient information for the computation (such as only
142 * year and month with no day of month), or there may be inconsistent
143 * information (such as Tuesday, July 15, 1996 (Gregorian) -- July 15,
144 * 1996 is actually a Monday). <code>Calendar</code> will resolve
145 * calendar field values to determine the date and time in the
148 * <p>If there is any conflict in calendar field values,
149 * <code>Calendar</code> gives priorities to calendar fields that have been set
150 * more recently. The following are the default combinations of the
151 * calendar fields. The most recent combination, as determined by the
152 * most recently set single field, will be used.
154 * <p><a name="date_resolution">For the date fields</a>:
157 * YEAR + MONTH + DAY_OF_MONTH
158 * YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
159 * YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
161 * YEAR + DAY_OF_WEEK + WEEK_OF_YEAR
162 * </pre></blockquote>
164 * <a name="time_resolution">For the time of day fields</a>:
169 * </pre></blockquote>
171 * <p>If there are any calendar fields whose values haven't been set in the selected
172 * field combination, <code>Calendar</code> uses their default values. The default
173 * value of each field may vary by concrete calendar systems. For example, in
174 * <code>GregorianCalendar</code>, the default of a field is the same as that
175 * of the start of the Epoch: i.e., <code>YEAR = 1970</code>, <code>MONTH =
176 * JANUARY</code>, <code>DAY_OF_MONTH = 1</code>, etc.
179 * <strong>Note:</strong> There are certain possible ambiguities in
180 * interpretation of certain singular times, which are resolved in the
183 * <li> 23:59 is the last minute of the day and 00:00 is the first
184 * minute of the next day. Thus, 23:59 on Dec 31, 1999 < 00:00 on
185 * Jan 1, 2000 < 00:01 on Jan 1, 2000.
187 * <li> Although historically not precise, midnight also belongs to "am",
188 * and noon belongs to "pm", so on the same day,
189 * 12:00 am (midnight) < 12:01 am, and 12:00 pm (noon) < 12:01 pm
193 * The date or time format strings are not part of the definition of a
194 * calendar, as those must be modifiable or overridable by the user at
195 * runtime. Use {@link DateFormat}
198 * <h4>Field Manipulation</h4>
200 * The calendar fields can be changed using three methods:
201 * <code>set()</code>, <code>add()</code>, and <code>roll()</code>.</p>
203 * <p><strong><code>set(f, value)</code></strong> changes calendar field
204 * <code>f</code> to <code>value</code>. In addition, it sets an
205 * internal member variable to indicate that calendar field <code>f</code> has
206 * been changed. Although calendar field <code>f</code> is changed immediately,
207 * the calendar's time value in milliseconds is not recomputed until the next call to
208 * <code>get()</code>, <code>getTime()</code>, <code>getTimeInMillis()</code>,
209 * <code>add()</code>, or <code>roll()</code> is made. Thus, multiple calls to
210 * <code>set()</code> do not trigger multiple, unnecessary
211 * computations. As a result of changing a calendar field using
212 * <code>set()</code>, other calendar fields may also change, depending on the
213 * calendar field, the calendar field value, and the calendar system. In addition,
214 * <code>get(f)</code> will not necessarily return <code>value</code> set by
215 * the call to the <code>set</code> method
216 * after the calendar fields have been recomputed. The specifics are determined by
217 * the concrete calendar class.</p>
219 * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
220 * originally set to August 31, 1999. Calling <code>set(Calendar.MONTH,
221 * Calendar.SEPTEMBER)</code> sets the date to September 31,
222 * 1999. This is a temporary internal representation that resolves to
223 * October 1, 1999 if <code>getTime()</code>is then called. However, a
224 * call to <code>set(Calendar.DAY_OF_MONTH, 30)</code> before the call to
225 * <code>getTime()</code> sets the date to September 30, 1999, since
226 * no recomputation occurs after <code>set()</code> itself.</p>
228 * <p><strong><code>add(f, delta)</code></strong> adds <code>delta</code>
229 * to field <code>f</code>. This is equivalent to calling <code>set(f,
230 * get(f) + delta)</code> with two adjustments:</p>
233 * <p><strong>Add rule 1</strong>. The value of field <code>f</code>
234 * after the call minus the value of field <code>f</code> before the
235 * call is <code>delta</code>, modulo any overflow that has occurred in
236 * field <code>f</code>. Overflow occurs when a field value exceeds its
237 * range and, as a result, the next larger field is incremented or
238 * decremented and the field value is adjusted back into its range.</p>
240 * <p><strong>Add rule 2</strong>. If a smaller field is expected to be
241 * invariant, but it is impossible for it to be equal to its
242 * prior value because of changes in its minimum or maximum after field
243 * <code>f</code> is changed or other constraints, such as time zone
244 * offset changes, then its value is adjusted to be as close
245 * as possible to its expected value. A smaller field represents a
246 * smaller unit of time. <code>HOUR</code> is a smaller field than
247 * <code>DAY_OF_MONTH</code>. No adjustment is made to smaller fields
248 * that are not expected to be invariant. The calendar system
249 * determines what fields are expected to be invariant.</p>
252 * <p>In addition, unlike <code>set()</code>, <code>add()</code> forces
253 * an immediate recomputation of the calendar's milliseconds and all
256 * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
257 * originally set to August 31, 1999. Calling <code>add(Calendar.MONTH,
258 * 13)</code> sets the calendar to September 30, 2000. <strong>Add rule
259 * 1</strong> sets the <code>MONTH</code> field to September, since
260 * adding 13 months to August gives September of the next year. Since
261 * <code>DAY_OF_MONTH</code> cannot be 31 in September in a
262 * <code>GregorianCalendar</code>, <strong>add rule 2</strong> sets the
263 * <code>DAY_OF_MONTH</code> to 30, the closest possible value. Although
264 * it is a smaller field, <code>DAY_OF_WEEK</code> is not adjusted by
265 * rule 2, since it is expected to change when the month changes in a
266 * <code>GregorianCalendar</code>.</p>
268 * <p><strong><code>roll(f, delta)</code></strong> adds
269 * <code>delta</code> to field <code>f</code> without changing larger
270 * fields. This is equivalent to calling <code>add(f, delta)</code> with
271 * the following adjustment:</p>
274 * <p><strong>Roll rule</strong>. Larger fields are unchanged after the
275 * call. A larger field represents a larger unit of
276 * time. <code>DAY_OF_MONTH</code> is a larger field than
277 * <code>HOUR</code>.</p>
280 * <p><em>Example</em>: See {@link java.util.GregorianCalendar#roll(int, int)}.
282 * <p><strong>Usage model</strong>. To motivate the behavior of
283 * <code>add()</code> and <code>roll()</code>, consider a user interface
284 * component with increment and decrement buttons for the month, day, and
285 * year, and an underlying <code>GregorianCalendar</code>. If the
286 * interface reads January 31, 1999 and the user presses the month
287 * increment button, what should it read? If the underlying
288 * implementation uses <code>set()</code>, it might read March 3, 1999. A
289 * better result would be February 28, 1999. Furthermore, if the user
290 * presses the month increment button again, it should read March 31,
291 * 1999, not March 28, 1999. By saving the original date and using either
292 * <code>add()</code> or <code>roll()</code>, depending on whether larger
293 * fields should be affected, the user interface can behave as most users
294 * will intuitively expect.</p>
296 * @see java.lang.System#currentTimeMillis()
298 * @see GregorianCalendar
300 * @see java.text.DateFormat
301 * @author Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu
304 public abstract class Calendar implements Serializable, Cloneable, Comparable<Calendar> {
306 // Data flow in Calendar
307 // ---------------------
309 // The current time is represented in two ways by Calendar: as UTC
310 // milliseconds from the epoch (1 January 1970 0:00 UTC), and as local
311 // fields such as MONTH, HOUR, AM_PM, etc. It is possible to compute the
312 // millis from the fields, and vice versa. The data needed to do this
313 // conversion is encapsulated by a TimeZone object owned by the Calendar.
314 // The data provided by the TimeZone object may also be overridden if the
315 // user sets the ZONE_OFFSET and/or DST_OFFSET fields directly. The class
316 // keeps track of what information was most recently set by the caller, and
317 // uses that to compute any other information as needed.
319 // If the user sets the fields using set(), the data flow is as follows.
320 // This is implemented by the Calendar subclass's computeTime() method.
321 // During this process, certain fields may be ignored. The disambiguation
322 // algorithm for resolving which fields to pay attention to is described
323 // in the class documentation.
325 // local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
327 // | Using Calendar-specific algorithm
329 // local standard millis
331 // | Using TimeZone or user-set ZONE_OFFSET / DST_OFFSET
333 // UTC millis (in time data member)
335 // If the user sets the UTC millis using setTime() or setTimeInMillis(),
336 // the data flow is as follows. This is implemented by the Calendar
337 // subclass's computeFields() method.
339 // UTC millis (in time data member)
341 // | Using TimeZone getOffset()
343 // local standard millis
345 // | Using Calendar-specific algorithm
347 // local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
349 // In general, a round trip from fields, through local and UTC millis, and
350 // back out to fields is made when necessary. This is implemented by the
351 // complete() method. Resolving a partial set of fields into a UTC millis
352 // value allows all remaining fields to be generated from that value. If
353 // the Calendar is lenient, the fields are also renormalized to standard
354 // ranges when they are regenerated.
357 * Field number for <code>get</code> and <code>set</code> indicating the
358 * era, e.g., AD or BC in the Julian calendar. This is a calendar-specific
359 * value; see subclass documentation.
361 * @see GregorianCalendar#AD
362 * @see GregorianCalendar#BC
364 public final static int ERA = 0;
367 * Field number for <code>get</code> and <code>set</code> indicating the
368 * year. This is a calendar-specific value; see subclass documentation.
370 public final static int YEAR = 1;
373 * Field number for <code>get</code> and <code>set</code> indicating the
374 * month. This is a calendar-specific value. The first month of
375 * the year in the Gregorian and Julian calendars is
376 * <code>JANUARY</code> which is 0; the last depends on the number
377 * of months in a year.
393 public final static int MONTH = 2;
396 * Field number for <code>get</code> and <code>set</code> indicating the
397 * week number within the current year. The first week of the year, as
398 * defined by <code>getFirstDayOfWeek()</code> and
399 * <code>getMinimalDaysInFirstWeek()</code>, has value 1. Subclasses define
400 * the value of <code>WEEK_OF_YEAR</code> for days before the first week of
403 * @see #getFirstDayOfWeek
404 * @see #getMinimalDaysInFirstWeek
406 public final static int WEEK_OF_YEAR = 3;
409 * Field number for <code>get</code> and <code>set</code> indicating the
410 * week number within the current month. The first week of the month, as
411 * defined by <code>getFirstDayOfWeek()</code> and
412 * <code>getMinimalDaysInFirstWeek()</code>, has value 1. Subclasses define
413 * the value of <code>WEEK_OF_MONTH</code> for days before the first week of
416 * @see #getFirstDayOfWeek
417 * @see #getMinimalDaysInFirstWeek
419 public final static int WEEK_OF_MONTH = 4;
422 * Field number for <code>get</code> and <code>set</code> indicating the
423 * day of the month. This is a synonym for <code>DAY_OF_MONTH</code>.
424 * The first day of the month has value 1.
428 public final static int DATE = 5;
431 * Field number for <code>get</code> and <code>set</code> indicating the
432 * day of the month. This is a synonym for <code>DATE</code>.
433 * The first day of the month has value 1.
437 public final static int DAY_OF_MONTH = 5;
440 * Field number for <code>get</code> and <code>set</code> indicating the day
441 * number within the current year. The first day of the year has value 1.
443 public final static int DAY_OF_YEAR = 6;
446 * Field number for <code>get</code> and <code>set</code> indicating the day
447 * of the week. This field takes values <code>SUNDAY</code>,
448 * <code>MONDAY</code>, <code>TUESDAY</code>, <code>WEDNESDAY</code>,
449 * <code>THURSDAY</code>, <code>FRIDAY</code>, and <code>SATURDAY</code>.
459 public final static int DAY_OF_WEEK = 7;
462 * Field number for <code>get</code> and <code>set</code> indicating the
463 * ordinal number of the day of the week within the current month. Together
464 * with the <code>DAY_OF_WEEK</code> field, this uniquely specifies a day
465 * within a month. Unlike <code>WEEK_OF_MONTH</code> and
466 * <code>WEEK_OF_YEAR</code>, this field's value does <em>not</em> depend on
467 * <code>getFirstDayOfWeek()</code> or
468 * <code>getMinimalDaysInFirstWeek()</code>. <code>DAY_OF_MONTH 1</code>
469 * through <code>7</code> always correspond to <code>DAY_OF_WEEK_IN_MONTH
470 * 1</code>; <code>8</code> through <code>14</code> correspond to
471 * <code>DAY_OF_WEEK_IN_MONTH 2</code>, and so on.
472 * <code>DAY_OF_WEEK_IN_MONTH 0</code> indicates the week before
473 * <code>DAY_OF_WEEK_IN_MONTH 1</code>. Negative values count back from the
474 * end of the month, so the last Sunday of a month is specified as
475 * <code>DAY_OF_WEEK = SUNDAY, DAY_OF_WEEK_IN_MONTH = -1</code>. Because
476 * negative values count backward they will usually be aligned differently
477 * within the month than positive values. For example, if a month has 31
478 * days, <code>DAY_OF_WEEK_IN_MONTH -1</code> will overlap
479 * <code>DAY_OF_WEEK_IN_MONTH 5</code> and the end of <code>4</code>.
482 * @see #WEEK_OF_MONTH
484 public final static int DAY_OF_WEEK_IN_MONTH = 8;
487 * Field number for <code>get</code> and <code>set</code> indicating
488 * whether the <code>HOUR</code> is before or after noon.
489 * E.g., at 10:04:15.250 PM the <code>AM_PM</code> is <code>PM</code>.
495 public final static int AM_PM = 9;
498 * Field number for <code>get</code> and <code>set</code> indicating the
499 * hour of the morning or afternoon. <code>HOUR</code> is used for the
500 * 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12.
501 * E.g., at 10:04:15.250 PM the <code>HOUR</code> is 10.
506 public final static int HOUR = 10;
509 * Field number for <code>get</code> and <code>set</code> indicating the
510 * hour of the day. <code>HOUR_OF_DAY</code> is used for the 24-hour clock.
511 * E.g., at 10:04:15.250 PM the <code>HOUR_OF_DAY</code> is 22.
515 public final static int HOUR_OF_DAY = 11;
518 * Field number for <code>get</code> and <code>set</code> indicating the
519 * minute within the hour.
520 * E.g., at 10:04:15.250 PM the <code>MINUTE</code> is 4.
522 public final static int MINUTE = 12;
525 * Field number for <code>get</code> and <code>set</code> indicating the
526 * second within the minute.
527 * E.g., at 10:04:15.250 PM the <code>SECOND</code> is 15.
529 public final static int SECOND = 13;
532 * Field number for <code>get</code> and <code>set</code> indicating the
533 * millisecond within the second.
534 * E.g., at 10:04:15.250 PM the <code>MILLISECOND</code> is 250.
536 public final static int MILLISECOND = 14;
539 * Field number for <code>get</code> and <code>set</code>
540 * indicating the raw offset from GMT in milliseconds.
542 * This field reflects the correct GMT offset value of the time
543 * zone of this <code>Calendar</code> if the
544 * <code>TimeZone</code> implementation subclass supports
545 * historical GMT offset changes.
547 public final static int ZONE_OFFSET = 15;
550 * Field number for <code>get</code> and <code>set</code> indicating the
551 * daylight saving offset in milliseconds.
553 * This field reflects the correct daylight saving offset value of
554 * the time zone of this <code>Calendar</code> if the
555 * <code>TimeZone</code> implementation subclass supports
556 * historical Daylight Saving Time schedule changes.
558 public final static int DST_OFFSET = 16;
561 * The number of distinct fields recognized by <code>get</code> and <code>set</code>.
562 * Field numbers range from <code>0..FIELD_COUNT-1</code>.
564 public final static int FIELD_COUNT = 17;
567 * Value of the {@link #DAY_OF_WEEK} field indicating
570 public final static int SUNDAY = 1;
573 * Value of the {@link #DAY_OF_WEEK} field indicating
576 public final static int MONDAY = 2;
579 * Value of the {@link #DAY_OF_WEEK} field indicating
582 public final static int TUESDAY = 3;
585 * Value of the {@link #DAY_OF_WEEK} field indicating
588 public final static int WEDNESDAY = 4;
591 * Value of the {@link #DAY_OF_WEEK} field indicating
594 public final static int THURSDAY = 5;
597 * Value of the {@link #DAY_OF_WEEK} field indicating
600 public final static int FRIDAY = 6;
603 * Value of the {@link #DAY_OF_WEEK} field indicating
606 public final static int SATURDAY = 7;
609 * Value of the {@link #MONTH} field indicating the
610 * first month of the year in the Gregorian and Julian calendars.
612 public final static int JANUARY = 0;
615 * Value of the {@link #MONTH} field indicating the
616 * second month of the year in the Gregorian and Julian calendars.
618 public final static int FEBRUARY = 1;
621 * Value of the {@link #MONTH} field indicating the
622 * third month of the year in the Gregorian and Julian calendars.
624 public final static int MARCH = 2;
627 * Value of the {@link #MONTH} field indicating the
628 * fourth month of the year in the Gregorian and Julian calendars.
630 public final static int APRIL = 3;
633 * Value of the {@link #MONTH} field indicating the
634 * fifth month of the year in the Gregorian and Julian calendars.
636 public final static int MAY = 4;
639 * Value of the {@link #MONTH} field indicating the
640 * sixth month of the year in the Gregorian and Julian calendars.
642 public final static int JUNE = 5;
645 * Value of the {@link #MONTH} field indicating the
646 * seventh month of the year in the Gregorian and Julian calendars.
648 public final static int JULY = 6;
651 * Value of the {@link #MONTH} field indicating the
652 * eighth month of the year in the Gregorian and Julian calendars.
654 public final static int AUGUST = 7;
657 * Value of the {@link #MONTH} field indicating the
658 * ninth month of the year in the Gregorian and Julian calendars.
660 public final static int SEPTEMBER = 8;
663 * Value of the {@link #MONTH} field indicating the
664 * tenth month of the year in the Gregorian and Julian calendars.
666 public final static int OCTOBER = 9;
669 * Value of the {@link #MONTH} field indicating the
670 * eleventh month of the year in the Gregorian and Julian calendars.
672 public final static int NOVEMBER = 10;
675 * Value of the {@link #MONTH} field indicating the
676 * twelfth month of the year in the Gregorian and Julian calendars.
678 public final static int DECEMBER = 11;
681 * Value of the {@link #MONTH} field indicating the
682 * thirteenth month of the year. Although <code>GregorianCalendar</code>
683 * does not use this value, lunar calendars do.
685 public final static int UNDECIMBER = 12;
688 * Value of the {@link #AM_PM} field indicating the
689 * period of the day from midnight to just before noon.
691 public final static int AM = 0;
694 * Value of the {@link #AM_PM} field indicating the
695 * period of the day from noon to just before midnight.
697 public final static int PM = 1;
700 * A style specifier for {@link #getDisplayNames(int, int, Locale)
701 * getDisplayNames} indicating names in all styles, such as
702 * "January" and "Jan".
708 public static final int ALL_STYLES = 0;
711 * A style specifier for {@link #getDisplayName(int, int, Locale)
712 * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
713 * getDisplayNames} indicating a short name, such as "Jan".
718 public static final int SHORT = 1;
721 * A style specifier for {@link #getDisplayName(int, int, Locale)
722 * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
723 * getDisplayNames} indicating a long name, such as "January".
728 public static final int LONG = 2;
731 // Calendar contains two kinds of time representations: current "time" in
732 // milliseconds, and a set of calendar "fields" representing the current time.
733 // The two representations are usually in sync, but can get out of sync
735 // 1. Initially, no fields are set, and the time is invalid.
736 // 2. If the time is set, all fields are computed and in sync.
737 // 3. If a single field is set, the time is invalid.
738 // Recomputation of the time and fields happens when the object needs
739 // to return a result to the user, or use a result for a computation.
742 * The calendar field values for the currently set time for this calendar.
743 * This is an array of <code>FIELD_COUNT</code> integers, with index values
744 * <code>ERA</code> through <code>DST_OFFSET</code>.
747 protected int fields[];
750 * The flags which tell if a specified calendar field for the calendar is set.
751 * A new object has no fields set. After the first call to a method
752 * which generates the fields, they all remain set after that.
753 * This is an array of <code>FIELD_COUNT</code> booleans, with index values
754 * <code>ERA</code> through <code>DST_OFFSET</code>.
757 protected boolean isSet[];
760 * Pseudo-time-stamps which specify when each field was set. There
761 * are two special values, UNSET and COMPUTED. Values from
762 * MINIMUM_USER_SET to Integer.MAX_VALUE are legal user set values.
764 transient private int stamp[];
767 * The currently set time for this calendar, expressed in milliseconds after
768 * January 1, 1970, 0:00:00 GMT.
775 * True if then the value of <code>time</code> is valid.
776 * The time is made invalid by a change to an item of <code>field[]</code>.
780 protected boolean isTimeSet;
783 * True if <code>fields[]</code> are in sync with the currently set time.
784 * If false, then the next attempt to get the value of a field will
785 * force a recomputation of all fields from the current value of
789 protected boolean areFieldsSet;
792 * True if all fields have been set.
795 transient boolean areAllFieldsSet;
798 * <code>True</code> if this calendar allows out-of-range field values during computation
799 * of <code>time</code> from <code>fields[]</code>.
804 private boolean lenient = true;
807 * The <code>TimeZone</code> used by this calendar. <code>Calendar</code>
808 * uses the time zone data to translate between locale and GMT time.
811 private TimeZone zone;
814 * <code>True</code> if zone references to a shared TimeZone object.
816 transient private boolean sharedZone = false;
819 * The first day of the week, with possible values <code>SUNDAY</code>,
820 * <code>MONDAY</code>, etc. This is a locale-dependent value.
823 private int firstDayOfWeek;
826 * The number of days required for the first week in a month or year,
827 * with possible values from 1 to 7. This is a locale-dependent value.
830 private int minimalDaysInFirstWeek;
833 * Cache to hold the firstDayOfWeek and minimalDaysInFirstWeek
836 private static final ConcurrentMap<Locale, int[]> cachedLocaleData
837 = new ConcurrentHashMap<Locale, int[]>(3);
839 // Special values of stamp[]
841 * The corresponding fields[] has no value.
843 private static final int UNSET = 0;
846 * The value of the corresponding fields[] has been calculated internally.
848 private static final int COMPUTED = 1;
851 * The value of the corresponding fields[] has been set externally. Stamp
852 * values which are greater than 1 represents the (pseudo) time when the
853 * corresponding fields[] value was set.
855 private static final int MINIMUM_USER_STAMP = 2;
858 * The mask value that represents all of the fields.
860 static final int ALL_FIELDS = (1 << FIELD_COUNT) - 1;
863 * The next available value for <code>stamp[]</code>, an internal array.
864 * This actually should not be written out to the stream, and will probably
865 * be removed from the stream in the near future. In the meantime,
866 * a value of <code>MINIMUM_USER_STAMP</code> should be used.
869 private int nextStamp = MINIMUM_USER_STAMP;
871 // the internal serial version which says which version was written
872 // - 0 (default) for version up to JDK 1.1.5
873 // - 1 for version from JDK 1.1.6, which writes a correct 'time' value
874 // as well as compatible values for other fields. This is a
875 // transitional format.
876 // - 2 (not implemented yet) a future version, in which fields[],
877 // areFieldsSet, and isTimeSet become transient, and isSet[] is
878 // removed. In JDK 1.1.6 we write a format compatible with version 2.
879 static final int currentSerialVersion = 1;
882 * The version of the serialized data on the stream. Possible values:
884 * <dt><b>0</b> or not present on stream</dt>
886 * JDK 1.1.5 or earlier.
890 * JDK 1.1.6 or later. Writes a correct 'time' value
891 * as well as compatible values for other fields. This is a
892 * transitional format.
895 * When streaming out this class, the most recent format
896 * and the highest allowable <code>serialVersionOnStream</code>
901 private int serialVersionOnStream = currentSerialVersion;
903 // Proclaim serialization compatibility with JDK 1.1
904 static final long serialVersionUID = -1807547505821590642L;
906 // Mask values for calendar fields
907 final static int ERA_MASK = (1 << ERA);
908 final static int YEAR_MASK = (1 << YEAR);
909 final static int MONTH_MASK = (1 << MONTH);
910 final static int WEEK_OF_YEAR_MASK = (1 << WEEK_OF_YEAR);
911 final static int WEEK_OF_MONTH_MASK = (1 << WEEK_OF_MONTH);
912 final static int DAY_OF_MONTH_MASK = (1 << DAY_OF_MONTH);
913 final static int DATE_MASK = DAY_OF_MONTH_MASK;
914 final static int DAY_OF_YEAR_MASK = (1 << DAY_OF_YEAR);
915 final static int DAY_OF_WEEK_MASK = (1 << DAY_OF_WEEK);
916 final static int DAY_OF_WEEK_IN_MONTH_MASK = (1 << DAY_OF_WEEK_IN_MONTH);
917 final static int AM_PM_MASK = (1 << AM_PM);
918 final static int HOUR_MASK = (1 << HOUR);
919 final static int HOUR_OF_DAY_MASK = (1 << HOUR_OF_DAY);
920 final static int MINUTE_MASK = (1 << MINUTE);
921 final static int SECOND_MASK = (1 << SECOND);
922 final static int MILLISECOND_MASK = (1 << MILLISECOND);
923 final static int ZONE_OFFSET_MASK = (1 << ZONE_OFFSET);
924 final static int DST_OFFSET_MASK = (1 << DST_OFFSET);
927 * Constructs a Calendar with the default time zone
929 * @see TimeZone#getDefault
933 this(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
938 * Constructs a calendar with the specified time zone and locale.
940 * @param zone the time zone to use
941 * @param aLocale the locale for the week data
943 protected Calendar(TimeZone zone, Locale aLocale)
945 fields = new int[FIELD_COUNT];
946 isSet = new boolean[FIELD_COUNT];
947 stamp = new int[FIELD_COUNT];
950 setWeekCountData(aLocale);
954 * Gets a calendar using the default time zone and locale. The
955 * <code>Calendar</code> returned is based on the current time
956 * in the default time zone with the default locale.
958 * @return a Calendar.
960 public static Calendar getInstance()
962 Calendar cal = createCalendar(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
963 cal.sharedZone = true;
968 * Gets a calendar using the specified time zone and default locale.
969 * The <code>Calendar</code> returned is based on the current time
970 * in the given time zone with the default locale.
972 * @param zone the time zone to use
973 * @return a Calendar.
975 public static Calendar getInstance(TimeZone zone)
977 return createCalendar(zone, Locale.getDefault(Locale.Category.FORMAT));
981 * Gets a calendar using the default time zone and specified locale.
982 * The <code>Calendar</code> returned is based on the current time
983 * in the default time zone with the given locale.
985 * @param aLocale the locale for the week data
986 * @return a Calendar.
988 public static Calendar getInstance(Locale aLocale)
990 Calendar cal = createCalendar(TimeZone.getDefaultRef(), aLocale);
991 cal.sharedZone = true;
996 * Gets a calendar with the specified time zone and locale.
997 * The <code>Calendar</code> returned is based on the current time
998 * in the given time zone with the given locale.
1000 * @param zone the time zone to use
1001 * @param aLocale the locale for the week data
1002 * @return a Calendar.
1004 public static Calendar getInstance(TimeZone zone,
1007 return createCalendar(zone, aLocale);
1010 private static Calendar createCalendar(TimeZone zone,
1013 Calendar cal = null;
1015 String caltype = aLocale.getUnicodeLocaleType("ca");
1016 if (caltype == null) {
1017 // Calendar type is not specified.
1018 // If the specified locale is a Thai locale,
1019 // returns a BuddhistCalendar instance.
1020 if ("th".equals(aLocale.getLanguage())
1021 && ("TH".equals(aLocale.getCountry()))) {
1022 // cal = new BuddhistCalendar(zone, aLocale);
1024 // cal = new GregorianCalendar(zone, aLocale);
1026 } else if (caltype.equals("japanese")) {
1027 // cal = new JapaneseImperialCalendar(zone, aLocale);
1028 } else if (caltype.equals("buddhist")) {
1029 // cal = new BuddhistCalendar(zone, aLocale);
1031 // Unsupported calendar type.
1032 // Use Gregorian calendar as a fallback.
1033 // cal = new GregorianCalendar(zone, aLocale);
1040 * Returns an array of all locales for which the <code>getInstance</code>
1041 * methods of this class can return localized instances.
1042 * The array returned must contain at least a <code>Locale</code>
1043 * instance equal to {@link java.util.Locale#US Locale.US}.
1045 * @return An array of locales for which localized
1046 * <code>Calendar</code> instances are available.
1048 public static synchronized Locale[] getAvailableLocales()
1050 return DateFormat.getAvailableLocales();
1054 * Converts the current calendar field values in {@link #fields fields[]}
1055 * to the millisecond time value
1059 * @see #computeFields()
1061 protected abstract void computeTime();
1064 * Converts the current millisecond time value {@link #time}
1065 * to calendar field values in {@link #fields fields[]}.
1066 * This allows you to sync up the calendar field values with
1067 * a new time that is set for the calendar. The time is <em>not</em>
1068 * recomputed first; to recompute the time, then the fields, call the
1069 * {@link #complete()} method.
1071 * @see #computeTime()
1073 protected abstract void computeFields();
1076 * Returns a <code>Date</code> object representing this
1077 * <code>Calendar</code>'s time value (millisecond offset from the <a
1078 * href="#Epoch">Epoch</a>").
1080 * @return a <code>Date</code> representing the time value.
1081 * @see #setTime(Date)
1082 * @see #getTimeInMillis()
1084 public final Date getTime() {
1085 return new Date(getTimeInMillis());
1089 * Sets this Calendar's time with the given <code>Date</code>.
1091 * Note: Calling <code>setTime()</code> with
1092 * <code>Date(Long.MAX_VALUE)</code> or <code>Date(Long.MIN_VALUE)</code>
1093 * may yield incorrect field values from <code>get()</code>.
1095 * @param date the given Date.
1097 * @see #setTimeInMillis(long)
1099 public final void setTime(Date date) {
1100 setTimeInMillis(date.getTime());
1104 * Returns this Calendar's time value in milliseconds.
1106 * @return the current time as UTC milliseconds from the epoch.
1108 * @see #setTimeInMillis(long)
1110 public long getTimeInMillis() {
1118 * Sets this Calendar's current time from the given long value.
1120 * @param millis the new time in UTC milliseconds from the epoch.
1121 * @see #setTime(Date)
1122 * @see #getTimeInMillis()
1124 public void setTimeInMillis(long millis) {
1125 // If we don't need to recalculate the calendar field values,
1127 // if (time == millis && isTimeSet && areFieldsSet && areAllFieldsSet
1128 // && (zone instanceof ZoneInfo) && !((ZoneInfo)zone).isDirty()) {
1133 areFieldsSet = false;
1135 areAllFieldsSet = areFieldsSet = true;
1139 * Returns the value of the given calendar field. In lenient mode,
1140 * all calendar fields are normalized. In non-lenient mode, all
1141 * calendar fields are validated and this method throws an
1142 * exception if any calendar fields have out-of-range values. The
1143 * normalization and validation are handled by the
1144 * {@link #complete()} method, which process is calendar
1147 * @param field the given calendar field.
1148 * @return the value for the given calendar field.
1149 * @throws ArrayIndexOutOfBoundsException if the specified field is out of range
1150 * (<code>field < 0 || field >= FIELD_COUNT</code>).
1151 * @see #set(int,int)
1154 public int get(int field)
1157 return internalGet(field);
1161 * Returns the value of the given calendar field. This method does
1162 * not involve normalization or validation of the field value.
1164 * @param field the given calendar field.
1165 * @return the value for the given calendar field.
1168 protected final int internalGet(int field)
1170 return fields[field];
1174 * Sets the value of the given calendar field. This method does
1175 * not affect any setting state of the field in this
1176 * <code>Calendar</code> instance.
1178 * @throws IndexOutOfBoundsException if the specified field is out of range
1179 * (<code>field < 0 || field >= FIELD_COUNT</code>).
1180 * @see #areFieldsSet
1182 * @see #areAllFieldsSet
1183 * @see #set(int,int)
1185 final void internalSet(int field, int value)
1187 fields[field] = value;
1191 * Sets the given calendar field to the given value. The value is not
1192 * interpreted by this method regardless of the leniency mode.
1194 * @param field the given calendar field.
1195 * @param value the value to be set for the given calendar field.
1196 * @throws ArrayIndexOutOfBoundsException if the specified field is out of range
1197 * (<code>field < 0 || field >= FIELD_COUNT</code>).
1198 * in non-lenient mode.
1199 * @see #set(int,int,int)
1200 * @see #set(int,int,int,int,int)
1201 * @see #set(int,int,int,int,int,int)
1204 public void set(int field, int value)
1206 // If the fields are partially normalized, calculate all the
1207 // fields before changing any fields.
1208 if (areFieldsSet && !areAllFieldsSet) {
1211 internalSet(field, value);
1213 areFieldsSet = false;
1214 isSet[field] = true;
1215 stamp[field] = nextStamp++;
1216 if (nextStamp == Integer.MAX_VALUE) {
1222 * Sets the values for the calendar fields <code>YEAR</code>,
1223 * <code>MONTH</code>, and <code>DAY_OF_MONTH</code>.
1224 * Previous values of other calendar fields are retained. If this is not desired,
1225 * call {@link #clear()} first.
1227 * @param year the value used to set the <code>YEAR</code> calendar field.
1228 * @param month the value used to set the <code>MONTH</code> calendar field.
1229 * Month value is 0-based. e.g., 0 for January.
1230 * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
1231 * @see #set(int,int)
1232 * @see #set(int,int,int,int,int)
1233 * @see #set(int,int,int,int,int,int)
1235 public final void set(int year, int month, int date)
1243 * Sets the values for the calendar fields <code>YEAR</code>,
1244 * <code>MONTH</code>, <code>DAY_OF_MONTH</code>,
1245 * <code>HOUR_OF_DAY</code>, and <code>MINUTE</code>.
1246 * Previous values of other fields are retained. If this is not desired,
1247 * call {@link #clear()} first.
1249 * @param year the value used to set the <code>YEAR</code> calendar field.
1250 * @param month the value used to set the <code>MONTH</code> calendar field.
1251 * Month value is 0-based. e.g., 0 for January.
1252 * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
1253 * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field.
1254 * @param minute the value used to set the <code>MINUTE</code> calendar field.
1255 * @see #set(int,int)
1256 * @see #set(int,int,int)
1257 * @see #set(int,int,int,int,int,int)
1259 public final void set(int year, int month, int date, int hourOfDay, int minute)
1264 set(HOUR_OF_DAY, hourOfDay);
1265 set(MINUTE, minute);
1269 * Sets the values for the fields <code>YEAR</code>, <code>MONTH</code>,
1270 * <code>DAY_OF_MONTH</code>, <code>HOUR</code>, <code>MINUTE</code>, and
1271 * <code>SECOND</code>.
1272 * Previous values of other fields are retained. If this is not desired,
1273 * call {@link #clear()} first.
1275 * @param year the value used to set the <code>YEAR</code> calendar field.
1276 * @param month the value used to set the <code>MONTH</code> calendar field.
1277 * Month value is 0-based. e.g., 0 for January.
1278 * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
1279 * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field.
1280 * @param minute the value used to set the <code>MINUTE</code> calendar field.
1281 * @param second the value used to set the <code>SECOND</code> calendar field.
1282 * @see #set(int,int)
1283 * @see #set(int,int,int)
1284 * @see #set(int,int,int,int,int)
1286 public final void set(int year, int month, int date, int hourOfDay, int minute,
1292 set(HOUR_OF_DAY, hourOfDay);
1293 set(MINUTE, minute);
1294 set(SECOND, second);
1298 * Sets all the calendar field values and the time value
1299 * (millisecond offset from the <a href="#Epoch">Epoch</a>) of
1300 * this <code>Calendar</code> undefined. This means that {@link
1301 * #isSet(int) isSet()} will return <code>false</code> for all the
1302 * calendar fields, and the date and time calculations will treat
1303 * the fields as if they had never been set. A
1304 * <code>Calendar</code> implementation class may use its specific
1305 * default field values for date/time calculations. For example,
1306 * <code>GregorianCalendar</code> uses 1970 if the
1307 * <code>YEAR</code> field value is undefined.
1311 public final void clear()
1313 for (int i = 0; i < fields.length; ) {
1314 stamp[i] = fields[i] = 0; // UNSET == 0
1317 areAllFieldsSet = areFieldsSet = false;
1322 * Sets the given calendar field value and the time value
1323 * (millisecond offset from the <a href="#Epoch">Epoch</a>) of
1324 * this <code>Calendar</code> undefined. This means that {@link
1325 * #isSet(int) isSet(field)} will return <code>false</code>, and
1326 * the date and time calculations will treat the field as if it
1327 * had never been set. A <code>Calendar</code> implementation
1328 * class may use the field's specific default value for date and
1329 * time calculations.
1331 * <p>The {@link #HOUR_OF_DAY}, {@link #HOUR} and {@link #AM_PM}
1332 * fields are handled independently and the <a
1333 * href="#time_resolution">the resolution rule for the time of
1334 * day</a> is applied. Clearing one of the fields doesn't reset
1335 * the hour of day value of this <code>Calendar</code>. Use {@link
1336 * #set(int,int) set(Calendar.HOUR_OF_DAY, 0)} to reset the hour
1339 * @param field the calendar field to be cleared.
1342 public final void clear(int field)
1345 stamp[field] = UNSET;
1346 isSet[field] = false;
1348 areAllFieldsSet = areFieldsSet = false;
1353 * Determines if the given calendar field has a value set,
1354 * including cases that the value has been set by internal fields
1355 * calculations triggered by a <code>get</code> method call.
1357 * @return <code>true</code> if the given calendar field has a value set;
1358 * <code>false</code> otherwise.
1360 public final boolean isSet(int field)
1362 return stamp[field] != UNSET;
1366 * Returns the string representation of the calendar
1367 * <code>field</code> value in the given <code>style</code> and
1368 * <code>locale</code>. If no string representation is
1369 * applicable, <code>null</code> is returned. This method calls
1370 * {@link Calendar#get(int) get(field)} to get the calendar
1371 * <code>field</code> value if the string representation is
1372 * applicable to the given calendar <code>field</code>.
1374 * <p>For example, if this <code>Calendar</code> is a
1375 * <code>GregorianCalendar</code> and its date is 2005-01-01, then
1376 * the string representation of the {@link #MONTH} field would be
1377 * "January" in the long style in an English locale or "Jan" in
1378 * the short style. However, no string representation would be
1379 * available for the {@link #DAY_OF_MONTH} field, and this method
1380 * would return <code>null</code>.
1382 * <p>The default implementation supports the calendar fields for
1383 * which a {@link DateFormatSymbols} has names in the given
1384 * <code>locale</code>.
1387 * the calendar field for which the string representation
1390 * the style applied to the string representation; one of
1391 * {@link #SHORT} or {@link #LONG}.
1393 * the locale for the string representation
1394 * @return the string representation of the given
1395 * <code>field</code> in the given <code>style</code>, or
1396 * <code>null</code> if no string representation is
1398 * @exception IllegalArgumentException
1399 * if <code>field</code> or <code>style</code> is invalid,
1400 * or if this <code>Calendar</code> is non-lenient and any
1401 * of the calendar fields have invalid values
1402 * @exception NullPointerException
1403 * if <code>locale</code> is null
1406 public String getDisplayName(int field, int style, Locale locale) {
1407 if (!checkDisplayNameParams(field, style, ALL_STYLES, LONG, locale,
1408 ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {
1412 DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
1413 String[] strings = getFieldStrings(field, style, symbols);
1414 if (strings != null) {
1415 int fieldValue = get(field);
1416 if (fieldValue < strings.length) {
1417 return strings[fieldValue];
1424 * Returns a <code>Map</code> containing all names of the calendar
1425 * <code>field</code> in the given <code>style</code> and
1426 * <code>locale</code> and their corresponding field values. For
1427 * example, if this <code>Calendar</code> is a {@link
1428 * GregorianCalendar}, the returned map would contain "Jan" to
1429 * {@link #JANUARY}, "Feb" to {@link #FEBRUARY}, and so on, in the
1430 * {@linkplain #SHORT short} style in an English locale.
1432 * <p>The values of other calendar fields may be taken into
1433 * account to determine a set of display names. For example, if
1434 * this <code>Calendar</code> is a lunisolar calendar system and
1435 * the year value given by the {@link #YEAR} field has a leap
1436 * month, this method would return month names containing the leap
1437 * month name, and month names are mapped to their values specific
1440 * <p>The default implementation supports display names contained in
1441 * a {@link DateFormatSymbols}. For example, if <code>field</code>
1442 * is {@link #MONTH} and <code>style</code> is {@link
1443 * #ALL_STYLES}, this method returns a <code>Map</code> containing
1444 * all strings returned by {@link DateFormatSymbols#getShortMonths()}
1445 * and {@link DateFormatSymbols#getMonths()}.
1448 * the calendar field for which the display names are returned
1450 * the style applied to the display names; one of {@link
1451 * #SHORT}, {@link #LONG}, or {@link #ALL_STYLES}.
1453 * the locale for the display names
1454 * @return a <code>Map</code> containing all display names in
1455 * <code>style</code> and <code>locale</code> and their
1456 * field values, or <code>null</code> if no display names
1457 * are defined for <code>field</code>
1458 * @exception IllegalArgumentException
1459 * if <code>field</code> or <code>style</code> is invalid,
1460 * or if this <code>Calendar</code> is non-lenient and any
1461 * of the calendar fields have invalid values
1462 * @exception NullPointerException
1463 * if <code>locale</code> is null
1466 public Map<String, Integer> getDisplayNames(int field, int style, Locale locale) {
1467 if (!checkDisplayNameParams(field, style, ALL_STYLES, LONG, locale,
1468 ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {
1473 if (style == ALL_STYLES) {
1474 Map<String,Integer> shortNames = getDisplayNamesImpl(field, SHORT, locale);
1475 if (field == ERA || field == AM_PM) {
1478 Map<String,Integer> longNames = getDisplayNamesImpl(field, LONG, locale);
1479 if (shortNames == null) {
1482 if (longNames != null) {
1483 shortNames.putAll(longNames);
1489 return getDisplayNamesImpl(field, style, locale);
1492 private Map<String,Integer> getDisplayNamesImpl(int field, int style, Locale locale) {
1493 DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
1494 String[] strings = getFieldStrings(field, style, symbols);
1495 if (strings != null) {
1496 Map<String,Integer> names = new HashMap<String,Integer>();
1497 for (int i = 0; i < strings.length; i++) {
1498 if (strings[i].length() == 0) {
1501 names.put(strings[i], i);
1508 boolean checkDisplayNameParams(int field, int style, int minStyle, int maxStyle,
1509 Locale locale, int fieldMask) {
1510 if (field < 0 || field >= fields.length ||
1511 style < minStyle || style > maxStyle) {
1512 throw new IllegalArgumentException();
1514 if (locale == null) {
1515 throw new NullPointerException();
1517 return isFieldSet(fieldMask, field);
1520 private String[] getFieldStrings(int field, int style, DateFormatSymbols symbols) {
1521 String[] strings = null;
1524 strings = symbols.getEras();
1528 strings = (style == LONG) ? symbols.getMonths() : symbols.getShortMonths();
1532 strings = (style == LONG) ? symbols.getWeekdays() : symbols.getShortWeekdays();
1536 strings = symbols.getAmPmStrings();
1543 * Fills in any unset fields in the calendar fields. First, the {@link
1544 * #computeTime()} method is called if the time value (millisecond offset
1545 * from the <a href="#Epoch">Epoch</a>) has not been calculated from
1546 * calendar field values. Then, the {@link #computeFields()} method is
1547 * called to calculate all calendar field values.
1549 protected void complete()
1553 if (!areFieldsSet || !areAllFieldsSet) {
1554 computeFields(); // fills in unset fields
1555 areAllFieldsSet = areFieldsSet = true;
1560 * Returns whether the value of the specified calendar field has been set
1561 * externally by calling one of the setter methods rather than by the
1562 * internal time calculation.
1564 * @return <code>true</code> if the field has been set externally,
1565 * <code>false</code> otherwise.
1566 * @exception IndexOutOfBoundsException if the specified
1567 * <code>field</code> is out of range
1568 * (<code>field < 0 || field >= FIELD_COUNT</code>).
1569 * @see #selectFields()
1570 * @see #setFieldsComputed(int)
1572 final boolean isExternallySet(int field) {
1573 return stamp[field] >= MINIMUM_USER_STAMP;
1577 * Returns a field mask (bit mask) indicating all calendar fields that
1578 * have the state of externally or internally set.
1580 * @return a bit mask indicating set state fields
1582 final int getSetStateFields() {
1584 for (int i = 0; i < fields.length; i++) {
1585 if (stamp[i] != UNSET) {
1593 * Sets the state of the specified calendar fields to
1594 * <em>computed</em>. This state means that the specified calendar fields
1595 * have valid values that have been set by internal time calculation
1596 * rather than by calling one of the setter methods.
1598 * @param fieldMask the field to be marked as computed.
1599 * @exception IndexOutOfBoundsException if the specified
1600 * <code>field</code> is out of range
1601 * (<code>field < 0 || field >= FIELD_COUNT</code>).
1602 * @see #isExternallySet(int)
1603 * @see #selectFields()
1605 final void setFieldsComputed(int fieldMask) {
1606 if (fieldMask == ALL_FIELDS) {
1607 for (int i = 0; i < fields.length; i++) {
1608 stamp[i] = COMPUTED;
1611 areFieldsSet = areAllFieldsSet = true;
1613 for (int i = 0; i < fields.length; i++) {
1614 if ((fieldMask & 1) == 1) {
1615 stamp[i] = COMPUTED;
1618 if (areAllFieldsSet && !isSet[i]) {
1619 areAllFieldsSet = false;
1628 * Sets the state of the calendar fields that are <em>not</em> specified
1629 * by <code>fieldMask</code> to <em>unset</em>. If <code>fieldMask</code>
1630 * specifies all the calendar fields, then the state of this
1631 * <code>Calendar</code> becomes that all the calendar fields are in sync
1632 * with the time value (millisecond offset from the Epoch).
1634 * @param fieldMask the field mask indicating which calendar fields are in
1635 * sync with the time value.
1636 * @exception IndexOutOfBoundsException if the specified
1637 * <code>field</code> is out of range
1638 * (<code>field < 0 || field >= FIELD_COUNT</code>).
1639 * @see #isExternallySet(int)
1640 * @see #selectFields()
1642 final void setFieldsNormalized(int fieldMask) {
1643 if (fieldMask != ALL_FIELDS) {
1644 for (int i = 0; i < fields.length; i++) {
1645 if ((fieldMask & 1) == 0) {
1646 stamp[i] = fields[i] = 0; // UNSET == 0
1653 // Some or all of the fields are in sync with the
1654 // milliseconds, but the stamp values are not normalized yet.
1655 areFieldsSet = true;
1656 areAllFieldsSet = false;
1660 * Returns whether the calendar fields are partially in sync with the time
1661 * value or fully in sync but not stamp values are not normalized yet.
1663 final boolean isPartiallyNormalized() {
1664 return areFieldsSet && !areAllFieldsSet;
1668 * Returns whether the calendar fields are fully in sync with the time
1671 final boolean isFullyNormalized() {
1672 return areFieldsSet && areAllFieldsSet;
1676 * Marks this Calendar as not sync'd.
1678 final void setUnnormalized() {
1679 areFieldsSet = areAllFieldsSet = false;
1683 * Returns whether the specified <code>field</code> is on in the
1684 * <code>fieldMask</code>.
1686 static final boolean isFieldSet(int fieldMask, int field) {
1687 return (fieldMask & (1 << field)) != 0;
1691 * Returns a field mask indicating which calendar field values
1692 * to be used to calculate the time value. The calendar fields are
1693 * returned as a bit mask, each bit of which corresponds to a field, i.e.,
1694 * the mask value of <code>field</code> is <code>(1 <<
1695 * field)</code>. For example, 0x26 represents the <code>YEAR</code>,
1696 * <code>MONTH</code>, and <code>DAY_OF_MONTH</code> fields (i.e., 0x26 is
1698 * <code>(1<<YEAR)|(1<<MONTH)|(1<<DAY_OF_MONTH))</code>.
1700 * <p>This method supports the calendar fields resolution as described in
1701 * the class description. If the bit mask for a given field is on and its
1702 * field has not been set (i.e., <code>isSet(field)</code> is
1703 * <code>false</code>), then the default value of the field has to be
1704 * used, which case means that the field has been selected because the
1705 * selected combination involves the field.
1707 * @return a bit mask of selected fields
1708 * @see #isExternallySet(int)
1709 * @see #setInternallySetState(int)
1711 final int selectFields() {
1712 // This implementation has been taken from the GregorianCalendar class.
1714 // The YEAR field must always be used regardless of its SET
1715 // state because YEAR is a mandatory field to determine the date
1716 // and the default value (EPOCH_YEAR) may change through the
1717 // normalization process.
1718 int fieldMask = YEAR_MASK;
1720 if (stamp[ERA] != UNSET) {
1721 fieldMask |= ERA_MASK;
1723 // Find the most recent group of fields specifying the day within
1724 // the year. These may be any of the following combinations:
1725 // MONTH + DAY_OF_MONTH
1726 // MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
1727 // MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
1729 // WEEK_OF_YEAR + DAY_OF_WEEK
1730 // We look for the most recent of the fields in each group to determine
1731 // the age of the group. For groups involving a week-related field such
1732 // as WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR, both the
1733 // week-related field and the DAY_OF_WEEK must be set for the group as a
1734 // whole to be considered. (See bug 4153860 - liu 7/24/98.)
1735 int dowStamp = stamp[DAY_OF_WEEK];
1736 int monthStamp = stamp[MONTH];
1737 int domStamp = stamp[DAY_OF_MONTH];
1738 int womStamp = aggregateStamp(stamp[WEEK_OF_MONTH], dowStamp);
1739 int dowimStamp = aggregateStamp(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
1740 int doyStamp = stamp[DAY_OF_YEAR];
1741 int woyStamp = aggregateStamp(stamp[WEEK_OF_YEAR], dowStamp);
1743 int bestStamp = domStamp;
1744 if (womStamp > bestStamp) {
1745 bestStamp = womStamp;
1747 if (dowimStamp > bestStamp) {
1748 bestStamp = dowimStamp;
1750 if (doyStamp > bestStamp) {
1751 bestStamp = doyStamp;
1753 if (woyStamp > bestStamp) {
1754 bestStamp = woyStamp;
1757 /* No complete combination exists. Look for WEEK_OF_MONTH,
1758 * DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR alone. Treat DAY_OF_WEEK alone
1759 * as DAY_OF_WEEK_IN_MONTH.
1761 if (bestStamp == UNSET) {
1762 womStamp = stamp[WEEK_OF_MONTH];
1763 dowimStamp = Math.max(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
1764 woyStamp = stamp[WEEK_OF_YEAR];
1765 bestStamp = Math.max(Math.max(womStamp, dowimStamp), woyStamp);
1767 /* Treat MONTH alone or no fields at all as DAY_OF_MONTH. This may
1768 * result in bestStamp = domStamp = UNSET if no fields are set,
1769 * which indicates DAY_OF_MONTH.
1771 if (bestStamp == UNSET) {
1772 bestStamp = domStamp = monthStamp;
1776 if (bestStamp == domStamp ||
1777 (bestStamp == womStamp && stamp[WEEK_OF_MONTH] >= stamp[WEEK_OF_YEAR]) ||
1778 (bestStamp == dowimStamp && stamp[DAY_OF_WEEK_IN_MONTH] >= stamp[WEEK_OF_YEAR])) {
1779 fieldMask |= MONTH_MASK;
1780 if (bestStamp == domStamp) {
1781 fieldMask |= DAY_OF_MONTH_MASK;
1783 assert (bestStamp == womStamp || bestStamp == dowimStamp);
1784 if (dowStamp != UNSET) {
1785 fieldMask |= DAY_OF_WEEK_MASK;
1787 if (womStamp == dowimStamp) {
1788 // When they are equal, give the priority to
1789 // WEEK_OF_MONTH for compatibility.
1790 if (stamp[WEEK_OF_MONTH] >= stamp[DAY_OF_WEEK_IN_MONTH]) {
1791 fieldMask |= WEEK_OF_MONTH_MASK;
1793 fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK;
1796 if (bestStamp == womStamp) {
1797 fieldMask |= WEEK_OF_MONTH_MASK;
1799 assert (bestStamp == dowimStamp);
1800 if (stamp[DAY_OF_WEEK_IN_MONTH] != UNSET) {
1801 fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK;
1807 assert (bestStamp == doyStamp || bestStamp == woyStamp ||
1808 bestStamp == UNSET);
1809 if (bestStamp == doyStamp) {
1810 fieldMask |= DAY_OF_YEAR_MASK;
1812 assert (bestStamp == woyStamp);
1813 if (dowStamp != UNSET) {
1814 fieldMask |= DAY_OF_WEEK_MASK;
1816 fieldMask |= WEEK_OF_YEAR_MASK;
1820 // Find the best set of fields specifying the time of day. There
1821 // are only two possibilities here; the HOUR_OF_DAY or the
1822 // AM_PM and the HOUR.
1823 int hourOfDayStamp = stamp[HOUR_OF_DAY];
1824 int hourStamp = aggregateStamp(stamp[HOUR], stamp[AM_PM]);
1825 bestStamp = (hourStamp > hourOfDayStamp) ? hourStamp : hourOfDayStamp;
1827 // if bestStamp is still UNSET, then take HOUR or AM_PM. (See 4846659)
1828 if (bestStamp == UNSET) {
1829 bestStamp = Math.max(stamp[HOUR], stamp[AM_PM]);
1833 if (bestStamp != UNSET) {
1834 if (bestStamp == hourOfDayStamp) {
1835 fieldMask |= HOUR_OF_DAY_MASK;
1837 fieldMask |= HOUR_MASK;
1838 if (stamp[AM_PM] != UNSET) {
1839 fieldMask |= AM_PM_MASK;
1843 if (stamp[MINUTE] != UNSET) {
1844 fieldMask |= MINUTE_MASK;
1846 if (stamp[SECOND] != UNSET) {
1847 fieldMask |= SECOND_MASK;
1849 if (stamp[MILLISECOND] != UNSET) {
1850 fieldMask |= MILLISECOND_MASK;
1852 if (stamp[ZONE_OFFSET] >= MINIMUM_USER_STAMP) {
1853 fieldMask |= ZONE_OFFSET_MASK;
1855 if (stamp[DST_OFFSET] >= MINIMUM_USER_STAMP) {
1856 fieldMask |= DST_OFFSET_MASK;
1863 * Returns the pseudo-time-stamp for two fields, given their
1864 * individual pseudo-time-stamps. If either of the fields
1865 * is unset, then the aggregate is unset. Otherwise, the
1866 * aggregate is the later of the two stamps.
1868 private static final int aggregateStamp(int stamp_a, int stamp_b) {
1869 if (stamp_a == UNSET || stamp_b == UNSET) {
1872 return (stamp_a > stamp_b) ? stamp_a : stamp_b;
1876 * Compares this <code>Calendar</code> to the specified
1877 * <code>Object</code>. The result is <code>true</code> if and only if
1878 * the argument is a <code>Calendar</code> object of the same calendar
1879 * system that represents the same time value (millisecond offset from the
1880 * <a href="#Epoch">Epoch</a>) under the same
1881 * <code>Calendar</code> parameters as this object.
1883 * <p>The <code>Calendar</code> parameters are the values represented
1884 * by the <code>isLenient</code>, <code>getFirstDayOfWeek</code>,
1885 * <code>getMinimalDaysInFirstWeek</code> and <code>getTimeZone</code>
1886 * methods. If there is any difference in those parameters
1887 * between the two <code>Calendar</code>s, this method returns
1888 * <code>false</code>.
1890 * <p>Use the {@link #compareTo(Calendar) compareTo} method to
1891 * compare only the time values.
1893 * @param obj the object to compare with.
1894 * @return <code>true</code> if this object is equal to <code>obj</code>;
1895 * <code>false</code> otherwise.
1897 public boolean equals(Object obj) {
1901 Calendar that = (Calendar)obj;
1902 return compareTo(getMillisOf(that)) == 0 &&
1903 lenient == that.lenient &&
1904 firstDayOfWeek == that.firstDayOfWeek &&
1905 minimalDaysInFirstWeek == that.minimalDaysInFirstWeek &&
1906 zone.equals(that.zone);
1907 } catch (Exception e) {
1908 // Note: GregorianCalendar.computeTime throws
1909 // IllegalArgumentException if the ERA value is invalid
1910 // even it's in lenient mode.
1916 * Returns a hash code for this calendar.
1918 * @return a hash code value for this object.
1921 public int hashCode() {
1922 // 'otheritems' represents the hash code for the previous versions.
1923 int otheritems = (lenient ? 1 : 0)
1924 | (firstDayOfWeek << 1)
1925 | (minimalDaysInFirstWeek << 4)
1926 | (zone.hashCode() << 7);
1927 long t = getMillisOf(this);
1928 return (int) t ^ (int)(t >> 32) ^ otheritems;
1932 * Returns whether this <code>Calendar</code> represents a time
1933 * before the time represented by the specified
1934 * <code>Object</code>. This method is equivalent to:
1936 * compareTo(when) < 0
1937 * </blockquote></pre>
1938 * if and only if <code>when</code> is a <code>Calendar</code>
1939 * instance. Otherwise, the method returns <code>false</code>.
1941 * @param when the <code>Object</code> to be compared
1942 * @return <code>true</code> if the time of this
1943 * <code>Calendar</code> is before the time represented by
1944 * <code>when</code>; <code>false</code> otherwise.
1945 * @see #compareTo(Calendar)
1947 public boolean before(Object when) {
1948 return when instanceof Calendar
1949 && compareTo((Calendar)when) < 0;
1953 * Returns whether this <code>Calendar</code> represents a time
1954 * after the time represented by the specified
1955 * <code>Object</code>. This method is equivalent to:
1957 * compareTo(when) > 0
1958 * </blockquote></pre>
1959 * if and only if <code>when</code> is a <code>Calendar</code>
1960 * instance. Otherwise, the method returns <code>false</code>.
1962 * @param when the <code>Object</code> to be compared
1963 * @return <code>true</code> if the time of this <code>Calendar</code> is
1964 * after the time represented by <code>when</code>; <code>false</code>
1966 * @see #compareTo(Calendar)
1968 public boolean after(Object when) {
1969 return when instanceof Calendar
1970 && compareTo((Calendar)when) > 0;
1974 * Compares the time values (millisecond offsets from the <a
1975 * href="#Epoch">Epoch</a>) represented by two
1976 * <code>Calendar</code> objects.
1978 * @param anotherCalendar the <code>Calendar</code> to be compared.
1979 * @return the value <code>0</code> if the time represented by the argument
1980 * is equal to the time represented by this <code>Calendar</code>; a value
1981 * less than <code>0</code> if the time of this <code>Calendar</code> is
1982 * before the time represented by the argument; and a value greater than
1983 * <code>0</code> if the time of this <code>Calendar</code> is after the
1984 * time represented by the argument.
1985 * @exception NullPointerException if the specified <code>Calendar</code> is
1986 * <code>null</code>.
1987 * @exception IllegalArgumentException if the time value of the
1988 * specified <code>Calendar</code> object can't be obtained due to
1989 * any invalid calendar values.
1992 public int compareTo(Calendar anotherCalendar) {
1993 return compareTo(getMillisOf(anotherCalendar));
1997 * Adds or subtracts the specified amount of time to the given calendar field,
1998 * based on the calendar's rules. For example, to subtract 5 days from
1999 * the current time of the calendar, you can achieve it by calling:
2000 * <p><code>add(Calendar.DAY_OF_MONTH, -5)</code>.
2002 * @param field the calendar field.
2003 * @param amount the amount of date or time to be added to the field.
2004 * @see #roll(int,int)
2005 * @see #set(int,int)
2007 abstract public void add(int field, int amount);
2010 * Adds or subtracts (up/down) a single unit of time on the given time
2011 * field without changing larger fields. For example, to roll the current
2012 * date up by one day, you can achieve it by calling:
2013 * <p>roll(Calendar.DATE, true).
2014 * When rolling on the year or Calendar.YEAR field, it will roll the year
2015 * value in the range between 1 and the value returned by calling
2016 * <code>getMaximum(Calendar.YEAR)</code>.
2017 * When rolling on the month or Calendar.MONTH field, other fields like
2018 * date might conflict and, need to be changed. For instance,
2019 * rolling the month on the date 01/31/96 will result in 02/29/96.
2020 * When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field, it will
2021 * roll the hour value in the range between 0 and 23, which is zero-based.
2023 * @param field the time field.
2024 * @param up indicates if the value of the specified time field is to be
2025 * rolled up or rolled down. Use true if rolling up, false otherwise.
2026 * @see Calendar#add(int,int)
2027 * @see Calendar#set(int,int)
2029 abstract public void roll(int field, boolean up);
2032 * Adds the specified (signed) amount to the specified calendar field
2033 * without changing larger fields. A negative amount means to roll
2036 * <p>NOTE: This default implementation on <code>Calendar</code> just repeatedly calls the
2037 * version of {@link #roll(int,boolean) roll()} that rolls by one unit. This may not
2038 * always do the right thing. For example, if the <code>DAY_OF_MONTH</code> field is 31,
2039 * rolling through February will leave it set to 28. The <code>GregorianCalendar</code>
2040 * version of this function takes care of this problem. Other subclasses
2041 * should also provide overrides of this function that do the right thing.
2043 * @param field the calendar field.
2044 * @param amount the signed amount to add to the calendar <code>field</code>.
2046 * @see #roll(int,boolean)
2047 * @see #add(int,int)
2048 * @see #set(int,int)
2050 public void roll(int field, int amount)
2052 while (amount > 0) {
2056 while (amount < 0) {
2063 * Sets the time zone with the given time zone value.
2065 * @param value the given time zone.
2067 public void setTimeZone(TimeZone value)
2071 /* Recompute the fields from the time using the new zone. This also
2072 * works if isTimeSet is false (after a call to set()). In that case
2073 * the time will be computed from the fields using the new zone, then
2074 * the fields will get recomputed from that. Consider the sequence of
2075 * calls: cal.setTimeZone(EST); cal.set(HOUR, 1); cal.setTimeZone(PST).
2076 * Is cal set to 1 o'clock EST or 1 o'clock PST? Answer: PST. More
2077 * generally, a call to setTimeZone() affects calls to set() BEFORE AND
2078 * AFTER it up to the next call to complete().
2080 areAllFieldsSet = areFieldsSet = false;
2084 * Gets the time zone.
2086 * @return the time zone object associated with this calendar.
2088 public TimeZone getTimeZone()
2090 // If the TimeZone object is shared by other Calendar instances, then
2093 zone = (TimeZone) zone.clone();
2100 * Returns the time zone (without cloning).
2102 TimeZone getZone() {
2107 * Sets the sharedZone flag to <code>shared</code>.
2109 void setZoneShared(boolean shared) {
2110 sharedZone = shared;
2114 * Specifies whether or not date/time interpretation is to be lenient. With
2115 * lenient interpretation, a date such as "February 942, 1996" will be
2116 * treated as being equivalent to the 941st day after February 1, 1996.
2117 * With strict (non-lenient) interpretation, such dates will cause an exception to be
2118 * thrown. The default is lenient.
2120 * @param lenient <code>true</code> if the lenient mode is to be turned
2121 * on; <code>false</code> if it is to be turned off.
2123 * @see java.text.DateFormat#setLenient
2125 public void setLenient(boolean lenient)
2127 this.lenient = lenient;
2131 * Tells whether date/time interpretation is to be lenient.
2133 * @return <code>true</code> if the interpretation mode of this calendar is lenient;
2134 * <code>false</code> otherwise.
2135 * @see #setLenient(boolean)
2137 public boolean isLenient()
2143 * Sets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
2144 * <code>MONDAY</code> in France.
2146 * @param value the given first day of the week.
2147 * @see #getFirstDayOfWeek()
2148 * @see #getMinimalDaysInFirstWeek()
2150 public void setFirstDayOfWeek(int value)
2152 if (firstDayOfWeek == value) {
2155 firstDayOfWeek = value;
2156 invalidateWeekFields();
2160 * Gets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
2161 * <code>MONDAY</code> in France.
2163 * @return the first day of the week.
2164 * @see #setFirstDayOfWeek(int)
2165 * @see #getMinimalDaysInFirstWeek()
2167 public int getFirstDayOfWeek()
2169 return firstDayOfWeek;
2173 * Sets what the minimal days required in the first week of the year are;
2174 * For example, if the first week is defined as one that contains the first
2175 * day of the first month of a year, call this method with value 1. If it
2176 * must be a full week, use value 7.
2178 * @param value the given minimal days required in the first week
2180 * @see #getMinimalDaysInFirstWeek()
2182 public void setMinimalDaysInFirstWeek(int value)
2184 if (minimalDaysInFirstWeek == value) {
2187 minimalDaysInFirstWeek = value;
2188 invalidateWeekFields();
2192 * Gets what the minimal days required in the first week of the year are;
2193 * e.g., if the first week is defined as one that contains the first day
2194 * of the first month of a year, this method returns 1. If
2195 * the minimal days required must be a full week, this method
2198 * @return the minimal days required in the first week of the year.
2199 * @see #setMinimalDaysInFirstWeek(int)
2201 public int getMinimalDaysInFirstWeek()
2203 return minimalDaysInFirstWeek;
2207 * Returns whether this {@code Calendar} supports week dates.
2209 * <p>The default implementation of this method returns {@code false}.
2211 * @return {@code true} if this {@code Calendar} supports week dates;
2212 * {@code false} otherwise.
2213 * @see #getWeekYear()
2214 * @see #setWeekDate(int,int,int)
2215 * @see #getWeeksInWeekYear()
2218 public boolean isWeekDateSupported() {
2223 * Returns the week year represented by this {@code Calendar}. The
2224 * week year is in sync with the week cycle. The {@linkplain
2225 * #getFirstDayOfWeek() first day of the first week} is the first
2226 * day of the week year.
2228 * <p>The default implementation of this method throws an
2229 * {@link UnsupportedOperationException}.
2231 * @return the week year of this {@code Calendar}
2232 * @exception UnsupportedOperationException
2233 * if any week year numbering isn't supported
2234 * in this {@code Calendar}.
2235 * @see #isWeekDateSupported()
2236 * @see #getFirstDayOfWeek()
2237 * @see #getMinimalDaysInFirstWeek()
2240 public int getWeekYear() {
2241 throw new UnsupportedOperationException();
2245 * Sets the date of this {@code Calendar} with the the given date
2246 * specifiers - week year, week of year, and day of week.
2248 * <p>Unlike the {@code set} method, all of the calendar fields
2249 * and {@code time} values are calculated upon return.
2251 * <p>If {@code weekOfYear} is out of the valid week-of-year range
2252 * in {@code weekYear}, the {@code weekYear} and {@code
2253 * weekOfYear} values are adjusted in lenient mode, or an {@code
2254 * IllegalArgumentException} is thrown in non-lenient mode.
2256 * <p>The default implementation of this method throws an
2257 * {@code UnsupportedOperationException}.
2259 * @param weekYear the week year
2260 * @param weekOfYear the week number based on {@code weekYear}
2261 * @param dayOfWeek the day of week value: one of the constants
2262 * for the {@link #DAY_OF_WEEK} field: {@link
2263 * #SUNDAY}, ..., {@link #SATURDAY}.
2264 * @exception IllegalArgumentException
2265 * if any of the given date specifiers is invalid
2266 * or any of the calendar fields are inconsistent
2267 * with the given date specifiers in non-lenient mode
2268 * @exception UnsupportedOperationException
2269 * if any week year numbering isn't supported in this
2271 * @see #isWeekDateSupported()
2272 * @see #getFirstDayOfWeek()
2273 * @see #getMinimalDaysInFirstWeek()
2276 public void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) {
2277 throw new UnsupportedOperationException();
2281 * Returns the number of weeks in the week year represented by this
2284 * <p>The default implementation of this method throws an
2285 * {@code UnsupportedOperationException}.
2287 * @return the number of weeks in the week year.
2288 * @exception UnsupportedOperationException
2289 * if any week year numbering isn't supported in this
2291 * @see #WEEK_OF_YEAR
2292 * @see #isWeekDateSupported()
2293 * @see #getWeekYear()
2294 * @see #getActualMaximum(int)
2297 public int getWeeksInWeekYear() {
2298 throw new UnsupportedOperationException();
2302 * Returns the minimum value for the given calendar field of this
2303 * <code>Calendar</code> instance. The minimum value is defined as
2304 * the smallest value returned by the {@link #get(int) get} method
2305 * for any possible time value. The minimum value depends on
2306 * calendar system specific parameters of the instance.
2308 * @param field the calendar field.
2309 * @return the minimum value for the given calendar field.
2310 * @see #getMaximum(int)
2311 * @see #getGreatestMinimum(int)
2312 * @see #getLeastMaximum(int)
2313 * @see #getActualMinimum(int)
2314 * @see #getActualMaximum(int)
2316 abstract public int getMinimum(int field);
2319 * Returns the maximum value for the given calendar field of this
2320 * <code>Calendar</code> instance. The maximum value is defined as
2321 * the largest value returned by the {@link #get(int) get} method
2322 * for any possible time value. The maximum value depends on
2323 * calendar system specific parameters of the instance.
2325 * @param field the calendar field.
2326 * @return the maximum value for the given calendar field.
2327 * @see #getMinimum(int)
2328 * @see #getGreatestMinimum(int)
2329 * @see #getLeastMaximum(int)
2330 * @see #getActualMinimum(int)
2331 * @see #getActualMaximum(int)
2333 abstract public int getMaximum(int field);
2336 * Returns the highest minimum value for the given calendar field
2337 * of this <code>Calendar</code> instance. The highest minimum
2338 * value is defined as the largest value returned by {@link
2339 * #getActualMinimum(int)} for any possible time value. The
2340 * greatest minimum value depends on calendar system specific
2341 * parameters of the instance.
2343 * @param field the calendar field.
2344 * @return the highest minimum value for the given calendar field.
2345 * @see #getMinimum(int)
2346 * @see #getMaximum(int)
2347 * @see #getLeastMaximum(int)
2348 * @see #getActualMinimum(int)
2349 * @see #getActualMaximum(int)
2351 abstract public int getGreatestMinimum(int field);
2354 * Returns the lowest maximum value for the given calendar field
2355 * of this <code>Calendar</code> instance. The lowest maximum
2356 * value is defined as the smallest value returned by {@link
2357 * #getActualMaximum(int)} for any possible time value. The least
2358 * maximum value depends on calendar system specific parameters of
2359 * the instance. For example, a <code>Calendar</code> for the
2360 * Gregorian calendar system returns 28 for the
2361 * <code>DAY_OF_MONTH</code> field, because the 28th is the last
2362 * day of the shortest month of this calendar, February in a
2365 * @param field the calendar field.
2366 * @return the lowest maximum value for the given calendar field.
2367 * @see #getMinimum(int)
2368 * @see #getMaximum(int)
2369 * @see #getGreatestMinimum(int)
2370 * @see #getActualMinimum(int)
2371 * @see #getActualMaximum(int)
2373 abstract public int getLeastMaximum(int field);
2376 * Returns the minimum value that the specified calendar field
2377 * could have, given the time value of this <code>Calendar</code>.
2379 * <p>The default implementation of this method uses an iterative
2380 * algorithm to determine the actual minimum value for the
2381 * calendar field. Subclasses should, if possible, override this
2382 * with a more efficient implementation - in many cases, they can
2383 * simply return <code>getMinimum()</code>.
2385 * @param field the calendar field
2386 * @return the minimum of the given calendar field for the time
2387 * value of this <code>Calendar</code>
2388 * @see #getMinimum(int)
2389 * @see #getMaximum(int)
2390 * @see #getGreatestMinimum(int)
2391 * @see #getLeastMaximum(int)
2392 * @see #getActualMaximum(int)
2395 public int getActualMinimum(int field) {
2396 int fieldValue = getGreatestMinimum(field);
2397 int endValue = getMinimum(field);
2399 // if we know that the minimum value is always the same, just return it
2400 if (fieldValue == endValue) {
2404 // clone the calendar so we don't mess with the real one, and set it to
2405 // accept anything for the field values
2406 Calendar work = (Calendar)this.clone();
2407 work.setLenient(true);
2409 // now try each value from getLeastMaximum() to getMaximum() one by one until
2410 // we get a value that normalizes to another value. The last value that
2411 // normalizes to itself is the actual minimum for the current date
2412 int result = fieldValue;
2415 work.set(field, fieldValue);
2416 if (work.get(field) != fieldValue) {
2419 result = fieldValue;
2422 } while (fieldValue >= endValue);
2428 * Returns the maximum value that the specified calendar field
2429 * could have, given the time value of this
2430 * <code>Calendar</code>. For example, the actual maximum value of
2431 * the <code>MONTH</code> field is 12 in some years, and 13 in
2432 * other years in the Hebrew calendar system.
2434 * <p>The default implementation of this method uses an iterative
2435 * algorithm to determine the actual maximum value for the
2436 * calendar field. Subclasses should, if possible, override this
2437 * with a more efficient implementation.
2439 * @param field the calendar field
2440 * @return the maximum of the given calendar field for the time
2441 * value of this <code>Calendar</code>
2442 * @see #getMinimum(int)
2443 * @see #getMaximum(int)
2444 * @see #getGreatestMinimum(int)
2445 * @see #getLeastMaximum(int)
2446 * @see #getActualMinimum(int)
2449 public int getActualMaximum(int field) {
2450 int fieldValue = getLeastMaximum(field);
2451 int endValue = getMaximum(field);
2453 // if we know that the maximum value is always the same, just return it.
2454 if (fieldValue == endValue) {
2458 // clone the calendar so we don't mess with the real one, and set it to
2459 // accept anything for the field values.
2460 Calendar work = (Calendar)this.clone();
2461 work.setLenient(true);
2463 // if we're counting weeks, set the day of the week to Sunday. We know the
2464 // last week of a month or year will contain the first day of the week.
2465 if (field == WEEK_OF_YEAR || field == WEEK_OF_MONTH)
2466 work.set(DAY_OF_WEEK, firstDayOfWeek);
2468 // now try each value from getLeastMaximum() to getMaximum() one by one until
2469 // we get a value that normalizes to another value. The last value that
2470 // normalizes to itself is the actual maximum for the current date
2471 int result = fieldValue;
2474 work.set(field, fieldValue);
2475 if (work.get(field) != fieldValue) {
2478 result = fieldValue;
2481 } while (fieldValue <= endValue);
2487 * Creates and returns a copy of this object.
2489 * @return a copy of this object.
2491 public Object clone()
2494 Calendar other = (Calendar) super.clone();
2496 other.fields = new int[FIELD_COUNT];
2497 other.isSet = new boolean[FIELD_COUNT];
2498 other.stamp = new int[FIELD_COUNT];
2499 for (int i = 0; i < FIELD_COUNT; i++) {
2500 other.fields[i] = fields[i];
2501 other.stamp[i] = stamp[i];
2502 other.isSet[i] = isSet[i];
2504 other.zone = (TimeZone) zone.clone();
2507 catch (CloneNotSupportedException e) {
2508 // this shouldn't happen, since we are Cloneable
2509 throw new InternalError();
2513 private static final String[] FIELD_NAME = {
2514 "ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH", "DAY_OF_MONTH",
2515 "DAY_OF_YEAR", "DAY_OF_WEEK", "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR",
2516 "HOUR_OF_DAY", "MINUTE", "SECOND", "MILLISECOND", "ZONE_OFFSET",
2521 * Returns the name of the specified calendar field.
2523 * @param field the calendar field
2524 * @return the calendar field name
2525 * @exception IndexOutOfBoundsException if <code>field</code> is negative,
2526 * equal to or greater then <code>FIELD_COUNT</code>.
2528 static final String getFieldName(int field) {
2529 return FIELD_NAME[field];
2533 * Return a string representation of this calendar. This method
2534 * is intended to be used only for debugging purposes, and the
2535 * format of the returned string may vary between implementations.
2536 * The returned string may be empty but may not be <code>null</code>.
2538 * @return a string representation of this calendar.
2540 public String toString() {
2541 // NOTE: BuddhistCalendar.toString() interprets the string
2542 // produced by this method so that the Gregorian year number
2543 // is substituted by its B.E. year value. It relies on
2544 // "...,YEAR=<year>,..." or "...,YEAR=?,...".
2545 StringBuilder buffer = new StringBuilder(800);
2546 buffer.append(getClass().getName()).append('[');
2547 appendValue(buffer, "time", isTimeSet, time);
2548 buffer.append(",areFieldsSet=").append(areFieldsSet);
2549 buffer.append(",areAllFieldsSet=").append(areAllFieldsSet);
2550 buffer.append(",lenient=").append(lenient);
2551 buffer.append(",zone=").append(zone);
2552 appendValue(buffer, ",firstDayOfWeek", true, (long) firstDayOfWeek);
2553 appendValue(buffer, ",minimalDaysInFirstWeek", true, (long) minimalDaysInFirstWeek);
2554 for (int i = 0; i < FIELD_COUNT; ++i) {
2556 appendValue(buffer, FIELD_NAME[i], isSet(i), (long) fields[i]);
2559 return buffer.toString();
2562 // =======================privates===============================
2564 private static final void appendValue(StringBuilder sb, String item, boolean valid, long value) {
2565 sb.append(item).append('=');
2574 * Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent.
2575 * They are used to figure out the week count for a specific date for
2576 * a given locale. These must be set when a Calendar is constructed.
2577 * @param desiredLocale the given locale.
2579 private void setWeekCountData(Locale desiredLocale)
2581 /* try to get the Locale data from the cache */
2582 int[] data = cachedLocaleData.get(desiredLocale);
2583 if (data == null) { /* cache miss */
2584 // ResourceBundle bundle = LocaleData.getCalendarData(desiredLocale);
2586 // data[0] = Integer.parseInt(bundle.getString("firstDayOfWeek"));
2587 // data[1] = Integer.parseInt(bundle.getString("minimalDaysInFirstWeek"));
2588 cachedLocaleData.putIfAbsent(desiredLocale, data);
2590 firstDayOfWeek = data[0];
2591 minimalDaysInFirstWeek = data[1];
2595 * Recomputes the time and updates the status fields isTimeSet
2596 * and areFieldsSet. Callers should check isTimeSet and only
2597 * call this method if isTimeSet is false.
2599 private void updateTime() {
2601 // The areFieldsSet and areAllFieldsSet values are no longer
2602 // controlled here (as of 1.5).
2606 private int compareTo(long t) {
2607 long thisTime = getMillisOf(this);
2608 return (thisTime > t) ? 1 : (thisTime == t) ? 0 : -1;
2611 private static final long getMillisOf(Calendar calendar) {
2612 if (calendar.isTimeSet) {
2613 return calendar.time;
2615 Calendar cal = (Calendar) calendar.clone();
2616 cal.setLenient(true);
2617 return cal.getTimeInMillis();
2621 * Adjusts the stamp[] values before nextStamp overflow. nextStamp
2622 * is set to the next stamp value upon the return.
2624 private final void adjustStamp() {
2625 int max = MINIMUM_USER_STAMP;
2626 int newStamp = MINIMUM_USER_STAMP;
2629 int min = Integer.MAX_VALUE;
2630 for (int i = 0; i < stamp.length; i++) {
2632 if (v >= newStamp && min > v) {
2639 if (max != min && min == Integer.MAX_VALUE) {
2642 for (int i = 0; i < stamp.length; i++) {
2643 if (stamp[i] == min) {
2644 stamp[i] = newStamp;
2652 nextStamp = newStamp;
2656 * Sets the WEEK_OF_MONTH and WEEK_OF_YEAR fields to new values with the
2657 * new parameter value if they have been calculated internally.
2659 private void invalidateWeekFields()
2661 if (stamp[WEEK_OF_MONTH] != COMPUTED &&
2662 stamp[WEEK_OF_YEAR] != COMPUTED) {
2666 // We have to check the new values of these fields after changing
2667 // firstDayOfWeek and/or minimalDaysInFirstWeek. If the field values
2668 // have been changed, then set the new values. (4822110)
2669 Calendar cal = (Calendar) clone();
2670 cal.setLenient(true);
2671 cal.clear(WEEK_OF_MONTH);
2672 cal.clear(WEEK_OF_YEAR);
2674 if (stamp[WEEK_OF_MONTH] == COMPUTED) {
2675 int weekOfMonth = cal.get(WEEK_OF_MONTH);
2676 if (fields[WEEK_OF_MONTH] != weekOfMonth) {
2677 fields[WEEK_OF_MONTH] = weekOfMonth;
2681 if (stamp[WEEK_OF_YEAR] == COMPUTED) {
2682 int weekOfYear = cal.get(WEEK_OF_YEAR);
2683 if (fields[WEEK_OF_YEAR] != weekOfYear) {
2684 fields[WEEK_OF_YEAR] = weekOfYear;
2690 * Save the state of this object to a stream (i.e., serialize it).
2692 * Ideally, <code>Calendar</code> would only write out its state data and
2693 * the current time, and not write any field data out, such as
2694 * <code>fields[]</code>, <code>isTimeSet</code>, <code>areFieldsSet</code>,
2695 * and <code>isSet[]</code>. <code>nextStamp</code> also should not be part
2696 * of the persistent state. Unfortunately, this didn't happen before JDK 1.1
2697 * shipped. To be compatible with JDK 1.1, we will always have to write out
2698 * the field values and state flags. However, <code>nextStamp</code> can be
2699 * removed from the serialization stream; this will probably happen in the
2702 private void writeObject(ObjectOutputStream stream)
2705 // Try to compute the time correctly, for the future (stream
2706 // version 2) in which we don't write out fields[] or isSet[].
2711 catch (IllegalArgumentException e) {}
2714 // If this Calendar has a ZoneInfo, save it and set a
2715 // SimpleTimeZone equivalent (as a single DST schedule) for
2716 // backward compatibility.
2717 TimeZone savedZone = null;
2718 // if (zone instanceof ZoneInfo) {
2719 // SimpleTimeZone stz = ((ZoneInfo)zone).getLastRuleInstance();
2720 // if (stz == null) {
2721 // stz = new SimpleTimeZone(zone.getRawOffset(), zone.getID());
2723 // savedZone = zone;
2727 // Write out the 1.1 FCS object.
2728 stream.defaultWriteObject();
2730 // Write out the ZoneInfo object
2731 // 4802409: we write out even if it is null, a temporary workaround
2732 // the real fix for bug 4844924 in corba-iiop
2733 stream.writeObject(savedZone);
2734 if (savedZone != null) {
2740 * Reconstitutes this object from a stream (i.e., deserialize it).
2742 private void readObject(ObjectInputStream stream)
2743 throws IOException, ClassNotFoundException
2745 final ObjectInputStream input = stream;
2746 input.defaultReadObject();
2748 stamp = new int[FIELD_COUNT];
2750 // Starting with version 2 (not implemented yet), we expect that
2751 // fields[], isSet[], isTimeSet, and areFieldsSet may not be
2752 // streamed out anymore. We expect 'time' to be correct.
2753 if (serialVersionOnStream >= 2)
2756 if (fields == null) fields = new int[FIELD_COUNT];
2757 if (isSet == null) isSet = new boolean[FIELD_COUNT];
2759 else if (serialVersionOnStream >= 0)
2761 for (int i=0; i<FIELD_COUNT; ++i)
2762 stamp[i] = isSet[i] ? COMPUTED : UNSET;
2765 serialVersionOnStream = currentSerialVersion;
2767 // If there's a ZoneInfo object, use it for zone.
2770 // zi = AccessController.doPrivileged(
2771 // new PrivilegedExceptionAction<ZoneInfo>() {
2772 // public ZoneInfo run() throws Exception {
2773 // return (ZoneInfo) input.readObject();
2776 // CalendarAccessControlContext.INSTANCE);
2777 // } catch (PrivilegedActionException pae) {
2778 // Exception e = pae.getException();
2779 // if (!(e instanceof OptionalDataException)) {
2780 // if (e instanceof RuntimeException) {
2781 // throw (RuntimeException) e;
2782 // } else if (e instanceof IOException) {
2783 // throw (IOException) e;
2784 // } else if (e instanceof ClassNotFoundException) {
2785 // throw (ClassNotFoundException) e;
2787 // throw new RuntimeException(e);
2794 // If the deserialized object has a SimpleTimeZone, try to
2795 // replace it with a ZoneInfo equivalent (as of 1.4) in order
2796 // to be compatible with the SimpleTimeZone-based
2797 // implementation as much as possible.
2798 if (zone instanceof SimpleTimeZone) {
2799 String id = zone.getID();
2800 TimeZone tz = TimeZone.getTimeZone(id);
2801 if (tz != null && tz.hasSameRules(zone) && tz.getID().equals(id)) {