1 /*
2 * Copyright 1996-2007 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
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. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun in the LICENSE file that accompanied this code.
10 *
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).
16 *
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.
20 *
21 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
25
26 /*
27 * (C) Copyright Taligent, Inc. 1996-1998 - All Rights Reserved
28 * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
29 *
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.
36 *
37 */
38
39 package java.util;
40
41 import java.io.IOException;
42 import java.io.ObjectInputStream;
43 import java.io.ObjectOutputStream;
44 import java.io.Serializable;
45 import java.security.AccessController;
46 import java.security.PrivilegedExceptionAction;
47 import java.text.DateFormat;
48 import java.text.DateFormatSymbols;
49 import sun.util.BuddhistCalendar;
50 import sun.util.calendar.ZoneInfo;
51 import sun.util.resources.LocaleData;
52
53 /**
54 * The <code>Calendar</code> class is an abstract class that provides methods
55 * for converting between a specific instant in time and a set of {@link
56 * #fields calendar fields} such as <code>YEAR</code>, <code>MONTH</code>,
57 * <code>DAY_OF_MONTH</code>, <code>HOUR</code>, and so on, and for
58 * manipulating the calendar fields, such as getting the date of the next
59 * week. An instant in time can be represented by a millisecond value that is
60 * an offset from the <a name="Epoch"><em>Epoch</em></a>, January 1, 1970
61 * 00:00:00.000 GMT (Gregorian).
62 *
63 * <p>The class also provides additional fields and methods for
64 * implementing a concrete calendar system outside the package. Those
65 * fields and methods are defined as <code>protected</code>.
66 *
67 * <p>
68 * Like other locale-sensitive classes, <code>Calendar</code> provides a
69 * class method, <code>getInstance</code>, for getting a generally useful
70 * object of this type. <code>Calendar</code>'s <code>getInstance</code> method
71 * returns a <code>Calendar</code> object whose
72 * calendar fields have been initialized with the current date and time:
73 * <blockquote>
74 * <pre>
75 * Calendar rightNow = Calendar.getInstance();
76 * </pre>
77 * </blockquote>
78 *
79 * <p>A <code>Calendar</code> object can produce all the calendar field values
80 * needed to implement the date-time formatting for a particular language and
81 * calendar style (for example, Japanese-Gregorian, Japanese-Traditional).
82 * <code>Calendar</code> defines the range of values returned by
83 * certain calendar fields, as well as their meaning. For example,
84 * the first month of the calendar system has value <code>MONTH ==
85 * JANUARY</code> for all calendars. Other values are defined by the
86 * concrete subclass, such as <code>ERA</code>. See individual field
87 * documentation and subclass documentation for details.
88 *
89 * <h4>Getting and Setting Calendar Field Values</h4>
90 *
91 * <p>The calendar field values can be set by calling the <code>set</code>
92 * methods. Any field values set in a <code>Calendar</code> will not be
93 * interpreted until it needs to calculate its time value (milliseconds from
94 * the Epoch) or values of the calendar fields. Calling the
95 * <code>get</code>, <code>getTimeInMillis</code>, <code>getTime</code>,
96 * <code>add</code> and <code>roll</code> involves such calculation.
97 *
98 * <h4>Leniency</h4>
99 *
100 * <p><code>Calendar</code> has two modes for interpreting the calendar
101 * fields, <em>lenient</em> and <em>non-lenient</em>. When a
102 * <code>Calendar</code> is in lenient mode, it accepts a wider range of
103 * calendar field values than it produces. When a <code>Calendar</code>
104 * recomputes calendar field values for return by <code>get()</code>, all of
105 * the calendar fields are normalized. For example, a lenient
106 * <code>GregorianCalendar</code> interprets <code>MONTH == JANUARY</code>,
107 * <code>DAY_OF_MONTH == 32</code> as February 1.
108
109 * <p>When a <code>Calendar</code> is in non-lenient mode, it throws an
110 * exception if there is any inconsistency in its calendar fields. For
111 * example, a <code>GregorianCalendar</code> always produces
112 * <code>DAY_OF_MONTH</code> values between 1 and the length of the month. A
113 * non-lenient <code>GregorianCalendar</code> throws an exception upon
114 * calculating its time or calendar field values if any out-of-range field
115 * value has been set.
116 *
117 * <h4>First Week</h4>
118 *
119 * <code>Calendar</code> defines a locale-specific seven day week using two
120 * parameters: the first day of the week and the minimal days in first week
121 * (from 1 to 7). These numbers are taken from the locale resource data when a
122 * <code>Calendar</code> is constructed. They may also be specified explicitly
123 * through the methods for setting their values.
124 *
125 * <p>When setting or getting the <code>WEEK_OF_MONTH</code> or
126 * <code>WEEK_OF_YEAR</code> fields, <code>Calendar</code> must determine the
127 * first week of the month or year as a reference point. The first week of a
128 * month or year is defined as the earliest seven day period beginning on
129 * <code>getFirstDayOfWeek()</code> and containing at least
130 * <code>getMinimalDaysInFirstWeek()</code> days of that month or year. Weeks
131 * numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow
132 * it. Note that the normalized numbering returned by <code>get()</code> may be
133 * different. For example, a specific <code>Calendar</code> subclass may
134 * designate the week before week 1 of a year as week <code><i>n</i></code> of
135 * the previous year.
136 *
137 * <h4>Calendar Fields Resolution</h4>
138 *
139 * When computing a date and time from the calendar fields, there
140 * may be insufficient information for the computation (such as only
141 * year and month with no day of month), or there may be inconsistent
142 * information (such as Tuesday, July 15, 1996 (Gregorian) -- July 15,
143 * 1996 is actually a Monday). <code>Calendar</code> will resolve
144 * calendar field values to determine the date and time in the
145 * following way.
146 *
147 * <p>If there is any conflict in calendar field values,
148 * <code>Calendar</code> gives priorities to calendar fields that have been set
149 * more recently. The following are the default combinations of the
150 * calendar fields. The most recent combination, as determined by the
151 * most recently set single field, will be used.
152 *
153 * <p><a name="date_resolution">For the date fields</a>:
154 * <blockquote>
155 * <pre>
156 * YEAR + MONTH + DAY_OF_MONTH
157 * YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
158 * YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
159 * YEAR + DAY_OF_YEAR
160 * YEAR + DAY_OF_WEEK + WEEK_OF_YEAR
161 * </pre></blockquote>
162 *
163 * <a name="time_resolution">For the time of day fields</a>:
164 * <blockquote>
165 * <pre>
166 * HOUR_OF_DAY
167 * AM_PM + HOUR
168 * </pre></blockquote>
169 *
170 * <p>If there are any calendar fields whose values haven't been set in the selected
171 * field combination, <code>Calendar</code> uses their default values. The default
172 * value of each field may vary by concrete calendar systems. For example, in
173 * <code>GregorianCalendar</code>, the default of a field is the same as that
174 * of the start of the Epoch: i.e., <code>YEAR = 1970</code>, <code>MONTH =
175 * JANUARY</code>, <code>DAY_OF_MONTH = 1</code>, etc.
176 *
177 * <p>
178 * <strong>Note:</strong> There are certain possible ambiguities in
179 * interpretation of certain singular times, which are resolved in the
180 * following ways:
181 * <ol>
182 * <li> 23:59 is the last minute of the day and 00:00 is the first
183 * minute of the next day. Thus, 23:59 on Dec 31, 1999 < 00:00 on
184 * Jan 1, 2000 < 00:01 on Jan 1, 2000.
185 *
186 * <li> Although historically not precise, midnight also belongs to "am",
187 * and noon belongs to "pm", so on the same day,
188 * 12:00 am (midnight) < 12:01 am, and 12:00 pm (noon) < 12:01 pm
189 * </ol>
190 *
191 * <p>
192 * The date or time format strings are not part of the definition of a
193 * calendar, as those must be modifiable or overridable by the user at
194 * runtime. Use {@link DateFormat}
195 * to format dates.
196 *
197 * <h4>Field Manipulation</h4>
198 *
199 * The calendar fields can be changed using three methods:
200 * <code>set()</code>, <code>add()</code>, and <code>roll()</code>.</p>
201 *
202 * <p><strong><code>set(f, value)</code></strong> changes calendar field
203 * <code>f</code> to <code>value</code>. In addition, it sets an
204 * internal member variable to indicate that calendar field <code>f</code> has
205 * been changed. Although calendar field <code>f</code> is changed immediately,
206 * the calendar's time value in milliseconds is not recomputed until the next call to
207 * <code>get()</code>, <code>getTime()</code>, <code>getTimeInMillis()</code>,
208 * <code>add()</code>, or <code>roll()</code> is made. Thus, multiple calls to
209 * <code>set()</code> do not trigger multiple, unnecessary
210 * computations. As a result of changing a calendar field using
211 * <code>set()</code>, other calendar fields may also change, depending on the
212 * calendar field, the calendar field value, and the calendar system. In addition,
213 * <code>get(f)</code> will not necessarily return <code>value</code> set by
214 * the call to the <code>set</code> method
215 * after the calendar fields have been recomputed. The specifics are determined by
216 * the concrete calendar class.</p>
217 *
218 * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
219 * originally set to August 31, 1999. Calling <code>set(Calendar.MONTH,
220 * Calendar.SEPTEMBER)</code> sets the date to September 31,
221 * 1999. This is a temporary internal representation that resolves to
222 * October 1, 1999 if <code>getTime()</code>is then called. However, a
223 * call to <code>set(Calendar.DAY_OF_MONTH, 30)</code> before the call to
224 * <code>getTime()</code> sets the date to September 30, 1999, since
225 * no recomputation occurs after <code>set()</code> itself.</p>
226 *
227 * <p><strong><code>add(f, delta)</code></strong> adds <code>delta</code>
228 * to field <code>f</code>. This is equivalent to calling <code>set(f,
229 * get(f) + delta)</code> with two adjustments:</p>
230 *
231 * <blockquote>
232 * <p><strong>Add rule 1</strong>. The value of field <code>f</code>
233 * after the call minus the value of field <code>f</code> before the
234 * call is <code>delta</code>, modulo any overflow that has occurred in
235 * field <code>f</code>. Overflow occurs when a field value exceeds its
236 * range and, as a result, the next larger field is incremented or
237 * decremented and the field value is adjusted back into its range.</p>
238 *
239 * <p><strong>Add rule 2</strong>. If a smaller field is expected to be
240 * invariant, but it is impossible for it to be equal to its
241 * prior value because of changes in its minimum or maximum after field
242 * <code>f</code> is changed or other constraints, such as time zone
243 * offset changes, then its value is adjusted to be as close
244 * as possible to its expected value. A smaller field represents a
245 * smaller unit of time. <code>HOUR</code> is a smaller field than
246 * <code>DAY_OF_MONTH</code>. No adjustment is made to smaller fields
247 * that are not expected to be invariant. The calendar system
248 * determines what fields are expected to be invariant.</p>
249 * </blockquote>
250 *
251 * <p>In addition, unlike <code>set()</code>, <code>add()</code> forces
252 * an immediate recomputation of the calendar's milliseconds and all
253 * fields.</p>
254 *
255 * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
256 * originally set to August 31, 1999. Calling <code>add(Calendar.MONTH,
257 * 13)</code> sets the calendar to September 30, 2000. <strong>Add rule
258 * 1</strong> sets the <code>MONTH</code> field to September, since
259 * adding 13 months to August gives September of the next year. Since
260 * <code>DAY_OF_MONTH</code> cannot be 31 in September in a
261 * <code>GregorianCalendar</code>, <strong>add rule 2</strong> sets the
262 * <code>DAY_OF_MONTH</code> to 30, the closest possible value. Although
263 * it is a smaller field, <code>DAY_OF_WEEK</code> is not adjusted by
264 * rule 2, since it is expected to change when the month changes in a
265 * <code>GregorianCalendar</code>.</p>
266 *
267 * <p><strong><code>roll(f, delta)</code></strong> adds
268 * <code>delta</code> to field <code>f</code> without changing larger
269 * fields. This is equivalent to calling <code>add(f, delta)</code> with
270 * the following adjustment:</p>
271 *
272 * <blockquote>
273 * <p><strong>Roll rule</strong>. Larger fields are unchanged after the
274 * call. A larger field represents a larger unit of
275 * time. <code>DAY_OF_MONTH</code> is a larger field than
276 * <code>HOUR</code>.</p>
277 * </blockquote>
278 *
279 * <p><em>Example</em>: See {@link java.util.GregorianCalendar#roll(int, int)}.
280 *
281 * <p><strong>Usage model</strong>. To motivate the behavior of
282 * <code>add()</code> and <code>roll()</code>, consider a user interface
283 * component with increment and decrement buttons for the month, day, and
284 * year, and an underlying <code>GregorianCalendar</code>. If the
285 * interface reads January 31, 1999 and the user presses the month
286 * increment button, what should it read? If the underlying
287 * implementation uses <code>set()</code>, it might read March 3, 1999. A
288 * better result would be February 28, 1999. Furthermore, if the user
289 * presses the month increment button again, it should read March 31,
290 * 1999, not March 28, 1999. By saving the original date and using either
291 * <code>add()</code> or <code>roll()</code>, depending on whether larger
292 * fields should be affected, the user interface can behave as most users
293 * will intuitively expect.</p>
294 *
295 * @see java.lang.System#currentTimeMillis()
296 * @see Date
297 * @see GregorianCalendar
298 * @see TimeZone
299 * @see java.text.DateFormat
300 * @author Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu
301 * @since JDK1.1
302 */
303 public abstract class Calendar implements Serializable, Cloneable, Comparable<Calendar> {
304
305 // Data flow in Calendar
306 // ---------------------
307
308 // The current time is represented in two ways by Calendar: as UTC
309 // milliseconds from the epoch (1 January 1970 0:00 UTC), and as local
310 // fields such as MONTH, HOUR, AM_PM, etc. It is possible to compute the
311 // millis from the fields, and vice versa. The data needed to do this
312 // conversion is encapsulated by a TimeZone object owned by the Calendar.
313 // The data provided by the TimeZone object may also be overridden if the
314 // user sets the ZONE_OFFSET and/or DST_OFFSET fields directly. The class
315 // keeps track of what information was most recently set by the caller, and
316 // uses that to compute any other information as needed.
317
318 // If the user sets the fields using set(), the data flow is as follows.
319 // This is implemented by the Calendar subclass's computeTime() method.
320 // During this process, certain fields may be ignored. The disambiguation
321 // algorithm for resolving which fields to pay attention to is described
322 // in the class documentation.
323
324 // local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
325 // |
326 // | Using Calendar-specific algorithm
327 // V
328 // local standard millis
329 // |
330 // | Using TimeZone or user-set ZONE_OFFSET / DST_OFFSET
331 // V
332 // UTC millis (in time data member)
333
334 // If the user sets the UTC millis using setTime() or setTimeInMillis(),
335 // the data flow is as follows. This is implemented by the Calendar
336 // subclass's computeFields() method.
337
338 // UTC millis (in time data member)
339 // |
340 // | Using TimeZone getOffset()
341 // V
342 // local standard millis
343 // |
344 // | Using Calendar-specific algorithm
345 // V
346 // local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
347
348 // In general, a round trip from fields, through local and UTC millis, and
349 // back out to fields is made when necessary. This is implemented by the
350 // complete() method. Resolving a partial set of fields into a UTC millis
351 // value allows all remaining fields to be generated from that value. If
352 // the Calendar is lenient, the fields are also renormalized to standard
353 // ranges when they are regenerated.
354
355 /**
356 * Field number for <code>get</code> and <code>set</code> indicating the
357 * era, e.g., AD or BC in the Julian calendar. This is a calendar-specific
358 * value; see subclass documentation.
359 *
360 * @see GregorianCalendar#AD
361 * @see GregorianCalendar#BC
362 */
363 public final static int ERA = 0;
364
365 /**
366 * Field number for <code>get</code> and <code>set</code> indicating the
367 * year. This is a calendar-specific value; see subclass documentation.
368 */
369 public final static int YEAR = 1;
370
371 /**
372 * Field number for <code>get</code> and <code>set</code> indicating the
373 * month. This is a calendar-specific value. The first month of
374 * the year in the Gregorian and Julian calendars is
375 * <code>JANUARY</code> which is 0; the last depends on the number
376 * of months in a year.
377 *
378 * @see #JANUARY
379 * @see #FEBRUARY
380 * @see #MARCH
381 * @see #APRIL
382 * @see #MAY
383 * @see #JUNE
384 * @see #JULY
385 * @see #AUGUST
386 * @see #SEPTEMBER
387 * @see #OCTOBER
388 * @see #NOVEMBER
389 * @see #DECEMBER
390 * @see #UNDECIMBER
391 */
392 public final static int MONTH = 2;
393
394 /**
395 * Field number for <code>get</code> and <code>set</code> indicating the
396 * week number within the current year. The first week of the year, as
397 * defined by <code>getFirstDayOfWeek()</code> and
398 * <code>getMinimalDaysInFirstWeek()</code>, has value 1. Subclasses define
399 * the value of <code>WEEK_OF_YEAR</code> for days before the first week of
400 * the year.
401 *
402 * @see #getFirstDayOfWeek
403 * @see #getMinimalDaysInFirstWeek
404 */
405 public final static int WEEK_OF_YEAR = 3;
406
407 /**
408 * Field number for <code>get</code> and <code>set</code> indicating the
409 * week number within the current month. The first week of the month, as
410 * defined by <code>getFirstDayOfWeek()</code> and
411 * <code>getMinimalDaysInFirstWeek()</code>, has value 1. Subclasses define
412 * the value of <code>WEEK_OF_MONTH</code> for days before the first week of
413 * the month.
414 *
415 * @see #getFirstDayOfWeek
416 * @see #getMinimalDaysInFirstWeek
417 */
418 public final static int WEEK_OF_MONTH = 4;
419
420 /**
421 * Field number for <code>get</code> and <code>set</code> indicating the
422 * day of the month. This is a synonym for <code>DAY_OF_MONTH</code>.
423 * The first day of the month has value 1.
424 *
425 * @see #DAY_OF_MONTH
426 */
427 public final static int DATE = 5;
428
429 /**
430 * Field number for <code>get</code> and <code>set</code> indicating the
431 * day of the month. This is a synonym for <code>DATE</code>.
432 * The first day of the month has value 1.
433 *
434 * @see #DATE
435 */
436 public final static int DAY_OF_MONTH = 5;
437
438 /**
439 * Field number for <code>get</code> and <code>set</code> indicating the day
440 * number within the current year. The first day of the year has value 1.
441 */
442 public final static int DAY_OF_YEAR = 6;
443
444 /**
445 * Field number for <code>get</code> and <code>set</code> indicating the day
446 * of the week. This field takes values <code>SUNDAY</code>,
447 * <code>MONDAY</code>, <code>TUESDAY</code>, <code>WEDNESDAY</code>,
448 * <code>THURSDAY</code>, <code>FRIDAY</code>, and <code>SATURDAY</code>.
449 *
450 * @see #SUNDAY
451 * @see #MONDAY
452 * @see #TUESDAY
453 * @see #WEDNESDAY
454 * @see #THURSDAY
455 * @see #FRIDAY
456 * @see #SATURDAY
457 */
458 public final static int DAY_OF_WEEK = 7;
459
460 /**
461 * Field number for <code>get</code> and <code>set</code> indicating the
462 * ordinal number of the day of the week within the current month. Together
463 * with the <code>DAY_OF_WEEK</code> field, this uniquely specifies a day
464 * within a month. Unlike <code>WEEK_OF_MONTH</code> and
465 * <code>WEEK_OF_YEAR</code>, this field's value does <em>not</em> depend on
466 * <code>getFirstDayOfWeek()</code> or
467 * <code>getMinimalDaysInFirstWeek()</code>. <code>DAY_OF_MONTH 1</code>
468 * through <code>7</code> always correspond to <code>DAY_OF_WEEK_IN_MONTH
469 * 1</code>; <code>8</code> through <code>14</code> correspond to
470 * <code>DAY_OF_WEEK_IN_MONTH 2</code>, and so on.
471 * <code>DAY_OF_WEEK_IN_MONTH 0</code> indicates the week before
472 * <code>DAY_OF_WEEK_IN_MONTH 1</code>. Negative values count back from the
473 * end of the month, so the last Sunday of a month is specified as
474 * <code>DAY_OF_WEEK = SUNDAY, DAY_OF_WEEK_IN_MONTH = -1</code>. Because
475 * negative values count backward they will usually be aligned differently
476 * within the month than positive values. For example, if a month has 31
477 * days, <code>DAY_OF_WEEK_IN_MONTH -1</code> will overlap
478 * <code>DAY_OF_WEEK_IN_MONTH 5</code> and the end of <code>4</code>.
479 *
480 * @see #DAY_OF_WEEK
481 * @see #WEEK_OF_MONTH
482 */
483 public final static int DAY_OF_WEEK_IN_MONTH = 8;
484
485 /**
486 * Field number for <code>get</code> and <code>set</code> indicating
487 * whether the <code>HOUR</code> is before or after noon.
488 * E.g., at 10:04:15.250 PM the <code>AM_PM</code> is <code>PM</code>.
489 *
490 * @see #AM
491 * @see #PM
492 * @see #HOUR
493 */
494 public final static int AM_PM = 9;
495
496 /**
497 * Field number for <code>get</code> and <code>set</code> indicating the
498 * hour of the morning or afternoon. <code>HOUR</code> is used for the
499 * 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12.
500 * E.g., at 10:04:15.250 PM the <code>HOUR</code> is 10.
501 *
502 * @see #AM_PM
503 * @see #HOUR_OF_DAY
504 */
505 public final static int HOUR = 10;
506
507 /**
508 * Field number for <code>get</code> and <code>set</code> indicating the
509 * hour of the day. <code>HOUR_OF_DAY</code> is used for the 24-hour clock.
510 * E.g., at 10:04:15.250 PM the <code>HOUR_OF_DAY</code> is 22.
511 *
512 * @see #HOUR
513 */
514 public final static int HOUR_OF_DAY = 11;
515
516 /**
517 * Field number for <code>get</code> and <code>set</code> indicating the
518 * minute within the hour.
519 * E.g., at 10:04:15.250 PM the <code>MINUTE</code> is 4.
520 */
521 public final static int MINUTE = 12;
522
523 /**
524 * Field number for <code>get</code> and <code>set</code> indicating the
525 * second within the minute.
526 * E.g., at 10:04:15.250 PM the <code>SECOND</code> is 15.
527 */
528 public final static int SECOND = 13;
529
530 /**
531 * Field number for <code>get</code> and <code>set</code> indicating the
532 * millisecond within the second.
533 * E.g., at 10:04:15.250 PM the <code>MILLISECOND</code> is 250.
534 */
535 public final static int MILLISECOND = 14;
536
537 /**
538 * Field number for <code>get</code> and <code>set</code>
539 * indicating the raw offset from GMT in milliseconds.
540 * <p>
541 * This field reflects the correct GMT offset value of the time
542 * zone of this <code>Calendar</code> if the
543 * <code>TimeZone</code> implementation subclass supports
544 * historical GMT offset changes.
545 */
546 public final static int ZONE_OFFSET = 15;
547
548 /**
549 * Field number for <code>get</code> and <code>set</code> indicating the
550 * daylight savings offset in milliseconds.
551 * <p>
552 * This field reflects the correct daylight saving offset value of
553 * the time zone of this <code>Calendar</code> if the
554 * <code>TimeZone</code> implementation subclass supports
555 * historical Daylight Saving Time schedule changes.
556 */
557 public final static int DST_OFFSET = 16;
558
559 /**
560 * The number of distinct fields recognized by <code>get</code> and <code>set</code>.
561 * Field numbers range from <code>0..FIELD_COUNT-1</code>.
562 */
563 public final static int FIELD_COUNT = 17;
564
565 /**
566 * Value of the {@link #DAY_OF_WEEK} field indicating
567 * Sunday.
568 */
569 public final static int SUNDAY = 1;
570
571 /**
572 * Value of the {@link #DAY_OF_WEEK} field indicating
573 * Monday.
574 */
575 public final static int MONDAY = 2;
576
577 /**
578 * Value of the {@link #DAY_OF_WEEK} field indicating
579 * Tuesday.
580 */
581 public final static int TUESDAY = 3;
582
583 /**
584 * Value of the {@link #DAY_OF_WEEK} field indicating
585 * Wednesday.
586 */
587 public final static int WEDNESDAY = 4;
588
589 /**
590 * Value of the {@link #DAY_OF_WEEK} field indicating
591 * Thursday.
592 */
593 public final static int THURSDAY = 5;
594
595 /**
596 * Value of the {@link #DAY_OF_WEEK} field indicating
597 * Friday.
598 */
599 public final static int FRIDAY = 6;
600
601 /**
602 * Value of the {@link #DAY_OF_WEEK} field indicating
603 * Saturday.
604 */
605 public final static int SATURDAY = 7;
606
607 /**
608 * Value of the {@link #MONTH} field indicating the
609 * first month of the year in the Gregorian and Julian calendars.
610 */
611 public final static int JANUARY = 0;
612
613 /**
614 * Value of the {@link #MONTH} field indicating the
615 * second month of the year in the Gregorian and Julian calendars.
616 */
617 public final static int FEBRUARY = 1;
618
619 /**
620 * Value of the {@link #MONTH} field indicating the
621 * third month of the year in the Gregorian and Julian calendars.
622 */
623 public final static int MARCH = 2;
624
625 /**
626 * Value of the {@link #MONTH} field indicating the
627 * fourth month of the year in the Gregorian and Julian calendars.
628 */
629 public final static int APRIL = 3;
630
631 /**
632 * Value of the {@link #MONTH} field indicating the
633 * fifth month of the year in the Gregorian and Julian calendars.
634 */
635 public final static int MAY = 4;
636
637 /**
638 * Value of the {@link #MONTH} field indicating the
639 * sixth month of the year in the Gregorian and Julian calendars.
640 */
641 public final static int JUNE = 5;
642
643 /**
644 * Value of the {@link #MONTH} field indicating the
645 * seventh month of the year in the Gregorian and Julian calendars.
646 */
647 public final static int JULY = 6;
648
649 /**
650 * Value of the {@link #MONTH} field indicating the
651 * eighth month of the year in the Gregorian and Julian calendars.
652 */
653 public final static int AUGUST = 7;
654
655 /**
656 * Value of the {@link #MONTH} field indicating the
657 * ninth month of the year in the Gregorian and Julian calendars.
658 */
659 public final static int SEPTEMBER = 8;
660
661 /**
662 * Value of the {@link #MONTH} field indicating the
663 * tenth month of the year in the Gregorian and Julian calendars.
664 */
665 public final static int OCTOBER = 9;
666
667 /**
668 * Value of the {@link #MONTH} field indicating the
669 * eleventh month of the year in the Gregorian and Julian calendars.
670 */
671 public final static int NOVEMBER = 10;
672
673 /**
674 * Value of the {@link #MONTH} field indicating the
675 * twelfth month of the year in the Gregorian and Julian calendars.
676 */
677 public final static int DECEMBER = 11;
678
679 /**
680 * Value of the {@link #MONTH} field indicating the
681 * thirteenth month of the year. Although <code>GregorianCalendar</code>
682 * does not use this value, lunar calendars do.
683 */
684 public final static int UNDECIMBER = 12;
685
686 /**
687 * Value of the {@link #AM_PM} field indicating the
688 * period of the day from midnight to just before noon.
689 */
690 public final static int AM = 0;
691
692 /**
693 * Value of the {@link #AM_PM} field indicating the
694 * period of the day from noon to just before midnight.
695 */
696 public final static int PM = 1;
697
698 /**
699 * A style specifier for {@link #getDisplayNames(int, int, Locale)
700 * getDisplayNames} indicating names in all styles, such as
701 * "January" and "Jan".
702 *
703 * @see #SHORT
704 * @see #LONG
705 * @since 1.6
706 */
707 public static final int ALL_STYLES = 0;
708
709 /**
710 * A style specifier for {@link #getDisplayName(int, int, Locale)
711 * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
712 * getDisplayNames} indicating a short name, such as "Jan".
713 *
714 * @see #LONG
715 * @since 1.6
716 */
717 public static final int SHORT = 1;
718
719 /**
720 * A style specifier for {@link #getDisplayName(int, int, Locale)
721 * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
722 * getDisplayNames} indicating a long name, such as "January".
723 *
724 * @see #SHORT
725 * @since 1.6
726 */
727 public static final int LONG = 2;
728
729 // Internal notes:
730 // Calendar contains two kinds of time representations: current "time" in
731 // milliseconds, and a set of calendar "fields" representing the current time.
732 // The two representations are usually in sync, but can get out of sync
733 // as follows.
734 // 1. Initially, no fields are set, and the time is invalid.
735 // 2. If the time is set, all fields are computed and in sync.
736 // 3. If a single field is set, the time is invalid.
737 // Recomputation of the time and fields happens when the object needs
738 // to return a result to the user, or use a result for a computation.
739
740 /**
741 * The calendar field values for the currently set time for this calendar.
742 * This is an array of <code>FIELD_COUNT</code> integers, with index values
743 * <code>ERA</code> through <code>DST_OFFSET</code>.
744 * @serial
745 */
746 protected int fields[];
747
748 /**
749 * The flags which tell if a specified calendar field for the calendar is set.
750 * A new object has no fields set. After the first call to a method
751 * which generates the fields, they all remain set after that.
752 * This is an array of <code>FIELD_COUNT</code> booleans, with index values
753 * <code>ERA</code> through <code>DST_OFFSET</code>.
754 * @serial
755 */
756 protected boolean isSet[];
757
758 /**
759 * Pseudo-time-stamps which specify when each field was set. There
760 * are two special values, UNSET and COMPUTED. Values from
761 * MINIMUM_USER_SET to Integer.MAX_VALUE are legal user set values.
762 */
763 transient private int stamp[];
764
765 /**
766 * The currently set time for this calendar, expressed in milliseconds after
767 * January 1, 1970, 0:00:00 GMT.
768 * @see #isTimeSet
769 * @serial
770 */
771 protected long time;
772
773 /**
774 * True if then the value of <code>time</code> is valid.
775 * The time is made invalid by a change to an item of <code>field[]</code>.
776 * @see #time
777 * @serial
778 */
779 protected boolean isTimeSet;
780
781 /**
782 * True if <code>fields[]</code> are in sync with the currently set time.
783 * If false, then the next attempt to get the value of a field will
784 * force a recomputation of all fields from the current value of
785 * <code>time</code>.
786 * @serial
787 */
788 protected boolean areFieldsSet;
789
790 /**
791 * True if all fields have been set.
792 * @serial
793 */
794 transient boolean areAllFieldsSet;
795
796 /**
797 * <code>True</code> if this calendar allows out-of-range field values during computation
798 * of <code>time</code> from <code>fields[]</code>.
799 * @see #setLenient
800 * @see #isLenient
801 * @serial
802 */
803 private boolean lenient = true;
804
805 /**
806 * The <code>TimeZone</code> used by this calendar. <code>Calendar</code>
807 * uses the time zone data to translate between locale and GMT time.
808 * @serial
809 */
810 private TimeZone zone;
811
812 /**
813 * <code>True</code> if zone references to a shared TimeZone object.
814 */
815 transient private boolean sharedZone = false;
816
817 /**
818 * The first day of the week, with possible values <code>SUNDAY</code>,
819 * <code>MONDAY</code>, etc. This is a locale-dependent value.
820 * @serial
821 */
822 private int firstDayOfWeek;
823
824 /**
825 * The number of days required for the first week in a month or year,
826 * with possible values from 1 to 7. This is a locale-dependent value.
827 * @serial
828 */
829 private int minimalDaysInFirstWeek;
830
831 /**
832 * Cache to hold the firstDayOfWeek and minimalDaysInFirstWeek
833 * of a Locale.
834 */
835 private static Hashtable<Locale, int[]> cachedLocaleData = new Hashtable<Locale, int[]>(3);
836
837 // Special values of stamp[]
838 /**
839 * The corresponding fields[] has no value.
840 */
841 private static final int UNSET = 0;
842
843 /**
844 * The value of the corresponding fields[] has been calculated internally.
845 */
846 private static final int COMPUTED = 1;
847
848 /**
849 * The value of the corresponding fields[] has been set externally. Stamp
850 * values which are greater than 1 represents the (pseudo) time when the
851 * corresponding fields[] value was set.
852 */
853 private static final int MINIMUM_USER_STAMP = 2;
854
855 /**
856 * The mask value that represents all of the fields.
857 */
858 static final int ALL_FIELDS = (1 << FIELD_COUNT) - 1;
859
860 /**
861 * The next available value for <code>stamp[]</code>, an internal array.
862 * This actually should not be written out to the stream, and will probably
863 * be removed from the stream in the near future. In the meantime,
864 * a value of <code>MINIMUM_USER_STAMP</code> should be used.
865 * @serial
866 */
867 private int nextStamp = MINIMUM_USER_STAMP;
868
869 // the internal serial version which says which version was written
870 // - 0 (default) for version up to JDK 1.1.5
871 // - 1 for version from JDK 1.1.6, which writes a correct 'time' value
872 // as well as compatible values for other fields. This is a
873 // transitional format.
874 // - 2 (not implemented yet) a future version, in which fields[],
875 // areFieldsSet, and isTimeSet become transient, and isSet[] is
876 // removed. In JDK 1.1.6 we write a format compatible with version 2.
877 static final int currentSerialVersion = 1;
878
879 /**
880 * The version of the serialized data on the stream. Possible values:
881 * <dl>
882 * <dt><b>0</b> or not present on stream</dt>
883 * <dd>
884 * JDK 1.1.5 or earlier.
885 * </dd>
886 * <dt><b>1</b></dt>
887 * <dd>
888 * JDK 1.1.6 or later. Writes a correct 'time' value
889 * as well as compatible values for other fields. This is a
890 * transitional format.
891 * </dd>
892 * </dl>
893 * When streaming out this class, the most recent format
894 * and the highest allowable <code>serialVersionOnStream</code>
895 * is written.
896 * @serial
897 * @since JDK1.1.6
898 */
899 private int serialVersionOnStream = currentSerialVersion;
900
901 // Proclaim serialization compatibility with JDK 1.1
902 static final long serialVersionUID = -1807547505821590642L;
903
904 // Mask values for calendar fields
905 final static int ERA_MASK = (1 << ERA);
906 final static int YEAR_MASK = (1 << YEAR);
907 final static int MONTH_MASK = (1 << MONTH);
908 final static int WEEK_OF_YEAR_MASK = (1 << WEEK_OF_YEAR);
909 final static int WEEK_OF_MONTH_MASK = (1 << WEEK_OF_MONTH);
910 final static int DAY_OF_MONTH_MASK = (1 << DAY_OF_MONTH);
911 final static int DATE_MASK = DAY_OF_MONTH_MASK;
912 final static int DAY_OF_YEAR_MASK = (1 << DAY_OF_YEAR);
913 final static int DAY_OF_WEEK_MASK = (1 << DAY_OF_WEEK);
914 final static int DAY_OF_WEEK_IN_MONTH_MASK = (1 << DAY_OF_WEEK_IN_MONTH);
915 final static int AM_PM_MASK = (1 << AM_PM);
916 final static int HOUR_MASK = (1 << HOUR);
917 final static int HOUR_OF_DAY_MASK = (1 << HOUR_OF_DAY);
918 final static int MINUTE_MASK = (1 << MINUTE);
919 final static int SECOND_MASK = (1 << SECOND);
920 final static int MILLISECOND_MASK = (1 << MILLISECOND);
921 final static int ZONE_OFFSET_MASK = (1 << ZONE_OFFSET);
922 final static int DST_OFFSET_MASK = (1 << DST_OFFSET);
923
924 /**
925 * Constructs a Calendar with the default time zone
926 * and locale.
927 * @see TimeZone#getDefault
928 */
929 protected Calendar()
930 {
931 this(TimeZone.getDefaultRef(), Locale.getDefault());
932 sharedZone = true;
933 }
934
935 /**
936 * Constructs a calendar with the specified time zone and locale.
937 *
938 * @param zone the time zone to use
939 * @param aLocale the locale for the week data
940 */
941 protected Calendar(TimeZone zone, Locale aLocale)
942 {
943 fields = new int[FIELD_COUNT];
944 isSet = new boolean[FIELD_COUNT];
945 stamp = new int[FIELD_COUNT];
946
947 this.zone = zone;
948 setWeekCountData(aLocale);
949 }
950
951 /**
952 * Gets a calendar using the default time zone and locale. The
953 * <code>Calendar</code> returned is based on the current time
954 * in the default time zone with the default locale.
955 *
956 * @return a Calendar.
957 */
958 public static Calendar getInstance()
959 {
960 Calendar cal = createCalendar(TimeZone.getDefaultRef(), Locale.getDefault());
961 cal.sharedZone = true;
962 return cal;
963 }
964
965 /**
966 * Gets a calendar using the specified time zone and default locale.
967 * The <code>Calendar</code> returned is based on the current time
968 * in the given time zone with the default locale.
969 *
970 * @param zone the time zone to use
971 * @return a Calendar.
972 */
973 public static Calendar getInstance(TimeZone zone)
974 {
975 return createCalendar(zone, Locale.getDefault());
976 }
977
978 /**
979 * Gets a calendar using the default time zone and specified locale.
980 * The <code>Calendar</code> returned is based on the current time
981 * in the default time zone with the given locale.
982 *
983 * @param aLocale the locale for the week data
984 * @return a Calendar.
985 */
986 public static Calendar getInstance(Locale aLocale)
987 {
988 Calendar cal = createCalendar(TimeZone.getDefaultRef(), aLocale);
989 cal.sharedZone = true;
990 return cal;
991 }
992
993 /**
994 * Gets a calendar with the specified time zone and locale.
995 * The <code>Calendar</code> returned is based on the current time
996 * in the given time zone with the given locale.
997 *
998 * @param zone the time zone to use
999 * @param aLocale the locale for the week data
1000 * @return a Calendar.
1001 */
1002 public static Calendar getInstance(TimeZone zone,
1003 Locale aLocale)
1004 {
1005 return createCalendar(zone, aLocale);
1006 }
1007
1008 private static Calendar createCalendar(TimeZone zone,
1009 Locale aLocale)
1010 {
1011 // If the specified locale is a Thai locale, returns a BuddhistCalendar
1012 // instance.
1013 if ("th".equals(aLocale.getLanguage())
1014 && ("TH".equals(aLocale.getCountry()))) {
1015 return new sun.util.BuddhistCalendar(zone, aLocale);
1016 } else if ("JP".equals(aLocale.getVariant())
1017 && "JP".equals(aLocale.getCountry())
1018 && "ja".equals(aLocale.getLanguage())) {
1019 return new JapaneseImperialCalendar(zone, aLocale);
1020 }
1021
1022 // else create the default calendar
1023 return new GregorianCalendar(zone, aLocale);
1024 }
1025
1026 /**
1027 * Returns an array of all locales for which the <code>getInstance</code>
1028 * methods of this class can return localized instances.
1029 * The array returned must contain at least a <code>Locale</code>
1030 * instance equal to {@link java.util.Locale#US Locale.US}.
1031 *
1032 * @return An array of locales for which localized
1033 * <code>Calendar</code> instances are available.
1034 */
1035 public static synchronized Locale[] getAvailableLocales()
1036 {
1037 return DateFormat.getAvailableLocales();
1038 }
1039
1040 /**
1041 * Converts the current calendar field values in {@link #fields fields[]}
1042 * to the millisecond time value
1043 * {@link #time}.
1044 *
1045 * @see #complete()
1046 * @see #computeFields()
1047 */
1048 protected abstract void computeTime();
1049
1050 /**
1051 * Converts the current millisecond time value {@link #time}
1052 * to calendar field values in {@link #fields fields[]}.
1053 * This allows you to sync up the calendar field values with
1054 * a new time that is set for the calendar. The time is <em>not</em>
1055 * recomputed first; to recompute the time, then the fields, call the
1056 * {@link #complete()} method.
1057 *
1058 * @see #computeTime()
1059 */
1060 protected abstract void computeFields();
1061
1062 /**
1063 * Returns a <code>Date</code> object representing this
1064 * <code>Calendar</code>'s time value (millisecond offset from the <a
1065 * href="#Epoch">Epoch</a>").
1066 *
1067 * @return a <code>Date</code> representing the time value.
1068 * @see #setTime(Date)
1069 * @see #getTimeInMillis()
1070 */
1071 public final Date getTime() {
1072 return new Date(getTimeInMillis());
1073 }
1074
1075 /**
1076 * Sets this Calendar's time with the given <code>Date</code>.
1077 * <p>
1078 * Note: Calling <code>setTime()</code> with
1079 * <code>Date(Long.MAX_VALUE)</code> or <code>Date(Long.MIN_VALUE)</code>
1080 * may yield incorrect field values from <code>get()</code>.
1081 *
1082 * @param date the given Date.
1083 * @see #getTime()
1084 * @see #setTimeInMillis(long)
1085 */
1086 public final void setTime(Date date) {
1087 setTimeInMillis(date.getTime());
1088 }
1089
1090 /**
1091 * Returns this Calendar's time value in milliseconds.
1092 *
1093 * @return the current time as UTC milliseconds from the epoch.
1094 * @see #getTime()
1095 * @see #setTimeInMillis(long)
1096 */
1097 public long getTimeInMillis() {
1098 if (!isTimeSet) {
1099 updateTime();
1100 }
1101 return time;
1102 }
1103
1104 /**
1105 * Sets this Calendar's current time from the given long value.
1106 *
1107 * @param millis the new time in UTC milliseconds from the epoch.
1108 * @see #setTime(Date)
1109 * @see #getTimeInMillis()
1110 */
1111 public void setTimeInMillis(long millis) {
1112 // If we don't need to recalculate the calendar field values,
1113 // do nothing.
1114 if (time == millis && isTimeSet && areFieldsSet && areAllFieldsSet
1115 && (zone instanceof ZoneInfo) && !((ZoneInfo)zone).isDirty()) {
1116 return;
1117 }
1118 time = millis;
1119 isTimeSet = true;
1120 areFieldsSet = false;
1121 computeFields();
1122 areAllFieldsSet = areFieldsSet = true;
1123 }
1124
1125 /**
1126 * Returns the value of the given calendar field. In lenient mode,
1127 * all calendar fields are normalized. In non-lenient mode, all
1128 * calendar fields are validated and this method throws an
1129 * exception if any calendar fields have out-of-range values. The
1130 * normalization and validation are handled by the
1131 * {@link #complete()} method, which process is calendar
1132 * system dependent.
1133 *
1134 * @param field the given calendar field.
1135 * @return the value for the given calendar field.
1136 * @throws ArrayIndexOutOfBoundsException if the specified field is out of range
1137 * (<code>field < 0 || field >= FIELD_COUNT</code>).
1138 * @see #set(int,int)
1139 * @see #complete()
1140 */
1141 public int get(int field)
1142 {
1143 complete();
1144 return internalGet(field);
1145 }
1146
1147 /**
1148 * Returns the value of the given calendar field. This method does
1149 * not involve normalization or validation of the field value.
1150 *
1151 * @param field the given calendar field.
1152 * @return the value for the given calendar field.
1153 * @see #get(int)
1154 */
1155 protected final int internalGet(int field)
1156 {
1157 return fields[field];
1158 }
1159
1160 /**
1161 * Sets the value of the given calendar field. This method does
1162 * not affect any setting state of the field in this
1163 * <code>Calendar</code> instance.
1164 *
1165 * @throws IndexOutOfBoundsException if the specified field is out of range
1166 * (<code>field < 0 || field >= FIELD_COUNT</code>).
1167 * @see #areFieldsSet
1168 * @see #isTimeSet
1169 * @see #areAllFieldsSet
1170 * @see #set(int,int)
1171 */
1172 final void internalSet(int field, int value)
1173 {
1174 fields[field] = value;
1175 }
1176
1177 /**
1178 * Sets the given calendar field to the given value. The value is not
1179 * interpreted by this method regardless of the leniency mode.
1180 *
1181 * @param field the given calendar field.
1182 * @param value the value to be set for the given calendar field.
1183 * @throws ArrayIndexOutOfBoundsException if the specified field is out of range
1184 * (<code>field < 0 || field >= FIELD_COUNT</code>).
1185 * in non-lenient mode.
1186 * @see #set(int,int,int)
1187 * @see #set(int,int,int,int,int)
1188 * @see #set(int,int,int,int,int,int)
1189 * @see #get(int)
1190 */
1191 public void set(int field, int value)
1192 {
1193 if (isLenient() && areFieldsSet && !areAllFieldsSet) {
1194 computeFields();
1195 }
1196 internalSet(field, value);
1197 isTimeSet = false;
1198 areFieldsSet = false;
1199 isSet[field] = true;
1200 stamp[field] = nextStamp++;
1201 if (nextStamp == Integer.MAX_VALUE) {
1202 adjustStamp();
1203 }
1204 }
1205
1206 /**
1207 * Sets the values for the calendar fields <code>YEAR</code>,
1208 * <code>MONTH</code>, and <code>DAY_OF_MONTH</code>.
1209 * Previous values of other calendar fields are retained. If this is not desired,
1210 * call {@link #clear()} first.
1211 *
1212 * @param year the value used to set the <code>YEAR</code> calendar field.
1213 * @param month the value used to set the <code>MONTH</code> calendar field.
1214 * Month value is 0-based. e.g., 0 for January.
1215 * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
1216 * @see #set(int,int)
1217 * @see #set(int,int,int,int,int)
1218 * @see #set(int,int,int,int,int,int)
1219 */
1220 public final void set(int year, int month, int date)
1221 {
1222 set(YEAR, year);
1223 set(MONTH, month);
1224 set(DATE, date);
1225 }
1226
1227 /**
1228 * Sets the values for the calendar fields <code>YEAR</code>,
1229 * <code>MONTH</code>, <code>DAY_OF_MONTH</code>,
1230 * <code>HOUR_OF_DAY</code>, and <code>MINUTE</code>.
1231 * Previous values of other fields are retained. If this is not desired,
1232 * call {@link #clear()} first.
1233 *
1234 * @param year the value used to set the <code>YEAR</code> calendar field.
1235 * @param month the value used to set the <code>MONTH</code> calendar field.
1236 * Month value is 0-based. e.g., 0 for January.
1237 * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
1238 * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field.
1239 * @param minute the value used to set the <code>MINUTE</code> calendar field.
1240 * @see #set(int,int)
1241 * @see #set(int,int,int)
1242 * @see #set(int,int,int,int,int,int)
1243 */
1244 public final void set(int year, int month, int date, int hourOfDay, int minute)
1245 {
1246 set(YEAR, year);
1247 set(MONTH, month);
1248 set(DATE, date);
1249 set(HOUR_OF_DAY, hourOfDay);
1250 set(MINUTE, minute);
1251 }
1252
1253 /**
1254 * Sets the values for the fields <code>YEAR</code>, <code>MONTH</code>,
1255 * <code>DAY_OF_MONTH</code>, <code>HOUR</code>, <code>MINUTE</code>, and
1256 * <code>SECOND</code>.
1257 * Previous values of other fields are retained. If this is not desired,
1258 * call {@link #clear()} first.
1259 *
1260 * @param year the value used to set the <code>YEAR</code> calendar field.
1261 * @param month the value used to set the <code>MONTH</code> calendar field.
1262 * Month value is 0-based. e.g., 0 for January.
1263 * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
1264 * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field.
1265 * @param minute the value used to set the <code>MINUTE</code> calendar field.
1266 * @param second the value used to set the <code>SECOND</code> calendar field.
1267 * @see #set(int,int)
1268 * @see #set(int,int,int)
1269 * @see #set(int,int,int,int,int)
1270 */
1271 public final void set(int year, int month, int date, int hourOfDay, int minute,
1272 int second)
1273 {
1274 set(YEAR, year);
1275 set(MONTH, month);
1276 set(DATE, date);
1277 set(HOUR_OF_DAY, hourOfDay);
1278 set(MINUTE, minute);
1279 set(SECOND, second);
1280 }
1281
1282 /**
1283 * Sets all the calendar field values and the time value
1284 * (millisecond offset from the <a href="#Epoch">Epoch</a>) of
1285 * this <code>Calendar</code> undefined. This means that {@link
1286 * #isSet(int) isSet()} will return <code>false</code> for all the
1287 * calendar fields, and the date and time calculations will treat
1288 * the fields as if they had never been set. A
1289 * <code>Calendar</code> implementation class may use its specific
1290 * default field values for date/time calculations. For example,
1291 * <code>GregorianCalendar</code> uses 1970 if the
1292 * <code>YEAR</code> field value is undefined.
1293 *
1294 * @see #clear(int)
1295 */
1296 public final void clear()
1297 {
1298 for (int i = 0; i < fields.length; ) {
1299 stamp[i] = fields[i] = 0; // UNSET == 0
1300 isSet[i++] = false;
1301 }
1302 areAllFieldsSet = areFieldsSet = false;
1303 isTimeSet = false;
1304 }
1305
1306 /**
1307 * Sets the given calendar field value and the time value
1308 * (millisecond offset from the <a href="#Epoch">Epoch</a>) of
1309 * this <code>Calendar</code> undefined. This means that {@link
1310 * #isSet(int) isSet(field)} will return <code>false</code>, and
1311 * the date and time calculations will treat the field as if it
1312 * had never been set. A <code>Calendar</code> implementation
1313 * class may use the field's specific default value for date and
1314 * time calculations.
1315 *
1316 * <p>The {@link #HOUR_OF_DAY}, {@link #HOUR} and {@link #AM_PM}
1317 * fields are handled independently and the <a
1318 * href="#time_resolution">the resolution rule for the time of
1319 * day</a> is applied. Clearing one of the fields doesn't reset
1320 * the hour of day value of this <code>Calendar</code>. Use {@link
1321 * #set(int,int) set(Calendar.HOUR_OF_DAY, 0)} to reset the hour
1322 * value.
1323 *
1324 * @param field the calendar field to be cleared.
1325 * @see #clear()
1326 */
1327 public final void clear(int field)
1328 {
1329 fields[field] = 0;
1330 stamp[field] = UNSET;
1331 isSet[field] = false;
1332
1333 areAllFieldsSet = areFieldsSet = false;
1334 isTimeSet = false;
1335 }
1336
1337 /**
1338 * Determines if the given calendar field has a value set,
1339 * including cases that the value has been set by internal fields
1340 * calculations triggered by a <code>get</code> method call.
1341 *
1342 * @return <code>true</code> if the given calendar field has a value set;
1343 * <code>false</code> otherwise.
1344 */
1345 public final boolean isSet(int field)
1346 {
1347 return stamp[field] != UNSET;
1348 }
1349
1350 /**
1351 * Returns the string representation of the calendar
1352 * <code>field</code> value in the given <code>style</code> and
1353 * <code>locale</code>. If no string representation is
1354 * applicable, <code>null</code> is returned. This method calls
1355 * {@link Calendar#get(int) get(field)} to get the calendar
1356 * <code>field</code> value if the string representation is
1357 * applicable to the given calendar <code>field</code>.
1358 *
1359 * <p>For example, if this <code>Calendar</code> is a
1360 * <code>GregorianCalendar</code> and its date is 2005-01-01, then
1361 * the string representation of the {@link #MONTH} field would be
1362 * "January" in the long style in an English locale or "Jan" in
1363 * the short style. However, no string representation would be
1364 * available for the {@link #DAY_OF_MONTH} field, and this method
1365 * would return <code>null</code>.
1366 *
1367 * <p>The default implementation supports the calendar fields for
1368 * which a {@link DateFormatSymbols} has names in the given
1369 * <code>locale</code>.
1370 *
1371 * @param field
1372 * the calendar field for which the string representation
1373 * is returned
1374 * @param style
1375 * the style applied to the string representation; one of
1376 * {@link #SHORT} or {@link #LONG}.
1377 * @param locale
1378 * the locale for the string representation
1379 * @return the string representation of the given
1380 * <code>field</code> in the given <code>style</code>, or
1381 * <code>null</code> if no string representation is
1382 * applicable.
1383 * @exception IllegalArgumentException
1384 * if <code>field</code> or <code>style</code> is invalid,
1385 * or if this <code>Calendar</code> is non-lenient and any
1386 * of the calendar fields have invalid values
1387 * @exception NullPointerException
1388 * if <code>locale</code> is null
1389 * @since 1.6
1390 */
1391 public String getDisplayName(int field, int style, Locale locale) {
1392 if (!checkDisplayNameParams(field, style, ALL_STYLES, LONG, locale,
1393 ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {
1394 return null;
1395 }
1396
1397 DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
1398 String[] strings = getFieldStrings(field, style, symbols);
1399 if (strings != null) {
1400 int fieldValue = get(field);
1401 if (fieldValue < strings.length) {
1402 return strings[fieldValue];
1403 }
1404 }
1405 return null;
1406 }
1407
1408 /**
1409 * Returns a <code>Map</code> containing all names of the calendar
1410 * <code>field</code> in the given <code>style</code> and
1411 * <code>locale</code> and their corresponding field values. For
1412 * example, if this <code>Calendar</code> is a {@link
1413 * GregorianCalendar}, the returned map would contain "Jan" to
1414 * {@link #JANUARY}, "Feb" to {@link #FEBRUARY}, and so on, in the
1415 * {@linkplain #SHORT short} style in an English locale.
1416 *
1417 * <p>The values of other calendar fields may be taken into
1418 * account to determine a set of display names. For example, if
1419 * this <code>Calendar</code> is a lunisolar calendar system and
1420 * the year value given by the {@link #YEAR} field has a leap
1421 * month, this method would return month names containing the leap
1422 * month name, and month names are mapped to their values specific
1423 * for the year.
1424 *
1425 * <p>The default implementation supports display names contained in
1426 * a {@link DateFormatSymbols}. For example, if <code>field</code>
1427 * is {@link #MONTH} and <code>style</code> is {@link
1428 * #ALL_STYLES}, this method returns a <code>Map</code> containing
1429 * all strings returned by {@link DateFormatSymbols#getShortMonths()}
1430 * and {@link DateFormatSymbols#getMonths()}.
1431 *
1432 * @param field
1433 * the calendar field for which the display names are returned
1434 * @param style
1435 * the style applied to the display names; one of {@link
1436 * #SHORT}, {@link #LONG}, or {@link #ALL_STYLES}.
1437 * @param locale
1438 * the locale for the display names
1439 * @return a <code>Map</code> containing all display names in
1440 * <code>style</code> and <code>locale</code> and their
1441 * field values, or <code>null</code> if no display names
1442 * are defined for <code>field</code>
1443 * @exception IllegalArgumentException
1444 * if <code>field</code> or <code>style</code> is invalid,
1445 * or if this <code>Calendar</code> is non-lenient and any
1446 * of the calendar fields have invalid values
1447 * @exception NullPointerException
1448 * if <code>locale</code> is null
1449 * @since 1.6
1450 */
1451 public Map<String, Integer> getDisplayNames(int field, int style, Locale locale) {
1452 if (!checkDisplayNameParams(field, style, ALL_STYLES, LONG, locale,
1453 ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {
1454 return null;
1455 }
1456
1457 // ALL_STYLES
1458 if (style == ALL_STYLES) {
1459 Map<String,Integer> shortNames = getDisplayNamesImpl(field, SHORT, locale);
1460 if (field == ERA || field == AM_PM) {
1461 return shortNames;
1462 }
1463 Map<String,Integer> longNames = getDisplayNamesImpl(field, LONG, locale);
1464 if (shortNames == null) {
1465 return longNames;
1466 }
1467 if (longNames != null) {
1468 shortNames.putAll(longNames);
1469 }
1470 return shortNames;
1471 }
1472
1473 // SHORT or LONG
1474 return getDisplayNamesImpl(field, style, locale);
1475 }
1476
1477 private Map<String,Integer> getDisplayNamesImpl(int field, int style, Locale locale) {
1478 DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
1479 String[] strings = getFieldStrings(field, style, symbols);
1480 if (strings != null) {
1481 Map<String,Integer> names = new HashMap<String,Integer>();
1482 for (int i = 0; i < strings.length; i++) {
1483 if (strings[i].length() == 0) {
1484 continue;
1485 }
1486 names.put(strings[i], i);
1487 }
1488 return names;
1489 }
1490 return null;
1491 }
1492
1493 boolean checkDisplayNameParams(int field, int style, int minStyle, int maxStyle,
1494 Locale locale, int fieldMask) {
1495 if (field < 0 || field >= fields.length ||
1496 style < minStyle || style > maxStyle) {
1497 throw new IllegalArgumentException();
1498 }
1499 if (locale == null) {
1500 throw new NullPointerException();
1501 }
1502 return isFieldSet(fieldMask, field);
1503 }
1504
1505 private String[] getFieldStrings(int field, int style, DateFormatSymbols symbols) {
1506 String[] strings = null;
1507 switch (field) {
1508 case ERA:
1509 strings = symbols.getEras();
1510 break;
1511
1512 case MONTH:
1513 strings = (style == LONG) ? symbols.getMonths() : symbols.getShortMonths();
1514 break;
1515
1516 case DAY_OF_WEEK:
1517 strings = (style == LONG) ? symbols.getWeekdays() : symbols.getShortWeekdays();
1518 break;
1519
1520 case AM_PM:
1521 strings = symbols.getAmPmStrings();
1522 break;
1523 }
1524 return strings;
1525 }
1526
1527 /**
1528 * Fills in any unset fields in the calendar fields. First, the {@link
1529 * #computeTime()} method is called if the time value (millisecond offset
1530 * from the <a href="#Epoch">Epoch</a>) has not been calculated from
1531 * calendar field values. Then, the {@link #computeFields()} method is
1532 * called to calculate all calendar field values.
1533 */
1534 protected void complete()
1535 {
1536 if (!isTimeSet)
1537 updateTime();
1538 if (!areFieldsSet || !areAllFieldsSet) {
1539 computeFields(); // fills in unset fields
1540 areAllFieldsSet = areFieldsSet = true;
1541 }
1542 }
1543
1544 /**
1545 * Returns whether the value of the specified calendar field has been set
1546 * externally by calling one of the setter methods rather than by the
1547 * internal time calculation.
1548 *
1549 * @return <code>true</code> if the field has been set externally,
1550 * <code>false</code> otherwise.
1551 * @exception IndexOutOfBoundsException if the specified
1552 * <code>field</code> is out of range
1553 * (<code>field < 0 || field >= FIELD_COUNT</code>).
1554 * @see #selectFields()
1555 * @see #setFieldsComputed(int)
1556 */
1557 final boolean isExternallySet(int field) {
1558 return stamp[field] >= MINIMUM_USER_STAMP;
1559 }
1560
1561 /**
1562 * Returns a field mask (bit mask) indicating all calendar fields that
1563 * have the state of externally or internally set.
1564 *
1565 * @return a bit mask indicating set state fields
1566 */
1567 final int getSetStateFields() {
1568 int mask = 0;
1569 for (int i = 0; i < fields.length; i++) {
1570 if (stamp[i] != UNSET) {
1571 mask |= 1 << i;
1572 }
1573 }
1574 return mask;
1575 }
1576
1577 /**
1578 * Sets the state of the specified calendar fields to
1579 * <em>computed</em>. This state means that the specified calendar fields
1580 * have valid values that have been set by internal time calculation
1581 * rather than by calling one of the setter methods.
1582 *
1583 * @param fieldMask the field to be marked as computed.
1584 * @exception IndexOutOfBoundsException if the specified
1585 * <code>field</code> is out of range
1586 * (<code>field < 0 || field >= FIELD_COUNT</code>).
1587 * @see #isExternallySet(int)
1588 * @see #selectFields()
1589 */
1590 final void setFieldsComputed(int fieldMask) {
1591 if (fieldMask == ALL_FIELDS) {
1592 for (int i = 0; i < fields.length; i++) {
1593 stamp[i] = COMPUTED;
1594 isSet[i] = true;
1595 }
1596 areFieldsSet = areAllFieldsSet = true;
1597 } else {
1598 for (int i = 0; i < fields.length; i++) {
1599 if ((fieldMask & 1) == 1) {
1600 stamp[i] = COMPUTED;
1601 isSet[i] = true;
1602 } else {
1603 if (areAllFieldsSet && !isSet[i]) {
1604 areAllFieldsSet = false;
1605 }
1606 }
1607 fieldMask >>>= 1;
1608 }
1609 }
1610 }
1611
1612 /**
1613 * Sets the state of the calendar fields that are <em>not</em> specified
1614 * by <code>fieldMask</code> to <em>unset</em>. If <code>fieldMask</code>
1615 * specifies all the calendar fields, then the state of this
1616 * <code>Calendar</code> becomes that all the calendar fields are in sync
1617 * with the time value (millisecond offset from the Epoch).
1618 *
1619 * @param fieldMask the field mask indicating which calendar fields are in
1620 * sync with the time value.
1621 * @exception IndexOutOfBoundsException if the specified
1622 * <code>field</code> is out of range
1623 * (<code>field < 0 || field >= FIELD_COUNT</code>).
1624 * @see #isExternallySet(int)
1625 * @see #selectFields()
1626 */
1627 final void setFieldsNormalized(int fieldMask) {
1628 if (fieldMask != ALL_FIELDS) {
1629 for (int i = 0; i < fields.length; i++) {
1630 if ((fieldMask & 1) == 0) {
1631 stamp[i] = fields[i] = 0; // UNSET == 0
1632 isSet[i] = false;
1633 }
1634 fieldMask >>= 1;
1635 }
1636 }
1637
1638 // Some or all of the fields are in sync with the
1639 // milliseconds, but the stamp values are not normalized yet.
1640 areFieldsSet = true;
1641 areAllFieldsSet = false;
1642 }
1643
1644 /**
1645 * Returns whether the calendar fields are partially in sync with the time
1646 * value or fully in sync but not stamp values are not normalized yet.
1647 */
1648 final boolean isPartiallyNormalized() {
1649 return areFieldsSet && !areAllFieldsSet;
1650 }
1651
1652 /**
1653 * Returns whether the calendar fields are fully in sync with the time
1654 * value.
1655 */
1656 final boolean isFullyNormalized() {
1657 return areFieldsSet && areAllFieldsSet;
1658 }
1659
1660 /**
1661 * Marks this Calendar as not sync'd.
1662 */
1663 final void setUnnormalized() {
1664 areFieldsSet = areAllFieldsSet = false;
1665 }
1666
1667 /**
1668 * Returns whether the specified <code>field</code> is on in the
1669 * <code>fieldMask</code>.
1670 */
1671 static final boolean isFieldSet(int fieldMask, int field) {
1672 return (fieldMask & (1 << field)) != 0;
1673 }
1674
1675 /**
1676 * Returns a field mask indicating which calendar field values
1677 * to be used to calculate the time value. The calendar fields are
1678 * returned as a bit mask, each bit of which corresponds to a field, i.e.,
1679 * the mask value of <code>field</code> is <code>(1 <<
1680 * field)</code>. For example, 0x26 represents the <code>YEAR</code>,
1681 * <code>MONTH</code>, and <code>DAY_OF_MONTH</code> fields (i.e., 0x26 is
1682 * equal to
1683 * <code>(1<<YEAR)|(1<<MONTH)|(1<<DAY_OF_MONTH))</code>.
1684 *
1685 * <p>This method supports the calendar fields resolution as described in
1686 * the class description. If the bit mask for a given field is on and its
1687 * field has not been set (i.e., <code>isSet(field)</code> is
1688 * <code>false</code>), then the default value of the field has to be
1689 * used, which case means that the field has been selected because the
1690 * selected combination involves the field.
1691 *
1692 * @return a bit mask of selected fields
1693 * @see #isExternallySet(int)
1694 * @see #setInternallySetState(int)
1695 */
1696 final int selectFields() {
1697 // This implementation has been taken from the GregorianCalendar class.
1698
1699 // The YEAR field must always be used regardless of its SET
1700 // state because YEAR is a mandatory field to determine the date
1701 // and the default value (EPOCH_YEAR) may change through the
1702 // normalization process.
1703 int fieldMask = YEAR_MASK;
1704
1705 if (stamp[ERA] != UNSET) {
1706 fieldMask |= ERA_MASK;
1707 }
1708 // Find the most recent group of fields specifying the day within
1709 // the year. These may be any of the following combinations:
1710 // MONTH + DAY_OF_MONTH
1711 // MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
1712 // MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
1713 // DAY_OF_YEAR
1714 // WEEK_OF_YEAR + DAY_OF_WEEK
1715 // We look for the most recent of the fields in each group to determine
1716 // the age of the group. For groups involving a week-related field such
1717 // as WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR, both the
1718 // week-related field and the DAY_OF_WEEK must be set for the group as a
1719 // whole to be considered. (See bug 4153860 - liu 7/24/98.)
1720 int dowStamp = stamp[DAY_OF_WEEK];
1721 int monthStamp = stamp[MONTH];
1722 int domStamp = stamp[DAY_OF_MONTH];
1723 int womStamp = aggregateStamp(stamp[WEEK_OF_MONTH], dowStamp);
1724 int dowimStamp = aggregateStamp(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
1725 int doyStamp = stamp[DAY_OF_YEAR];
1726 int woyStamp = aggregateStamp(stamp[WEEK_OF_YEAR], dowStamp);
1727
1728 int bestStamp = domStamp;
1729 if (womStamp > bestStamp) {
1730 bestStamp = womStamp;
1731 }
1732 if (dowimStamp > bestStamp) {
1733 bestStamp = dowimStamp;
1734 }
1735 if (doyStamp > bestStamp) {
1736 bestStamp = doyStamp;
1737 }
1738 if (woyStamp > bestStamp) {
1739 bestStamp = woyStamp;
1740 }
1741
1742 /* No complete combination exists. Look for WEEK_OF_MONTH,
1743 * DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR alone. Treat DAY_OF_WEEK alone
1744 * as DAY_OF_WEEK_IN_MONTH.
1745 */
1746 if (bestStamp == UNSET) {
1747 womStamp = stamp[WEEK_OF_MONTH];
1748 dowimStamp = Math.max(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
1749 woyStamp = stamp[WEEK_OF_YEAR];
1750 bestStamp = Math.max(Math.max(womStamp, dowimStamp), woyStamp);
1751
1752 /* Treat MONTH alone or no fields at all as DAY_OF_MONTH. This may
1753 * result in bestStamp = domStamp = UNSET if no fields are set,
1754 * which indicates DAY_OF_MONTH.
1755 */
1756 if (bestStamp == UNSET) {
1757 bestStamp = domStamp = monthStamp;
1758 }
1759 }
1760
1761 if (bestStamp == domStamp ||
1762 (bestStamp == womStamp && stamp[WEEK_OF_MONTH] >= stamp[WEEK_OF_YEAR]) ||
1763 (bestStamp == dowimStamp && stamp[DAY_OF_WEEK_IN_MONTH] >= stamp[WEEK_OF_YEAR])) {
1764 fieldMask |= MONTH_MASK;
1765 if (bestStamp == domStamp) {
1766 fieldMask |= DAY_OF_MONTH_MASK;
1767 } else {
1768 assert (bestStamp == womStamp || bestStamp == dowimStamp);
1769 if (dowStamp != UNSET) {
1770 fieldMask |= DAY_OF_WEEK_MASK;
1771 }
1772 if (womStamp == dowimStamp) {
1773 // When they are equal, give the priority to
1774 // WEEK_OF_MONTH for compatibility.
1775 if (stamp[WEEK_OF_MONTH] >= stamp[DAY_OF_WEEK_IN_MONTH]) {
1776 fieldMask |= WEEK_OF_MONTH_MASK;
1777 } else {
1778 fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK;
1779 }
1780 } else {
1781 if (bestStamp == womStamp) {
1782 fieldMask |= WEEK_OF_MONTH_MASK;
1783 } else {
1784 assert (bestStamp == dowimStamp);
1785 if (stamp[DAY_OF_WEEK_IN_MONTH] != UNSET) {
1786 fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK;
1787 }
1788 }
1789 }
1790 }
1791 } else {
1792 assert (bestStamp == doyStamp || bestStamp == woyStamp ||
1793 bestStamp == UNSET);
1794 if (bestStamp == doyStamp) {
1795 fieldMask |= DAY_OF_YEAR_MASK;
1796 } else {
1797 assert (bestStamp == woyStamp);
1798 if (dowStamp != UNSET) {
1799 fieldMask |= DAY_OF_WEEK_MASK;
1800 }
1801 fieldMask |= WEEK_OF_YEAR_MASK;
1802 }
1803 }
1804
1805 // Find the best set of fields specifying the time of day. There
1806 // are only two possibilities here; the HOUR_OF_DAY or the
1807 // AM_PM and the HOUR.
1808 int hourOfDayStamp = stamp[HOUR_OF_DAY];
1809 int hourStamp = aggregateStamp(stamp[HOUR], stamp[AM_PM]);
1810 bestStamp = (hourStamp > hourOfDayStamp) ? hourStamp : hourOfDayStamp;
1811
1812 // if bestStamp is still UNSET, then take HOUR or AM_PM. (See 4846659)
1813 if (bestStamp == UNSET) {
1814 bestStamp = Math.max(stamp[HOUR], stamp[AM_PM]);
1815 }
1816
1817 // Hours
1818 if (bestStamp != UNSET) {
1819 if (bestStamp == hourOfDayStamp) {
1820 fieldMask |= HOUR_OF_DAY_MASK;
1821 } else {
1822 fieldMask |= HOUR_MASK;
1823 if (stamp[AM_PM] != UNSET) {
1824 fieldMask |= AM_PM_MASK;
1825 }
1826 }
1827 }
1828 if (stamp[MINUTE] != UNSET) {
1829 fieldMask |= MINUTE_MASK;
1830 }
1831 if (stamp[SECOND] != UNSET) {
1832 fieldMask |= SECOND_MASK;
1833 }
1834 if (stamp[MILLISECOND] != UNSET) {
1835 fieldMask |= MILLISECOND_MASK;
1836 }
1837 if (stamp[ZONE_OFFSET] >= MINIMUM_USER_STAMP) {
1838 fieldMask |= ZONE_OFFSET_MASK;
1839 }
1840 if (stamp[DST_OFFSET] >= MINIMUM_USER_STAMP) {
1841 fieldMask |= DST_OFFSET_MASK;
1842 }
1843
1844 return fieldMask;
1845 }
1846
1847 /**
1848 * Returns the pseudo-time-stamp for two fields, given their
1849 * individual pseudo-time-stamps. If either of the fields
1850 * is unset, then the aggregate is unset. Otherwise, the
1851 * aggregate is the later of the two stamps.
1852 */
1853 private static final int aggregateStamp(int stamp_a, int stamp_b) {
1854 if (stamp_a == UNSET || stamp_b == UNSET) {
1855 return UNSET;
1856 }
1857 return (stamp_a > stamp_b) ? stamp_a : stamp_b;
1858 }
1859
1860 /**
1861 * Compares this <code>Calendar</code> to the specified
1862 * <code>Object</code>. The result is <code>true</code> if and only if
1863 * the argument is a <code>Calendar</code> object of the same calendar
1864 * system that represents the same time value (millisecond offset from the
1865 * <a href="#Epoch">Epoch</a>) under the same
1866 * <code>Calendar</code> parameters as this object.
1867 *
1868 * <p>The <code>Calendar</code> parameters are the values represented
1869 * by the <code>isLenient</code>, <code>getFirstDayOfWeek</code>,
1870 * <code>getMinimalDaysInFirstWeek</code> and <code>getTimeZone</code>
1871 * methods. If there is any difference in those parameters
1872 * between the two <code>Calendar</code>s, this method returns
1873 * <code>false</code>.
1874 *
1875 * <p>Use the {@link #compareTo(Calendar) compareTo} method to
1876 * compare only the time values.
1877 *
1878 * @param obj the object to compare with.
1879 * @return <code>true</code> if this object is equal to <code>obj</code>;
1880 * <code>false</code> otherwise.
1881 */
1882 public boolean equals(Object obj) {
1883 if (this == obj)
1884 return true;
1885 try {
1886 Calendar that = (Calendar)obj;
1887 return compareTo(getMillisOf(that)) == 0 &&
1888 lenient == that.lenient &&
1889 firstDayOfWeek == that.firstDayOfWeek &&
1890 minimalDaysInFirstWeek == that.minimalDaysInFirstWeek &&
1891 zone.equals(that.zone);
1892 } catch (Exception e) {
1893 // Note: GregorianCalendar.computeTime throws
1894 // IllegalArgumentException if the ERA value is invalid
1895 // even it's in lenient mode.
1896 }
1897 return false;
1898 }
1899
1900 /**
1901 * Returns a hash code for this calendar.
1902 *
1903 * @return a hash code value for this object.
1904 * @since 1.2
1905 */
1906 public int hashCode() {
1907 // 'otheritems' represents the hash code for the previous versions.
1908 int otheritems = (lenient ? 1 : 0)
1909 | (firstDayOfWeek << 1)
1910 | (minimalDaysInFirstWeek << 4)
1911 | (zone.hashCode() << 7);
1912 long t = getMillisOf(this);
1913 return (int) t ^ (int)(t >> 32) ^ otheritems;
1914 }
1915
1916 /**
1917 * Returns whether this <code>Calendar</code> represents a time
1918 * before the time represented by the specified
1919 * <code>Object</code>. This method is equivalent to:
1920 * <pre><blockquote>
1921 * compareTo(when) < 0
1922 * </blockquote></pre>
1923 * if and only if <code>when</code> is a <code>Calendar</code>
1924 * instance. Otherwise, the method returns <code>false</code>.
1925 *
1926 * @param when the <code>Object</code> to be compared
1927 * @return <code>true</code> if the time of this
1928 * <code>Calendar</code> is before the time represented by
1929 * <code>when</code>; <code>false</code> otherwise.
1930 * @see #compareTo(Calendar)
1931 */
1932 public boolean before(Object when) {
1933 return when instanceof Calendar
1934 && compareTo((Calendar)when) < 0;
1935 }
1936
1937 /**
1938 * Returns whether this <code>Calendar</code> represents a time
1939 * after the time represented by the specified
1940 * <code>Object</code>. This method is equivalent to:
1941 * <pre><blockquote>
1942 * compareTo(when) > 0
1943 * </blockquote></pre>
1944 * if and only if <code>when</code> is a <code>Calendar</code>
1945 * instance. Otherwise, the method returns <code>false</code>.
1946 *
1947 * @param when the <code>Object</code> to be compared
1948 * @return <code>true</code> if the time of this <code>Calendar</code> is
1949 * after the time represented by <code>when</code>; <code>false</code>
1950 * otherwise.
1951 * @see #compareTo(Calendar)
1952 */
1953 public boolean after(Object when) {
1954 return when instanceof Calendar
1955 && compareTo((Calendar)when) > 0;
1956 }
1957
1958 /**
1959 * Compares the time values (millisecond offsets from the <a
1960 * href="#Epoch">Epoch</a>) represented by two
1961 * <code>Calendar</code> objects.
1962 *
1963 * @param anotherCalendar the <code>Calendar</code> to be compared.
1964 * @return the value <code>0</code> if the time represented by the argument
1965 * is equal to the time represented by this <code>Calendar</code>; a value
1966 * less than <code>0</code> if the time of this <code>Calendar</code> is
1967 * before the time represented by the argument; and a value greater than
1968 * <code>0</code> if the time of this <code>Calendar</code> is after the
1969 * time represented by the argument.
1970 * @exception NullPointerException if the specified <code>Calendar</code> is
1971 * <code>null</code>.
1972 * @exception IllegalArgumentException if the time value of the
1973 * specified <code>Calendar</code> object can't be obtained due to
1974 * any invalid calendar values.
1975 * @since 1.5
1976 */
1977 public int compareTo(Calendar anotherCalendar) {
1978 return compareTo(getMillisOf(anotherCalendar));
1979 }
1980
1981 /**
1982 * Adds or subtracts the specified amount of time to the given calendar field,
1983 * based on the calendar's rules. For example, to subtract 5 days from
1984 * the current time of the calendar, you can achieve it by calling:
1985 * <p><code>add(Calendar.DAY_OF_MONTH, -5)</code>.
1986 *
1987 * @param field the calendar field.
1988 * @param amount the amount of date or time to be added to the field.
1989 * @see #roll(int,int)
1990 * @see #set(int,int)
1991 */
1992 abstract public void add(int field, int amount);
1993
1994 /**
1995 * Adds or subtracts (up/down) a single unit of time on the given time
1996 * field without changing larger fields. For example, to roll the current
1997 * date up by one day, you can achieve it by calling:
1998 * <p>roll(Calendar.DATE, true).
1999 * When rolling on the year or Calendar.YEAR field, it will roll the year
2000 * value in the range between 1 and the value returned by calling
2001 * <code>getMaximum(Calendar.YEAR)</code>.
2002 * When rolling on the month or Calendar.MONTH field, other fields like
2003 * date might conflict and, need to be changed. For instance,
2004 * rolling the month on the date 01/31/96 will result in 02/29/96.
2005 * When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field, it will
2006 * roll the hour value in the range between 0 and 23, which is zero-based.
2007 *
2008 * @param field the time field.
2009 * @param up indicates if the value of the specified time field is to be
2010 * rolled up or rolled down. Use true if rolling up, false otherwise.
2011 * @see Calendar#add(int,int)
2012 * @see Calendar#set(int,int)
2013 */
2014 abstract public void roll(int field, boolean up);
2015
2016 /**
2017 * Adds the specified (signed) amount to the specified calendar field
2018 * without changing larger fields. A negative amount means to roll
2019 * down.
2020 *
2021 * <p>NOTE: This default implementation on <code>Calendar</code> just repeatedly calls the
2022 * version of {@link #roll(int,boolean) roll()} that rolls by one unit. This may not
2023 * always do the right thing. For example, if the <code>DAY_OF_MONTH</code> field is 31,
2024 * rolling through February will leave it set to 28. The <code>GregorianCalendar</code>
2025 * version of this function takes care of this problem. Other subclasses
2026 * should also provide overrides of this function that do the right thing.
2027 *
2028 * @param field the calendar field.
2029 * @param amount the signed amount to add to the calendar <code>field</code>.
2030 * @since 1.2
2031 * @see #roll(int,boolean)
2032 * @see #add(int,int)
2033 * @see #set(int,int)
2034 */
2035 public void roll(int field, int amount)
2036 {
2037 while (amount > 0) {
2038 roll(field, true);
2039 amount--;
2040 }
2041 while (amount < 0) {
2042 roll(field, false);
2043 amount++;
2044 }
2045 }
2046
2047 /**
2048 * Sets the time zone with the given time zone value.
2049 *
2050 * @param value the given time zone.
2051 */
2052 public void setTimeZone(TimeZone value)
2053 {
2054 zone = value;
2055 sharedZone = false;
2056 /* Recompute the fields from the time using the new zone. This also
2057 * works if isTimeSet is false (after a call to set()). In that case
2058 * the time will be computed from the fields using the new zone, then
2059 * the fields will get recomputed from that. Consider the sequence of
2060 * calls: cal.setTimeZone(EST); cal.set(HOUR, 1); cal.setTimeZone(PST).
2061 * Is cal set to 1 o'clock EST or 1 o'clock PST? Answer: PST. More
2062 * generally, a call to setTimeZone() affects calls to set() BEFORE AND
2063 * AFTER it up to the next call to complete().
2064 */
2065 areAllFieldsSet = areFieldsSet = false;
2066 }
2067
2068 /**
2069 * Gets the time zone.
2070 *
2071 * @return the time zone object associated with this calendar.
2072 */
2073 public TimeZone getTimeZone()
2074 {
2075 // If the TimeZone object is shared by other Calendar instances, then
2076 // create a clone.
2077 if (sharedZone) {
2078 zone = (TimeZone) zone.clone();
2079 sharedZone = false;
2080 }
2081 return zone;
2082 }
2083
2084 /**
2085 * Returns the time zone (without cloning).
2086 */
2087 TimeZone getZone() {
2088 return zone;
2089 }
2090
2091 /**
2092 * Sets the sharedZone flag to <code>shared</code>.
2093 */
2094 void setZoneShared(boolean shared) {
2095 sharedZone = shared;
2096 }
2097
2098 /**
2099 * Specifies whether or not date/time interpretation is to be lenient. With
2100 * lenient interpretation, a date such as "February 942, 1996" will be
2101 * treated as being equivalent to the 941st day after February 1, 1996.
2102 * With strict (non-lenient) interpretation, such dates will cause an exception to be
2103 * thrown. The default is lenient.
2104 *
2105 * @param lenient <code>true</code> if the lenient mode is to be turned
2106 * on; <code>false</code> if it is to be turned off.
2107 * @see #isLenient()
2108 * @see java.text.DateFormat#setLenient
2109 */
2110 public void setLenient(boolean lenient)
2111 {
2112 this.lenient = lenient;
2113 }
2114
2115 /**
2116 * Tells whether date/time interpretation is to be lenient.
2117 *
2118 * @return <code>true</code> if the interpretation mode of this calendar is lenient;
2119 * <code>false</code> otherwise.
2120 * @see #setLenient(boolean)
2121 */
2122 public boolean isLenient()
2123 {
2124 return lenient;
2125 }
2126
2127 /**
2128 * Sets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
2129 * <code>MONDAY</code> in France.
2130 *
2131 * @param value the given first day of the week.
2132 * @see #getFirstDayOfWeek()
2133 * @see #getMinimalDaysInFirstWeek()
2134 */
2135 public void setFirstDayOfWeek(int value)
2136 {
2137 if (firstDayOfWeek == value) {
2138 return;
2139 }
2140 firstDayOfWeek = value;
2141 invalidateWeekFields();
2142 }
2143
2144 /**
2145 * Gets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
2146 * <code>MONDAY</code> in France.
2147 *
2148 * @return the first day of the week.
2149 * @see #setFirstDayOfWeek(int)
2150 * @see #getMinimalDaysInFirstWeek()
2151 */
2152 public int getFirstDayOfWeek()
2153 {
2154 return firstDayOfWeek;
2155 }
2156
2157 /**
2158 * Sets what the minimal days required in the first week of the year are;
2159 * For example, if the first week is defined as one that contains the first
2160 * day of the first month of a year, call this method with value 1. If it
2161 * must be a full week, use value 7.
2162 *
2163 * @param value the given minimal days required in the first week
2164 * of the year.
2165 * @see #getMinimalDaysInFirstWeek()
2166 */
2167 public void setMinimalDaysInFirstWeek(int value)
2168 {
2169 if (minimalDaysInFirstWeek == value) {
2170 return;
2171 }
2172 minimalDaysInFirstWeek = value;
2173 invalidateWeekFields();
2174 }
2175
2176 /**
2177 * Gets what the minimal days required in the first week of the year are;
2178 * e.g., if the first week is defined as one that contains the first day
2179 * of the first month of a year, this method returns 1. If
2180 * the minimal days required must be a full week, this method
2181 * returns 7.
2182 *
2183 * @return the minimal days required in the first week of the year.
2184 * @see #setMinimalDaysInFirstWeek(int)
2185 */
2186 public int getMinimalDaysInFirstWeek()
2187 {
2188 return minimalDaysInFirstWeek;
2189 }
2190
2191 /**
2192 * Returns the minimum value for the given calendar field of this
2193 * <code>Calendar</code> instance. The minimum value is defined as
2194 * the smallest value returned by the {@link #get(int) get} method
2195 * for any possible time value. The minimum value depends on
2196 * calendar system specific parameters of the instance.
2197 *
2198 * @param field the calendar field.
2199 * @return the minimum value for the given calendar field.
2200 * @see #getMaximum(int)
2201 * @see #getGreatestMinimum(int)
2202 * @see #getLeastMaximum(int)
2203 * @see #getActualMinimum(int)
2204 * @see #getActualMaximum(int)
2205 */
2206 abstract public int getMinimum(int field);
2207
2208 /**
2209 * Returns the maximum value for the given calendar field of this
2210 * <code>Calendar</code> instance. The maximum value is defined as
2211 * the largest value returned by the {@link #get(int) get} method
2212 * for any possible time value. The maximum value depends on
2213 * calendar system specific parameters of the instance.
2214 *
2215 * @param field the calendar field.
2216 * @return the maximum value for the given calendar field.
2217 * @see #getMinimum(int)
2218 * @see #getGreatestMinimum(int)
2219 * @see #getLeastMaximum(int)
2220 * @see #getActualMinimum(int)
2221 * @see #getActualMaximum(int)
2222 */
2223 abstract public int getMaximum(int field);
2224
2225 /**
2226 * Returns the highest minimum value for the given calendar field
2227 * of this <code>Calendar</code> instance. The highest minimum
2228 * value is defined as the largest value returned by {@link
2229 * #getActualMinimum(int)} for any possible time value. The
2230 * greatest minimum value depends on calendar system specific
2231 * parameters of the instance.
2232 *
2233 * @param field the calendar field.
2234 * @return the highest minimum value for the given calendar field.
2235 * @see #getMinimum(int)
2236 * @see #getMaximum(int)
2237 * @see #getLeastMaximum(int)
2238 * @see #getActualMinimum(int)
2239 * @see #getActualMaximum(int)
2240 */
2241 abstract public int getGreatestMinimum(int field);
2242
2243 /**
2244 * Returns the lowest maximum value for the given calendar field
2245 * of this <code>Calendar</code> instance. The lowest maximum
2246 * value is defined as the smallest value returned by {@link
2247 * #getActualMaximum(int)} for any possible time value. The least
2248 * maximum value depends on calendar system specific parameters of
2249 * the instance. For example, a <code>Calendar</code> for the
2250 * Gregorian calendar system returns 28 for the
2251 * <code>DAY_OF_MONTH</code> field, because the 28th is the last
2252 * day of the shortest month of this calendar, February in a
2253 * common year.
2254 *
2255 * @param field the calendar field.
2256 * @return the lowest maximum value for the given calendar field.
2257 * @see #getMinimum(int)
2258 * @see #getMaximum(int)
2259 * @see #getGreatestMinimum(int)
2260 * @see #getActualMinimum(int)
2261 * @see #getActualMaximum(int)
2262 */
2263 abstract public int getLeastMaximum(int field);
2264
2265 /**
2266 * Returns the minimum value that the specified calendar field
2267 * could have, given the time value of this <code>Calendar</code>.
2268 *
2269 * <p>The default implementation of this method uses an iterative
2270 * algorithm to determine the actual minimum value for the
2271 * calendar field. Subclasses should, if possible, override this
2272 * with a more efficient implementation - in many cases, they can
2273 * simply return <code>getMinimum()</code>.
2274 *
2275 * @param field the calendar field
2276 * @return the minimum of the given calendar field for the time
2277 * value of this <code>Calendar</code>
2278 * @see #getMinimum(int)
2279 * @see #getMaximum(int)
2280 * @see #getGreatestMinimum(int)
2281 * @see #getLeastMaximum(int)
2282 * @see #getActualMaximum(int)
2283 * @since 1.2
2284 */
2285 public int getActualMinimum(int field) {
2286 int fieldValue = getGreatestMinimum(field);
2287 int endValue = getMinimum(field);
2288
2289 // if we know that the minimum value is always the same, just return it
2290 if (fieldValue == endValue) {
2291 return fieldValue;
2292 }
2293
2294 // clone the calendar so we don't mess with the real one, and set it to
2295 // accept anything for the field values
2296 Calendar work = (Calendar)this.clone();
2297 work.setLenient(true);
2298
2299 // now try each value from getLeastMaximum() to getMaximum() one by one until
2300 // we get a value that normalizes to another value. The last value that
2301 // normalizes to itself is the actual minimum for the current date
2302 int result = fieldValue;
2303
2304 do {
2305 work.set(field, fieldValue);
2306 if (work.get(field) != fieldValue) {
2307 break;
2308 } else {
2309 result = fieldValue;
2310 fieldValue--;
2311 }
2312 } while (fieldValue >= endValue);
2313
2314 return result;
2315 }
2316
2317 /**
2318 * Returns the maximum value that the specified calendar field
2319 * could have, given the time value of this
2320 * <code>Calendar</code>. For example, the actual maximum value of
2321 * the <code>MONTH</code> field is 12 in some years, and 13 in
2322 * other years in the Hebrew calendar system.
2323 *
2324 * <p>The default implementation of this method uses an iterative
2325 * algorithm to determine the actual maximum value for the
2326 * calendar field. Subclasses should, if possible, override this
2327 * with a more efficient implementation.
2328 *
2329 * @param field the calendar field
2330 * @return the maximum of the given calendar field for the time
2331 * value of this <code>Calendar</code>
2332 * @see #getMinimum(int)
2333 * @see #getMaximum(int)
2334 * @see #getGreatestMinimum(int)
2335 * @see #getLeastMaximum(int)
2336 * @see #getActualMinimum(int)
2337 * @since 1.2
2338 */
2339 public int getActualMaximum(int field) {
2340 int fieldValue = getLeastMaximum(field);
2341 int endValue = getMaximum(field);
2342
2343 // if we know that the maximum value is always the same, just return it.
2344 if (fieldValue == endValue) {
2345 return fieldValue;
2346 }
2347
2348 // clone the calendar so we don't mess with the real one, and set it to
2349 // accept anything for the field values.
2350 Calendar work = (Calendar)this.clone();
2351 work.setLenient(true);
2352
2353 // if we're counting weeks, set the day of the week to Sunday. We know the
2354 // last week of a month or year will contain the first day of the week.
2355 if (field == WEEK_OF_YEAR || field == WEEK_OF_MONTH)
2356 work.set(DAY_OF_WEEK, firstDayOfWeek);
2357
2358 // now try each value from getLeastMaximum() to getMaximum() one by one until
2359 // we get a value that normalizes to another value. The last value that
2360 // normalizes to itself is the actual maximum for the current date
2361 int result = fieldValue;
2362
2363 do {
2364 work.set(field, fieldValue);
2365 if (work.get(field) != fieldValue) {
2366 break;
2367 } else {
2368 result = fieldValue;
2369 fieldValue++;
2370 }
2371 } while (fieldValue <= endValue);
2372
2373 return result;
2374 }
2375
2376 /**
2377 * Creates and returns a copy of this object.
2378 *
2379 * @return a copy of this object.
2380 */
2381 public Object clone()
2382 {
2383 try {
2384 Calendar other = (Calendar) super.clone();
2385
2386 other.fields = new int[FIELD_COUNT];
2387 other.isSet = new boolean[FIELD_COUNT];
2388 other.stamp = new int[FIELD_COUNT];
2389 for (int i = 0; i < FIELD_COUNT; i++) {
2390 other.fields[i] = fields[i];
2391 other.stamp[i] = stamp[i];
2392 other.isSet[i] = isSet[i];
2393 }
2394 other.zone = (TimeZone) zone.clone();
2395 return other;
2396 }
2397 catch (CloneNotSupportedException e) {
2398 // this shouldn't happen, since we are Cloneable
2399 throw new InternalError();
2400 }
2401 }
2402
2403 private static final String[] FIELD_NAME = {
2404 "ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH", "DAY_OF_MONTH",
2405 "DAY_OF_YEAR", "DAY_OF_WEEK", "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR",
2406 "HOUR_OF_DAY", "MINUTE", "SECOND", "MILLISECOND", "ZONE_OFFSET",
2407 "DST_OFFSET"
2408 };
2409
2410 /**
2411 * Returns the name of the specified calendar field.
2412 *
2413 * @param field the calendar field
2414 * @return the calendar field name
2415 * @exception IndexOutOfBoundsException if <code>field</code> is negative,
2416 * equal to or greater then <code>FIELD_COUNT</code>.
2417 */
2418 static final String getFieldName(int field) {
2419 return FIELD_NAME[field];
2420 }
2421
2422 /**
2423 * Return a string representation of this calendar. This method
2424 * is intended to be used only for debugging purposes, and the
2425 * format of the returned string may vary between implementations.
2426 * The returned string may be empty but may not be <code>null</code>.
2427 *
2428 * @return a string representation of this calendar.
2429 */
2430 public String toString() {
2431 // NOTE: BuddhistCalendar.toString() interprets the string
2432 // produced by this method so that the Gregorian year number
2433 // is substituted by its B.E. year value. It relies on
2434 // "...,YEAR=<year>,..." or "...,YEAR=?,...".
2435 StringBuilder buffer = new StringBuilder(800);
2436 buffer.append(getClass().getName()).append('[');
2437 appendValue(buffer, "time", isTimeSet, time);
2438 buffer.append(",areFieldsSet=").append(areFieldsSet);
2439 buffer.append(",areAllFieldsSet=").append(areAllFieldsSet);
2440 buffer.append(",lenient=").append(lenient);
2441 buffer.append(",zone=").append(zone);
2442 appendValue(buffer, ",firstDayOfWeek", true, (long) firstDayOfWeek);
2443 appendValue(buffer, ",minimalDaysInFirstWeek", true, (long) minimalDaysInFirstWeek);
2444 for (int i = 0; i < FIELD_COUNT; ++i) {
2445 buffer.append(',');
2446 appendValue(buffer, FIELD_NAME[i], isSet(i), (long) fields[i]);
2447 }
2448 buffer.append(']');
2449 return buffer.toString();
2450 }
2451
2452 // =======================privates===============================
2453
2454 private static final void appendValue(StringBuilder sb, String item, boolean valid, long value) {
2455 sb.append(item).append('=');
2456 if (valid) {
2457 sb.append(value);
2458 } else {
2459 sb.append('?');
2460 }
2461 }
2462
2463 /**
2464 * Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent.
2465 * They are used to figure out the week count for a specific date for
2466 * a given locale. These must be set when a Calendar is constructed.
2467 * @param desiredLocale the given locale.
2468 */
2469 private void setWeekCountData(Locale desiredLocale)
2470 {
2471 /* try to get the Locale data from the cache */
2472 int[] data = cachedLocaleData.get(desiredLocale);
2473 if (data == null) { /* cache miss */
2474 ResourceBundle bundle = LocaleData.getCalendarData(desiredLocale);
2475 data = new int[2];
2476 data[0] = Integer.parseInt(bundle.getString("firstDayOfWeek"));
2477 data[1] = Integer.parseInt(bundle.getString("minimalDaysInFirstWeek"));
2478 cachedLocaleData.put(desiredLocale, data);
2479 }
2480 firstDayOfWeek = data[0];
2481 minimalDaysInFirstWeek = data[1];
2482 }
2483
2484 /**
2485 * Recomputes the time and updates the status fields isTimeSet
2486 * and areFieldsSet. Callers should check isTimeSet and only
2487 * call this method if isTimeSet is false.
2488 */
2489 private void updateTime() {
2490 computeTime();
2491 // The areFieldsSet and areAllFieldsSet values are no longer
2492 // controlled here (as of 1.5).
2493 isTimeSet = true;
2494 }
2495
2496 private int compareTo(long t) {
2497 long thisTime = getMillisOf(this);
2498 return (thisTime > t) ? 1 : (thisTime == t) ? 0 : -1;
2499 }
2500
2501 private static final long getMillisOf(Calendar calendar) {
2502 if (calendar.isTimeSet) {
2503 return calendar.time;
2504 }
2505 Calendar cal = (Calendar) calendar.clone();
2506 cal.setLenient(true);
2507 return cal.getTimeInMillis();
2508 }
2509
2510 /**
2511 * Adjusts the stamp[] values before nextStamp overflow. nextStamp
2512 * is set to the next stamp value upon the return.
2513 */
2514 private final void adjustStamp() {
2515 int max = MINIMUM_USER_STAMP;
2516 int newStamp = MINIMUM_USER_STAMP;
2517
2518 for (;;) {
2519 int min = Integer.MAX_VALUE;
2520 for (int i = 0; i < stamp.length; i++) {
2521 int v = stamp[i];
2522 if (v >= newStamp && min > v) {
2523 min = v;
2524 }
2525 if (max < v) {
2526 max = v;
2527 }
2528 }
2529 if (max != min && min == Integer.MAX_VALUE) {
2530 break;
2531 }
2532 for (int i = 0; i < stamp.length; i++) {
2533 if (stamp[i] == min) {
2534 stamp[i] = newStamp;
2535 }
2536 }
2537 newStamp++;
2538 if (min == max) {
2539 break;
2540 }
2541 }
2542 nextStamp = newStamp;
2543 }
2544
2545 /**
2546 * Sets the WEEK_OF_MONTH and WEEK_OF_YEAR fields to new values with the
2547 * new parameter value if they have been calculated internally.
2548 */
2549 private void invalidateWeekFields()
2550 {
2551 if (stamp[WEEK_OF_MONTH] != COMPUTED &&
2552 stamp[WEEK_OF_YEAR] != COMPUTED) {
2553 return;
2554 }
2555
2556 // We have to check the new values of these fields after changing
2557 // firstDayOfWeek and/or minimalDaysInFirstWeek. If the field values
2558 // have been changed, then set the new values. (4822110)
2559 Calendar cal = (Calendar) clone();
2560 cal.setLenient(true);
2561 cal.clear(WEEK_OF_MONTH);
2562 cal.clear(WEEK_OF_YEAR);
2563
2564 if (stamp[WEEK_OF_MONTH] == COMPUTED) {
2565 int weekOfMonth = cal.get(WEEK_OF_MONTH);
2566 if (fields[WEEK_OF_MONTH] != weekOfMonth) {
2567 fields[WEEK_OF_MONTH] = weekOfMonth;
2568 }
2569 }
2570
2571 if (stamp[WEEK_OF_YEAR] == COMPUTED) {
2572 int weekOfYear = cal.get(WEEK_OF_YEAR);
2573 if (fields[WEEK_OF_YEAR] != weekOfYear) {
2574 fields[WEEK_OF_YEAR] = weekOfYear;
2575 }
2576 }
2577 }
2578
2579 /**
2580 * Save the state of this object to a stream (i.e., serialize it).
2581 *
2582 * Ideally, <code>Calendar</code> would only write out its state data and
2583 * the current time, and not write any field data out, such as
2584 * <code>fields[]</code>, <code>isTimeSet</code>, <code>areFieldsSet</code>,
2585 * and <code>isSet[]</code>. <code>nextStamp</code> also should not be part
2586 * of the persistent state. Unfortunately, this didn't happen before JDK 1.1
2587 * shipped. To be compatible with JDK 1.1, we will always have to write out
2588 * the field values and state flags. However, <code>nextStamp</code> can be
2589 * removed from the serialization stream; this will probably happen in the
2590 * near future.
2591 */
2592 private void writeObject(ObjectOutputStream stream)
2593 throws IOException
2594 {
2595 // Try to compute the time correctly, for the future (stream
2596 // version 2) in which we don't write out fields[] or isSet[].
2597 if (!isTimeSet) {
2598 try {
2599 updateTime();
2600 }
2601 catch (IllegalArgumentException e) {}
2602 }
2603
2604 // If this Calendar has a ZoneInfo, save it and set a
2605 // SimpleTimeZone equivalent (as a single DST schedule) for
2606 // backward compatibility.
2607 TimeZone savedZone = null;
2608 if (zone instanceof ZoneInfo) {
2609 SimpleTimeZone stz = ((ZoneInfo)zone).getLastRuleInstance();
2610 if (stz == null) {
2611 stz = new SimpleTimeZone(zone.getRawOffset(), zone.getID());
2612 }
2613 savedZone = zone;
2614 zone = stz;
2615 }
2616
2617 // Write out the 1.1 FCS object.
2618 stream.defaultWriteObject();
2619
2620 // Write out the ZoneInfo object
2621 // 4802409: we write out even if it is null, a temporary workaround
2622 // the real fix for bug 4844924 in corba-iiop
2623 stream.writeObject(savedZone);
2624 if (savedZone != null) {
2625 zone = savedZone;
2626 }
2627 }
2628
2629 /**
2630 * Reconstitutes this object from a stream (i.e., deserialize it).
2631 */
2632 private void readObject(ObjectInputStream stream)
2633 throws IOException, ClassNotFoundException
2634 {
2635 final ObjectInputStream input = stream;
2636 input.defaultReadObject();
2637
2638 stamp = new int[FIELD_COUNT];
2639
2640 // Starting with version 2 (not implemented yet), we expect that
2641 // fields[], isSet[], isTimeSet, and areFieldsSet may not be
2642 // streamed out anymore. We expect 'time' to be correct.
2643 if (serialVersionOnStream >= 2)
2644 {
2645 isTimeSet = true;
2646 if (fields == null) fields = new int[FIELD_COUNT];
2647 if (isSet == null) isSet = new boolean[FIELD_COUNT];
2648 }
2649 else if (serialVersionOnStream >= 0)
2650 {
2651 for (int i=0; i<FIELD_COUNT; ++i)
2652 stamp[i] = isSet[i] ? COMPUTED : UNSET;
2653 }
2654
2655 serialVersionOnStream = currentSerialVersion;
2656
2657 // If there's a ZoneInfo object, use it for zone.
2658 try {
2659 ZoneInfo zi = (ZoneInfo) AccessController.doPrivileged(
2660 new PrivilegedExceptionAction() {
2661 public Object run() throws Exception {
2662 return input.readObject();
2663 }
2664 });
2665 if (zi != null) {
2666 zone = zi;
2667 }
2668 } catch (Exception e) {
2669 }
2670
2671 // If the deserialized object has a SimpleTimeZone, try to
2672 // replace it with a ZoneInfo equivalent (as of 1.4) in order
2673 // to be compatible with the SimpleTimeZone-based
2674 // implementation as much as possible.
2675 if (zone instanceof SimpleTimeZone) {
2676 String id = zone.getID();
2677 TimeZone zi = TimeZone.getTimeZone(id);
2678 if (zi != null && zi.hasSameRules(zone) && zi.getID().equals(id)) {
2679 zone = zi;
2680 }
2681 }
2682 }
2683 }