KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > util > Calendar


1 /*
2  * @(#)Calendar.java 1.81 04/07/26
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 /*
9  * (C) Copyright Taligent, Inc. 1996-1998 - All Rights Reserved
10  * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
11  *
12  * The original version of this source code and documentation is copyrighted
13  * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
14  * materials are provided under terms of a License Agreement between Taligent
15  * and Sun. This technology is protected by multiple US and International
16  * patents. This notice and attribution to Taligent may not be removed.
17  * Taligent is a registered trademark of Taligent, Inc.
18  *
19  */

20
21 package java.util;
22
23 import java.io.IOException JavaDoc;
24 import java.io.ObjectInputStream JavaDoc;
25 import java.io.ObjectOutputStream JavaDoc;
26 import java.io.Serializable JavaDoc;
27 import java.security.AccessController JavaDoc;
28 import java.security.PrivilegedExceptionAction JavaDoc;
29 import java.text.DateFormat JavaDoc;
30 import sun.text.resources.LocaleData;
31 import sun.util.BuddhistCalendar;
32 import sun.util.calendar.ZoneInfo;
33
34 /**
35  * The <code>Calendar</code> class is an abstract class that provides methods
36  * for converting between a specific instant in time and a set of {@link
37  * #fields calendar fields} such as <code>YEAR</code>, <code>MONTH</code>,
38  * <code>DAY_OF_MONTH</code>, <code>HOUR</code>, and so on, and for
39  * manipulating the calendar fields, such as getting the date of the next
40  * week. An instant in time can be represented by a millisecond value that is
41  * an offset from the <a name="Epoch"><em>Epoch</em></a>, January 1, 1970
42  * 00:00:00.000 GMT (Gregorian).
43  *
44  * <p>The class also provides additional fields and methods for
45  * implementing a concrete calendar system outside the package. Those
46  * fields and methods are defined as <code>protected</code>.
47  *
48  * <p>
49  * Like other locale-sensitive classes, <code>Calendar</code> provides a
50  * class method, <code>getInstance</code>, for getting a generally useful
51  * object of this type. <code>Calendar</code>'s <code>getInstance</code> method
52  * returns a <code>Calendar</code> object whose
53  * calendar fields have been initialized with the current date and time:
54  * <blockquote>
55  * <pre>
56  * Calendar rightNow = Calendar.getInstance();
57  * </pre>
58  * </blockquote>
59  *
60  * <p>A <code>Calendar</code> object can produce all the calendar field values
61  * needed to implement the date-time formatting for a particular language and
62  * calendar style (for example, Japanese-Gregorian, Japanese-Traditional).
63  * <code>Calendar</code> defines the range of values returned by
64  * certain calendar fields, as well as their meaning. For example,
65  * the first month of the calendar system has value <code>MONTH ==
66  * JANUARY</code> for all calendars. Other values are defined by the
67  * concrete subclass, such as <code>ERA</code>. See individual field
68  * documentation and subclass documentation for details.
69  *
70  * <h4>Getting and Setting Calendar Field Values</h4>
71  *
72  * <p>The calendar field values can be set by calling the <code>set</code>
73  * methods. Any field values set in a <code>Calendar</code> will not be
74  * interpreted until it needs to calculate its time value (milliseconds from
75  * the Epoch) or values of the calendar fields. Calling the
76  * <code>get</code>, <code>getTimeInMillis</code>, <code>getTime</code>,
77  * <code>add</code> and <code>roll</code> involves such calculation.
78  *
79  * <h4>Leniency</h4>
80  *
81  * <p><code>Calendar</code> has two modes for interpreting the calendar
82  * fields, <em>lenient</em> and <em>non-lenient</em>. When a
83  * <code>Calendar</code> is in lenient mode, it accepts a wider range of
84  * calendar field values than it produces. When a <code>Calendar</code>
85  * recomputes calendar field values for return by <code>get()</code>, all of
86  * the calendar fields are normalized. For example, a lenient
87  * <code>GregorianCalendar</code> interprets <code>MONTH == JANUARY</code>,
88  * <code>DAY_OF_MONTH == 32</code> as February 1.
89
90  * <p>When a <code>Calendar</code> is in non-lenient mode, it throws an
91  * exception if there is any inconsistency in its calendar fields. For
92  * example, a <code>GregorianCalendar</code> always produces
93  * <code>DAY_OF_MONTH</code> values between 1 and the length of the month. A
94  * non-lenient <code>GregorianCalendar</code> throws an exception upon
95  * calculating its time or calendar field values if any out-of-range field
96  * value has been set.
97  *
98  * <h4>First Week</h4>
99  *
100  * <code>Calendar</code> defines a locale-specific seven day week using two
101  * parameters: the first day of the week and the minimal days in first week
102  * (from 1 to 7). These numbers are taken from the locale resource data when a
103  * <code>Calendar</code> is constructed. They may also be specified explicitly
104  * through the methods for setting their values.
105  *
106  * <p>When setting or getting the <code>WEEK_OF_MONTH</code> or
107  * <code>WEEK_OF_YEAR</code> fields, <code>Calendar</code> must determine the
108  * first week of the month or year as a reference point. The first week of a
109  * month or year is defined as the earliest seven day period beginning on
110  * <code>getFirstDayOfWeek()</code> and containing at least
111  * <code>getMinimalDaysInFirstWeek()</code> days of that month or year. Weeks
112  * numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow
113  * it. Note that the normalized numbering returned by <code>get()</code> may be
114  * different. For example, a specific <code>Calendar</code> subclass may
115  * designate the week before week 1 of a year as week <code><i>n</i></code> of
116  * the previous year.
117  *
118  * <h4>Calendar Fields Resolution</h4>
119  *
120  * When computing a date and time from the calendar fields, there
121  * may be insufficient information for the computation (such as only
122  * year and month with no day of month), or there may be inconsistent
123  * information (such as Tuesday, July 15, 1996 (Gregorian) -- July 15,
124  * 1996 is actually a Monday). <code>Calendar</code> will resolve
125  * calendar field values to determine the date and time in the
126  * following way.
127  *
128  * <p>If there is any conflict in calendar field values,
129  * <code>Calendar</code> gives priorities to calendar fields that have been set
130  * more recently. The following are the default combinations of the
131  * calendar fields. The most recent combination, as determined by the
132  * most recently set single field, will be used.
133  *
134  * <p><a name="date_resolution">For the date fields</a>:
135  * <blockquote>
136  * <pre>
137  * YEAR + MONTH + DAY_OF_MONTH
138  * YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
139  * YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
140  * YEAR + DAY_OF_YEAR
141  * YEAR + DAY_OF_WEEK + WEEK_OF_YEAR
142  * </pre></blockquote>
143  *
144  * <a name="time_resolution">For the time of day fields</a>:
145  * <blockquote>
146  * <pre>
147  * HOUR_OF_DAY
148  * AM_PM + HOUR
149  * </pre></blockquote>
150  *
151  * <p>If there are any calendar fields whose values haven't been set in the selected
152  * field combination, <code>Calendar</code> uses their default values. The default
153  * value of each field may vary by concrete calendar systems. For example, in
154  * <code>GregorianCalendar</code>, the default of a field is the same as that
155  * of the start of the Epoch: i.e., <code>YEAR = 1970</code>, <code>MONTH =
156  * JANUARY</code>, <code>DAY_OF_MONTH = 1</code>, etc.
157  *
158  * <p>
159  * <strong>Note:</strong> There are certain possible ambiguities in
160  * interpretation of certain singular times, which are resolved in the
161  * following ways:
162  * <ol>
163  * <li> 23:59 is the last minute of the day and 00:00 is the first
164  * minute of the next day. Thus, 23:59 on Dec 31, 1999 &lt; 00:00 on
165  * Jan 1, 2000 &lt; 00:01 on Jan 1, 2000.
166  *
167  * <li> Although historically not precise, midnight also belongs to "am",
168  * and noon belongs to "pm", so on the same day,
169  * 12:00 am (midnight) &lt; 12:01 am, and 12:00 pm (noon) &lt; 12:01 pm
170  * </ol>
171  *
172  * <p>
173  * The date or time format strings are not part of the definition of a
174  * calendar, as those must be modifiable or overridable by the user at
175  * runtime. Use {@link DateFormat}
176  * to format dates.
177  *
178  * <h4>Field Manipulation</h4>
179  *
180  * The calendar fields can be changed using three methods:
181  * <code>set()</code>, <code>add()</code>, and <code>roll()</code>.</p>
182  *
183  * <p><strong><code>set(f, value)</code></strong> changes calendar field
184  * <code>f</code> to <code>value</code>. In addition, it sets an
185  * internal member variable to indicate that calendar field <code>f</code> has
186  * been changed. Although calendar field <code>f</code> is changed immediately,
187  * the calendar's time value in milliseconds is not recomputed until the next call to
188  * <code>get()</code>, <code>getTime()</code>, <code>getTimeInMillis()</code>,
189  * <code>add()</code>, or <code>roll()</code> is made. Thus, multiple calls to
190  * <code>set()</code> do not trigger multiple, unnecessary
191  * computations. As a result of changing a calendar field using
192  * <code>set()</code>, other calendar fields may also change, depending on the
193  * calendar field, the calendar field value, and the calendar system. In addition,
194  * <code>get(f)</code> will not necessarily return <code>value</code> set by
195  * the call to the <code>set</code> method
196  * after the calendar fields have been recomputed. The specifics are determined by
197  * the concrete calendar class.</p>
198  *
199  * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
200  * originally set to August 31, 1999. Calling <code>set(Calendar.MONTH,
201  * Calendar.SEPTEMBER)</code> sets the date to September 31,
202  * 1999. This is a temporary internal representation that resolves to
203  * October 1, 1999 if <code>getTime()</code>is then called. However, a
204  * call to <code>set(Calendar.DAY_OF_MONTH, 30)</code> before the call to
205  * <code>getTime()</code> sets the date to September 30, 1999, since
206  * no recomputation occurs after <code>set()</code> itself.</p>
207  *
208  * <p><strong><code>add(f, delta)</code></strong> adds <code>delta</code>
209  * to field <code>f</code>. This is equivalent to calling <code>set(f,
210  * get(f) + delta)</code> with two adjustments:</p>
211  *
212  * <blockquote>
213  * <p><strong>Add rule 1</strong>. The value of field <code>f</code>
214  * after the call minus the value of field <code>f</code> before the
215  * call is <code>delta</code>, modulo any overflow that has occurred in
216  * field <code>f</code>. Overflow occurs when a field value exceeds its
217  * range and, as a result, the next larger field is incremented or
218  * decremented and the field value is adjusted back into its range.</p>
219  *
220  * <p><strong>Add rule 2</strong>. If a smaller field is expected to be
221  * invariant, but it is impossible for it to be equal to its
222  * prior value because of changes in its minimum or maximum after field
223  * <code>f</code> is changed or other constraints, such as time zone
224  * offset changes, then its value is adjusted to be as close
225  * as possible to its expected value. A smaller field represents a
226  * smaller unit of time. <code>HOUR</code> is a smaller field than
227  * <code>DAY_OF_MONTH</code>. No adjustment is made to smaller fields
228  * that are not expected to be invariant. The calendar system
229  * determines what fields are expected to be invariant.</p>
230  * </blockquote>
231  *
232  * <p>In addition, unlike <code>set()</code>, <code>add()</code> forces
233  * an immediate recomputation of the calendar's milliseconds and all
234  * fields.</p>
235  *
236  * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
237  * originally set to August 31, 1999. Calling <code>add(Calendar.MONTH,
238  * 13)</code> sets the calendar to September 30, 2000. <strong>Add rule
239  * 1</strong> sets the <code>MONTH</code> field to September, since
240  * adding 13 months to August gives September of the next year. Since
241  * <code>DAY_OF_MONTH</code> cannot be 31 in September in a
242  * <code>GregorianCalendar</code>, <strong>add rule 2</strong> sets the
243  * <code>DAY_OF_MONTH</code> to 30, the closest possible value. Although
244  * it is a smaller field, <code>DAY_OF_WEEK</code> is not adjusted by
245  * rule 2, since it is expected to change when the month changes in a
246  * <code>GregorianCalendar</code>.</p>
247  *
248  * <p><strong><code>roll(f, delta)</code></strong> adds
249  * <code>delta</code> to field <code>f</code> without changing larger
250  * fields. This is equivalent to calling <code>add(f, delta)</code> with
251  * the following adjustment:</p>
252  *
253  * <blockquote>
254  * <p><strong>Roll rule</strong>. Larger fields are unchanged after the
255  * call. A larger field represents a larger unit of
256  * time. <code>DAY_OF_MONTH</code> is a larger field than
257  * <code>HOUR</code>.</p>
258  * </blockquote>
259  *
260  * <p><em>Example</em>: See {@link java.util.GregorianCalendar#roll(int, int)}.
261  *
262  * <p><strong>Usage model</strong>. To motivate the behavior of
263  * <code>add()</code> and <code>roll()</code>, consider a user interface
264  * component with increment and decrement buttons for the month, day, and
265  * year, and an underlying <code>GregorianCalendar</code>. If the
266  * interface reads January 31, 1999 and the user presses the month
267  * increment button, what should it read? If the underlying
268  * implementation uses <code>set()</code>, it might read March 3, 1999. A
269  * better result would be February 28, 1999. Furthermore, if the user
270  * presses the month increment button again, it should read March 31,
271  * 1999, not March 28, 1999. By saving the original date and using either
272  * <code>add()</code> or <code>roll()</code>, depending on whether larger
273  * fields should be affected, the user interface can behave as most users
274  * will intuitively expect.</p>
275  *
276  * @see java.lang.System#currentTimeMillis()
277  * @see Date
278  * @see GregorianCalendar
279  * @see TimeZone
280  * @see java.text.DateFormat
281  * @version 1.81, 07/26/04
282  * @author Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu
283  * @since JDK1.1
284  */

285 public abstract class Calendar implements Serializable JavaDoc, Cloneable JavaDoc, Comparable JavaDoc<Calendar JavaDoc> {
286
287     // Data flow in Calendar
288
// ---------------------
289

290     // The current time is represented in two ways by Calendar: as UTC
291
// milliseconds from the epoch (1 January 1970 0:00 UTC), and as local
292
// fields such as MONTH, HOUR, AM_PM, etc. It is possible to compute the
293
// millis from the fields, and vice versa. The data needed to do this
294
// conversion is encapsulated by a TimeZone object owned by the Calendar.
295
// The data provided by the TimeZone object may also be overridden if the
296
// user sets the ZONE_OFFSET and/or DST_OFFSET fields directly. The class
297
// keeps track of what information was most recently set by the caller, and
298
// uses that to compute any other information as needed.
299

300     // If the user sets the fields using set(), the data flow is as follows.
301
// This is implemented by the Calendar subclass's computeTime() method.
302
// During this process, certain fields may be ignored. The disambiguation
303
// algorithm for resolving which fields to pay attention to is described
304
// in the class documentation.
305

306     // local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
307
// |
308
// | Using Calendar-specific algorithm
309
// V
310
// local standard millis
311
// |
312
// | Using TimeZone or user-set ZONE_OFFSET / DST_OFFSET
313
// V
314
// UTC millis (in time data member)
315

316     // If the user sets the UTC millis using setTime() or setTimeInMillis(),
317
// the data flow is as follows. This is implemented by the Calendar
318
// subclass's computeFields() method.
319

320     // UTC millis (in time data member)
321
// |
322
// | Using TimeZone getOffset()
323
// V
324
// local standard millis
325
// |
326
// | Using Calendar-specific algorithm
327
// V
328
// local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
329

330     // In general, a round trip from fields, through local and UTC millis, and
331
// back out to fields is made when necessary. This is implemented by the
332
// complete() method. Resolving a partial set of fields into a UTC millis
333
// value allows all remaining fields to be generated from that value. If
334
// the Calendar is lenient, the fields are also renormalized to standard
335
// ranges when they are regenerated.
336

337     /**
338      * Field number for <code>get</code> and <code>set</code> indicating the
339      * era, e.g., AD or BC in the Julian calendar. This is a calendar-specific
340      * value; see subclass documentation.
341      *
342      * @see GregorianCalendar#AD
343      * @see GregorianCalendar#BC
344      */

345     public final static int ERA = 0;
346
347     /**
348      * Field number for <code>get</code> and <code>set</code> indicating the
349      * year. This is a calendar-specific value; see subclass documentation.
350      */

351     public final static int YEAR = 1;
352
353     /**
354      * Field number for <code>get</code> and <code>set</code> indicating the
355      * month. This is a calendar-specific value. The first month of the year is
356      * <code>JANUARY</code> which is 0; the last depends on the number of months in a year.
357      *
358      * @see #JANUARY
359      * @see #FEBRUARY
360      * @see #MARCH
361      * @see #APRIL
362      * @see #MAY
363      * @see #JUNE
364      * @see #JULY
365      * @see #AUGUST
366      * @see #SEPTEMBER
367      * @see #OCTOBER
368      * @see #NOVEMBER
369      * @see #DECEMBER
370      * @see #UNDECIMBER
371      */

372     public final static int MONTH = 2;
373
374     /**
375      * Field number for <code>get</code> and <code>set</code> indicating the
376      * week number within the current year. The first week of the year, as
377      * defined by <code>getFirstDayOfWeek()</code> and
378      * <code>getMinimalDaysInFirstWeek()</code>, has value 1. Subclasses define
379      * the value of <code>WEEK_OF_YEAR</code> for days before the first week of
380      * the year.
381      *
382      * @see #getFirstDayOfWeek
383      * @see #getMinimalDaysInFirstWeek
384      */

385     public final static int WEEK_OF_YEAR = 3;
386
387     /**
388      * Field number for <code>get</code> and <code>set</code> indicating the
389      * week number within the current month. The first week of the month, as
390      * defined by <code>getFirstDayOfWeek()</code> and
391      * <code>getMinimalDaysInFirstWeek()</code>, has value 1. Subclasses define
392      * the value of <code>WEEK_OF_MONTH</code> for days before the first week of
393      * the month.
394      *
395      * @see #getFirstDayOfWeek
396      * @see #getMinimalDaysInFirstWeek
397      */

398     public final static int WEEK_OF_MONTH = 4;
399
400     /**
401      * Field number for <code>get</code> and <code>set</code> indicating the
402      * day of the month. This is a synonym for <code>DAY_OF_MONTH</code>.
403      * The first day of the month has value 1.
404      *
405      * @see #DAY_OF_MONTH
406      */

407     public final static int DATE = 5;
408
409     /**
410      * Field number for <code>get</code> and <code>set</code> indicating the
411      * day of the month. This is a synonym for <code>DATE</code>.
412      * The first day of the month has value 1.
413      *
414      * @see #DATE
415      */

416     public final static int DAY_OF_MONTH = 5;
417
418     /**
419      * Field number for <code>get</code> and <code>set</code> indicating the day
420      * number within the current year. The first day of the year has value 1.
421      */

422     public final static int DAY_OF_YEAR = 6;
423
424     /**
425      * Field number for <code>get</code> and <code>set</code> indicating the day
426      * of the week. This field takes values <code>SUNDAY</code>,
427      * <code>MONDAY</code>, <code>TUESDAY</code>, <code>WEDNESDAY</code>,
428      * <code>THURSDAY</code>, <code>FRIDAY</code>, and <code>SATURDAY</code>.
429      *
430      * @see #SUNDAY
431      * @see #MONDAY
432      * @see #TUESDAY
433      * @see #WEDNESDAY
434      * @see #THURSDAY
435      * @see #FRIDAY
436      * @see #SATURDAY
437      */

438     public final static int DAY_OF_WEEK = 7;
439
440     /**
441      * Field number for <code>get</code> and <code>set</code> indicating the
442      * ordinal number of the day of the week within the current month. Together
443      * with the <code>DAY_OF_WEEK</code> field, this uniquely specifies a day
444      * within a month. Unlike <code>WEEK_OF_MONTH</code> and
445      * <code>WEEK_OF_YEAR</code>, this field's value does <em>not</em> depend on
446      * <code>getFirstDayOfWeek()</code> or
447      * <code>getMinimalDaysInFirstWeek()</code>. <code>DAY_OF_MONTH 1</code>
448      * through <code>7</code> always correspond to <code>DAY_OF_WEEK_IN_MONTH
449      * 1</code>; <code>8</code> through <code>14</code> correspond to
450      * <code>DAY_OF_WEEK_IN_MONTH 2</code>, and so on.
451      * <code>DAY_OF_WEEK_IN_MONTH 0</code> indicates the week before
452      * <code>DAY_OF_WEEK_IN_MONTH 1</code>. Negative values count back from the
453      * end of the month, so the last Sunday of a month is specified as
454      * <code>DAY_OF_WEEK = SUNDAY, DAY_OF_WEEK_IN_MONTH = -1</code>. Because
455      * negative values count backward they will usually be aligned differently
456      * within the month than positive values. For example, if a month has 31
457      * days, <code>DAY_OF_WEEK_IN_MONTH -1</code> will overlap
458      * <code>DAY_OF_WEEK_IN_MONTH 5</code> and the end of <code>4</code>.
459      *
460      * @see #DAY_OF_WEEK
461      * @see #WEEK_OF_MONTH
462      */

463     public final static int DAY_OF_WEEK_IN_MONTH = 8;
464
465     /**
466      * Field number for <code>get</code> and <code>set</code> indicating
467      * whether the <code>HOUR</code> is before or after noon.
468      * E.g., at 10:04:15.250 PM the <code>AM_PM</code> is <code>PM</code>.
469      *
470      * @see #AM
471      * @see #PM
472      * @see #HOUR
473      */

474     public final static int AM_PM = 9;
475
476     /**
477      * Field number for <code>get</code> and <code>set</code> indicating the
478      * hour of the morning or afternoon. <code>HOUR</code> is used for the
479      * 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12.
480      * E.g., at 10:04:15.250 PM the <code>HOUR</code> is 10.
481      *
482      * @see #AM_PM
483      * @see #HOUR_OF_DAY
484      */

485     public final static int HOUR = 10;
486
487     /**
488      * Field number for <code>get</code> and <code>set</code> indicating the
489      * hour of the day. <code>HOUR_OF_DAY</code> is used for the 24-hour clock.
490      * E.g., at 10:04:15.250 PM the <code>HOUR_OF_DAY</code> is 22.
491      *
492      * @see #HOUR
493      */

494     public final static int HOUR_OF_DAY = 11;
495
496     /**
497      * Field number for <code>get</code> and <code>set</code> indicating the
498      * minute within the hour.
499      * E.g., at 10:04:15.250 PM the <code>MINUTE</code> is 4.
500      */

501     public final static int MINUTE = 12;
502
503     /**
504      * Field number for <code>get</code> and <code>set</code> indicating the
505      * second within the minute.
506      * E.g., at 10:04:15.250 PM the <code>SECOND</code> is 15.
507      */

508     public final static int SECOND = 13;
509
510     /**
511      * Field number for <code>get</code> and <code>set</code> indicating the
512      * millisecond within the second.
513      * E.g., at 10:04:15.250 PM the <code>MILLISECOND</code> is 250.
514      */

515     public final static int MILLISECOND = 14;
516
517     /**
518      * Field number for <code>get</code> and <code>set</code>
519      * indicating the raw offset from GMT in milliseconds.
520      * <p>
521      * This field reflects the correct GMT offset value of the time
522      * zone of this <code>Calendar</code> if the
523      * <code>TimeZone</code> implementation subclass supports
524      * historical GMT offset changes.
525      */

526     public final static int ZONE_OFFSET = 15;
527
528     /**
529      * Field number for <code>get</code> and <code>set</code> indicating the
530      * daylight savings offset in milliseconds.
531      * <p>
532      * This field reflects the correct daylight saving offset value of
533      * the time zone of this <code>Calendar</code> if the
534      * <code>TimeZone</code> implementation subclass supports
535      * historical Daylight Saving Time schedule changes.
536      */

537     public final static int DST_OFFSET = 16;
538
539     /**
540      * The number of distinct fields recognized by <code>get</code> and <code>set</code>.
541      * Field numbers range from <code>0..FIELD_COUNT-1</code>.
542      */

543     public final static int FIELD_COUNT = 17;
544
545     /**
546      * Value of the {@link #DAY_OF_WEEK} field indicating
547      * Sunday.
548      */

549     public final static int SUNDAY = 1;
550
551     /**
552      * Value of the {@link #DAY_OF_WEEK} field indicating
553      * Monday.
554      */

555     public final static int MONDAY = 2;
556
557     /**
558      * Value of the {@link #DAY_OF_WEEK} field indicating
559      * Tuesday.
560      */

561     public final static int TUESDAY = 3;
562
563     /**
564      * Value of the {@link #DAY_OF_WEEK} field indicating
565      * Wednesday.
566      */

567     public final static int WEDNESDAY = 4;
568
569     /**
570      * Value of the {@link #DAY_OF_WEEK} field indicating
571      * Thursday.
572      */

573     public final static int THURSDAY = 5;
574
575     /**
576      * Value of the {@link #DAY_OF_WEEK} field indicating
577      * Friday.
578      */

579     public final static int FRIDAY = 6;
580
581     /**
582      * Value of the {@link #DAY_OF_WEEK} field indicating
583      * Saturday.
584      */

585     public final static int SATURDAY = 7;
586
587     /**
588      * Value of the {@link #MONTH} field indicating the
589      * first month of the year.
590      */

591     public final static int JANUARY = 0;
592
593     /**
594      * Value of the {@link #MONTH} field indicating the
595      * second month of the year.
596      */

597     public final static int FEBRUARY = 1;
598
599     /**
600      * Value of the {@link #MONTH} field indicating the
601      * third month of the year.
602      */

603     public final static int MARCH = 2;
604
605     /**
606      * Value of the {@link #MONTH} field indicating the
607      * fourth month of the year.
608      */

609     public final static int APRIL = 3;
610
611     /**
612      * Value of the {@link #MONTH} field indicating the
613      * fifth month of the year.
614      */

615     public final static int MAY = 4;
616
617     /**
618      * Value of the {@link #MONTH} field indicating the
619      * sixth month of the year.
620      */

621     public final static int JUNE = 5;
622
623     /**
624      * Value of the {@link #MONTH} field indicating the
625      * seventh month of the year.
626      */

627     public final static int JULY = 6;
628
629     /**
630      * Value of the {@link #MONTH} field indicating the
631      * eighth month of the year.
632      */

633     public final static int AUGUST = 7;
634
635     /**
636      * Value of the {@link #MONTH} field indicating the
637      * ninth month of the year.
638      */

639     public final static int SEPTEMBER = 8;
640
641     /**
642      * Value of the {@link #MONTH} field indicating the
643      * tenth month of the year.
644      */

645     public final static int OCTOBER = 9;
646
647     /**
648      * Value of the {@link #MONTH} field indicating the
649      * eleventh month of the year.
650      */

651     public final static int NOVEMBER = 10;
652
653     /**
654      * Value of the {@link #MONTH} field indicating the
655      * twelfth month of the year.
656      */

657     public final static int DECEMBER = 11;
658
659     /**
660      * Value of the {@link #MONTH} field indicating the
661      * thirteenth month of the year. Although <code>GregorianCalendar</code>
662      * does not use this value, lunar calendars do.
663      */

664     public final static int UNDECIMBER = 12;
665
666     /**
667      * Value of the {@link #AM_PM} field indicating the
668      * period of the day from midnight to just before noon.
669      */

670     public final static int AM = 0;
671
672     /**
673      * Value of the {@link #AM_PM} field indicating the
674      * period of the day from noon to just before midnight.
675      */

676     public final static int PM = 1;
677
678     // Internal notes:
679
// Calendar contains two kinds of time representations: current "time" in
680
// milliseconds, and a set of calendar "fields" representing the current time.
681
// The two representations are usually in sync, but can get out of sync
682
// as follows.
683
// 1. Initially, no fields are set, and the time is invalid.
684
// 2. If the time is set, all fields are computed and in sync.
685
// 3. If a single field is set, the time is invalid.
686
// Recomputation of the time and fields happens when the object needs
687
// to return a result to the user, or use a result for a computation.
688

689     /**
690      * The calendar field values for the currently set time for this calendar.
691      * This is an array of <code>FIELD_COUNT</code> integers, with index values
692      * <code>ERA</code> through <code>DST_OFFSET</code>.
693      * @serial
694      */

695     protected int fields[];
696
697     /**
698      * The flags which tell if a specified calendar field for the calendar is set.
699      * A new object has no fields set. After the first call to a method
700      * which generates the fields, they all remain set after that.
701      * This is an array of <code>FIELD_COUNT</code> booleans, with index values
702      * <code>ERA</code> through <code>DST_OFFSET</code>.
703      * @serial
704      */

705     protected boolean isSet[];
706
707     /**
708      * Pseudo-time-stamps which specify when each field was set. There
709      * are two special values, UNSET and COMPUTED. Values from
710      * MINIMUM_USER_SET to Integer.MAX_VALUE are legal user set values.
711      */

712     transient private int stamp[];
713
714     /**
715      * The currently set time for this calendar, expressed in milliseconds after
716      * January 1, 1970, 0:00:00 GMT.
717      * @see #isTimeSet
718      * @serial
719      */

720     protected long time;
721
722     /**
723      * True if then the value of <code>time</code> is valid.
724      * The time is made invalid by a change to an item of <code>field[]</code>.
725      * @see #time
726      * @serial
727      */

728     protected boolean isTimeSet;
729
730     /**
731      * True if <code>fields[]</code> are in sync with the currently set time.
732      * If false, then the next attempt to get the value of a field will
733      * force a recomputation of all fields from the current value of
734      * <code>time</code>.
735      * @serial
736      */

737     protected boolean areFieldsSet;
738
739     /**
740      * True if all fields have been set.
741      * @serial
742      */

743     transient boolean areAllFieldsSet;
744
745     /**
746      * <code>True</code> if this calendar allows out-of-range field values during computation
747      * of <code>time</code> from <code>fields[]</code>.
748      * @see #setLenient
749      * @see #isLenient
750      * @serial
751      */

752     private boolean lenient = true;
753
754     /**
755      * The <code>TimeZone</code> used by this calendar. <code>Calendar</code>
756      * uses the time zone data to translate between locale and GMT time.
757      * @serial
758      */

759     private TimeZone JavaDoc zone;
760
761     /**
762      * <code>True</code> if zone references to a shared TimeZone object.
763      */

764     transient private boolean sharedZone = false;
765
766     /**
767      * The first day of the week, with possible values <code>SUNDAY</code>,
768      * <code>MONDAY</code>, etc. This is a locale-dependent value.
769      * @serial
770      */

771     private int firstDayOfWeek;
772
773     /**
774      * The number of days required for the first week in a month or year,
775      * with possible values from 1 to 7. This is a locale-dependent value.
776      * @serial
777      */

778     private int minimalDaysInFirstWeek;
779
780     /**
781      * Cache to hold the firstDayOfWeek and minimalDaysInFirstWeek
782      * of a Locale.
783      */

784     private static Hashtable JavaDoc<Locale JavaDoc, int[]> cachedLocaleData = new Hashtable JavaDoc<Locale JavaDoc, int[]>(3);
785
786     // Special values of stamp[]
787
/**
788      * The corresponding fields[] has no value.
789      */

790     private static final int UNSET = 0;
791
792     /**
793      * The value of the corresponding fields[] has been calculated internally.
794      */

795     private static final int COMPUTED = 1;
796
797     /**
798      * The value of the corresponding fields[] has been set externally. Stamp
799      * values which are greater than 1 represents the (pseudo) time when the
800      * corresponding fields[] value was set.
801      */

802     private static final int MINIMUM_USER_STAMP = 2;
803
804     /**
805      * The mask value that represents all of the fields.
806      */

807     static final int ALL_FIELDS = (1 << FIELD_COUNT) - 1;
808
809     /**
810      * The next available value for <code>stamp[]</code>, an internal array.
811      * This actually should not be written out to the stream, and will probably
812      * be removed from the stream in the near future. In the meantime,
813      * a value of <code>MINIMUM_USER_STAMP</code> should be used.
814      * @serial
815      */

816     private int nextStamp = MINIMUM_USER_STAMP;
817
818     // the internal serial version which says which version was written
819
// - 0 (default) for version up to JDK 1.1.5
820
// - 1 for version from JDK 1.1.6, which writes a correct 'time' value
821
// as well as compatible values for other fields. This is a
822
// transitional format.
823
// - 2 (not implemented yet) a future version, in which fields[],
824
// areFieldsSet, and isTimeSet become transient, and isSet[] is
825
// removed. In JDK 1.1.6 we write a format compatible with version 2.
826
static final int currentSerialVersion = 1;
827     
828     /**
829      * The version of the serialized data on the stream. Possible values:
830      * <dl>
831      * <dt><b>0</b> or not present on stream</dt>
832      * <dd>
833      * JDK 1.1.5 or earlier.
834      * </dd>
835      * <dt><b>1</b></dt>
836      * <dd>
837      * JDK 1.1.6 or later. Writes a correct 'time' value
838      * as well as compatible values for other fields. This is a
839      * transitional format.
840      * </dd>
841      * </dl>
842      * When streaming out this class, the most recent format
843      * and the highest allowable <code>serialVersionOnStream</code>
844      * is written.
845      * @serial
846      * @since JDK1.1.6
847      */

848     private int serialVersionOnStream = currentSerialVersion;
849
850     // Proclaim serialization compatibility with JDK 1.1
851
static final long serialVersionUID = -1807547505821590642L;
852
853     // Mask values for calendar fields
854
final static int ERA_MASK = (1 << ERA);
855     final static int YEAR_MASK = (1 << YEAR);
856     final static int MONTH_MASK = (1 << MONTH);
857     final static int WEEK_OF_YEAR_MASK = (1 << WEEK_OF_YEAR);
858     final static int WEEK_OF_MONTH_MASK = (1 << WEEK_OF_MONTH);
859     final static int DAY_OF_MONTH_MASK = (1 << DAY_OF_MONTH);
860     final static int DATE_MASK = DAY_OF_MONTH_MASK;
861     final static int DAY_OF_YEAR_MASK = (1 << DAY_OF_YEAR);
862     final static int DAY_OF_WEEK_MASK = (1 << DAY_OF_WEEK);
863     final static int DAY_OF_WEEK_IN_MONTH_MASK = (1 << DAY_OF_WEEK_IN_MONTH);
864     final static int AM_PM_MASK = (1 << AM_PM);
865     final static int HOUR_MASK = (1 << HOUR);
866     final static int HOUR_OF_DAY_MASK = (1 << HOUR_OF_DAY);
867     final static int MINUTE_MASK = (1 << MINUTE);
868     final static int SECOND_MASK = (1 << SECOND);
869     final static int MILLISECOND_MASK = (1 << MILLISECOND);
870     final static int ZONE_OFFSET_MASK = (1 << ZONE_OFFSET);
871     final static int DST_OFFSET_MASK = (1 << DST_OFFSET);
872
873     /**
874      * Constructs a Calendar with the default time zone
875      * and locale.
876      * @see TimeZone#getDefault
877      */

878     protected Calendar()
879     {
880         this(TimeZone.getDefaultRef(), Locale.getDefault());
881     sharedZone = true;
882     }
883
884     /**
885      * Constructs a calendar with the specified time zone and locale.
886      *
887      * @param zone the time zone to use
888      * @param aLocale the locale for the week data
889      */

890     protected Calendar(TimeZone JavaDoc zone, Locale JavaDoc aLocale)
891     {
892         fields = new int[FIELD_COUNT];
893         isSet = new boolean[FIELD_COUNT];
894         stamp = new int[FIELD_COUNT];
895
896         this.zone = zone;
897         setWeekCountData(aLocale);
898     }
899
900     /**
901      * Gets a calendar using the default time zone and locale. The
902      * <code>Calendar</code> returned is based on the current time
903      * in the default time zone with the default locale.
904      *
905      * @return a Calendar.
906      */

907     public static Calendar JavaDoc getInstance()
908     {
909         Calendar JavaDoc cal = createCalendar(TimeZone.getDefaultRef(), Locale.getDefault());
910     cal.sharedZone = true;
911     return cal;
912     }
913
914     /**
915      * Gets a calendar using the specified time zone and default locale.
916      * The <code>Calendar</code> returned is based on the current time
917      * in the given time zone with the default locale.
918      *
919      * @param zone the time zone to use
920      * @return a Calendar.
921      */

922     public static Calendar JavaDoc getInstance(TimeZone JavaDoc zone)
923     {
924         return createCalendar(zone, Locale.getDefault());
925     }
926
927     /**
928      * Gets a calendar using the default time zone and specified locale.
929      * The <code>Calendar</code> returned is based on the current time
930      * in the default time zone with the given locale.
931      *
932      * @param aLocale the locale for the week data
933      * @return a Calendar.
934      */

935     public static Calendar JavaDoc getInstance(Locale JavaDoc aLocale)
936     {
937         Calendar JavaDoc cal = createCalendar(TimeZone.getDefaultRef(), aLocale);
938     cal.sharedZone = true;
939     return cal;
940     }
941
942     /**
943      * Gets a calendar with the specified time zone and locale.
944      * The <code>Calendar</code> returned is based on the current time
945      * in the given time zone with the given locale.
946      *
947      * @param zone the time zone to use
948      * @param aLocale the locale for the week data
949      * @return a Calendar.
950      */

951     public static Calendar JavaDoc getInstance(TimeZone JavaDoc zone,
952                        Locale JavaDoc aLocale)
953     {
954     return createCalendar(zone, aLocale);
955     }
956
957     private static Calendar JavaDoc createCalendar(TimeZone JavaDoc zone,
958                        Locale JavaDoc aLocale)
959     {
960     // If the specified locale is a Thai locale, returns a BuddhistCalendar
961
// instance.
962
if ("th".equals(aLocale.getLanguage())
963         && ("TH".equals(aLocale.getCountry()))) {
964         return new sun.util.BuddhistCalendar(zone, aLocale);
965     }
966
967     // else create the default calendar
968
return new GregorianCalendar JavaDoc(zone, aLocale);
969     }
970
971     /**
972      * Returns an array of all locales for which the <code>getInstance</code>
973      * methods of this class can return localized instances.
974      * The array returned must contain at least a <code>Locale</code>
975      * instance equal to {@link java.util.Locale#US Locale.US}.
976      *
977      * @return An array of locales for which localized
978      * <code>Calendar</code> instances are available.
979      */

980     public static synchronized Locale JavaDoc[] getAvailableLocales()
981     {
982         return DateFormat.getAvailableLocales();
983     }
984
985     /**
986      * Converts the current calendar field values in {@link #fields fields[]}
987      * to the millisecond time value
988      * {@link #time}.
989      *
990      * @see #complete()
991      * @see #computeFields()
992      */

993     protected abstract void computeTime();
994
995     /**
996      * Converts the current millisecond time value {@link #time}
997      * to calendar field values in {@link #fields fields[]}.
998      * This allows you to sync up the calendar field values with
999      * a new time that is set for the calendar. The time is <em>not</em>
1000     * recomputed first; to recompute the time, then the fields, call the
1001     * {@link #complete()} method.
1002     *
1003     * @see #computeTime()
1004     */

1005    protected abstract void computeFields();
1006
1007    /**
1008     * Returns a <code>Date</code> object representing this
1009     * <code>Calendar</code>'s time value (millisecond offset from the <a
1010     * HREF="#Epoch">Epoch</a>").
1011     *
1012     * @return a <code>Date</code> representing the time value.
1013     * @see #setTime(Date)
1014     * @see #getTimeInMillis()
1015     */

1016    public final Date JavaDoc getTime() {
1017        return new Date JavaDoc(getTimeInMillis());
1018    }
1019
1020    /**
1021     * Sets this Calendar's time with the given <code>Date</code>.
1022     * <p>
1023     * Note: Calling <code>setTime()</code> with
1024     * <code>Date(Long.MAX_VALUE)</code> or <code>Date(Long.MIN_VALUE)</code>
1025     * may yield incorrect field values from <code>get()</code>.
1026     *
1027     * @param date the given Date.
1028     * @see #getTime()
1029     * @see #setTimeInMillis(long)
1030     */

1031    public final void setTime(Date JavaDoc date) {
1032        setTimeInMillis(date.getTime());
1033    }
1034
1035    /**
1036     * Returns this Calendar's time value in milliseconds.
1037     *
1038     * @return the current time as UTC milliseconds from the epoch.
1039     * @see #getTime()
1040     * @see #setTimeInMillis(long)
1041     */

1042    public long getTimeInMillis() {
1043        if (!isTimeSet) {
1044        updateTime();
1045    }
1046        return time;
1047    }
1048
1049    /**
1050     * Sets this Calendar's current time from the given long value.
1051     *
1052     * @param millis the new time in UTC milliseconds from the epoch.
1053     * @see #setTime(Date)
1054     * @see #getTimeInMillis()
1055     */

1056    public void setTimeInMillis(long millis) {
1057    // If we don't need to recalculate the calendar field values,
1058
// do nothing.
1059
if (time == millis && isTimeSet && areFieldsSet && areAllFieldsSet
1060        && (zone instanceof ZoneInfo) && !((ZoneInfo)zone).isDirty()) {
1061        return;
1062    }
1063        time = millis;
1064        isTimeSet = true;
1065        areFieldsSet = false;
1066    computeFields();
1067        areAllFieldsSet = areFieldsSet = true;
1068    }
1069
1070    /**
1071     * Returns the value of the given calendar field. In lenient mode,
1072     * all calendar fields are normalized. In non-lenient mode, all
1073     * calendar fields are validated and this method throws an
1074     * exception if any calendar fields have out-of-range values. The
1075     * normalization and validation are handled by the
1076     * {@link #complete()} method, which process is calendar
1077     * system dependent.
1078     *
1079     * @param field the given calendar field.
1080     * @return the value for the given calendar field.
1081     * @throws ArrayIndexOutOfBoundsException if the specified field is out of range
1082     * (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
1083     * @see #set(int,int)
1084     * @see #complete()
1085     */

1086    public int get(int field)
1087    {
1088        complete();
1089    return internalGet(field);
1090    }
1091
1092    /**
1093     * Returns the value of the given calendar field. This method does
1094     * not involve normalization or validation of the field value.
1095     *
1096     * @param field the given calendar field.
1097     * @return the value for the given calendar field.
1098     * @see #get(int)
1099     */

1100    protected final int internalGet(int field)
1101    {
1102        return fields[field];
1103    }
1104
1105    /**
1106     * Sets the value of the given calendar field. This method does
1107     * not affect any setting state of the field in this
1108     * <code>Calendar</code> instance.
1109     *
1110     * @throws IndexOutOfBoundsException if the specified field is out of range
1111     * (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
1112     * @see #areFieldsSet
1113     * @see #isTimeSet
1114     * @see #areAllFieldsSet
1115     * @see #set(int,int)
1116     */

1117    final void internalSet(int field, int value)
1118    {
1119        fields[field] = value;
1120    }
1121
1122    /**
1123     * Sets the given calendar field to the given value. The value is not
1124     * interpreted by this method regardless of the leniency mode.
1125     *
1126     * @param field the given calendar field.
1127     * @param value the value to be set for the given calendar field.
1128     * @throws ArrayIndexOutOfBoundsException if the specified field is out of range
1129     * (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
1130     * in non-lenient mode.
1131     * @see #set(int,int,int)
1132     * @see #set(int,int,int,int,int)
1133     * @see #set(int,int,int,int,int,int)
1134     * @see #get(int)
1135     */

1136    public void set(int field, int value)
1137    {
1138    if (isLenient() && areFieldsSet && !areAllFieldsSet) {
1139        computeFields();
1140    }
1141    internalSet(field, value);
1142        isTimeSet = false;
1143    areFieldsSet = false;
1144        isSet[field] = true;
1145        stamp[field] = nextStamp++;
1146    if (nextStamp == Integer.MAX_VALUE) {
1147        adjustStamp();
1148    }
1149    }
1150
1151    /**
1152     * Sets the values for the calendar fields <code>YEAR</code>,
1153     * <code>MONTH</code>, and <code>DAY_OF_MONTH</code>.
1154     * Previous values of other calendar fields are retained. If this is not desired,
1155     * call {@link #clear()} first.
1156     *
1157     * @param year the value used to set the <code>YEAR</code> calendar field.
1158     * @param month the value used to set the <code>MONTH</code> calendar field.
1159     * Month value is 0-based. e.g., 0 for January.
1160     * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
1161     * @see #set(int,int)
1162     * @see #set(int,int,int,int,int)
1163     * @see #set(int,int,int,int,int,int)
1164     */

1165    public final void set(int year, int month, int date)
1166    {
1167        set(YEAR, year);
1168        set(MONTH, month);
1169        set(DATE, date);
1170    }
1171
1172    /**
1173     * Sets the values for the calendar fields <code>YEAR</code>,
1174     * <code>MONTH</code>, <code>DAY_OF_MONTH</code>,
1175     * <code>HOUR_OF_DAY</code>, and <code>MINUTE</code>.
1176     * Previous values of other fields are retained. If this is not desired,
1177     * call {@link #clear()} first.
1178     *
1179     * @param year the value used to set the <code>YEAR</code> calendar field.
1180     * @param month the value used to set the <code>MONTH</code> calendar field.
1181     * Month value is 0-based. e.g., 0 for January.
1182     * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
1183     * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field.
1184     * @param minute the value used to set the <code>MINUTE</code> calendar field.
1185     * @see #set(int,int)
1186     * @see #set(int,int,int)
1187     * @see #set(int,int,int,int,int,int)
1188     */

1189    public final void set(int year, int month, int date, int hourOfDay, int minute)
1190    {
1191        set(YEAR, year);
1192        set(MONTH, month);
1193        set(DATE, date);
1194        set(HOUR_OF_DAY, hourOfDay);
1195        set(MINUTE, minute);
1196    }
1197
1198    /**
1199     * Sets the values for the fields <code>YEAR</code>, <code>MONTH</code>,
1200     * <code>DAY_OF_MONTH</code>, <code>HOUR</code>, <code>MINUTE</code>, and
1201     * <code>SECOND</code>.
1202     * Previous values of other fields are retained. If this is not desired,
1203     * call {@link #clear()} first.
1204     *
1205     * @param year the value used to set the <code>YEAR</code> calendar field.
1206     * @param month the value used to set the <code>MONTH</code> calendar field.
1207     * Month value is 0-based. e.g., 0 for January.
1208     * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
1209     * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field.
1210     * @param minute the value used to set the <code>MINUTE</code> calendar field.
1211     * @param second the value used to set the <code>SECOND</code> calendar field.
1212     * @see #set(int,int)
1213     * @see #set(int,int,int)
1214     * @see #set(int,int,int,int,int)
1215     */

1216    public final void set(int year, int month, int date, int hourOfDay, int minute,
1217                          int second)
1218    {
1219        set(YEAR, year);
1220        set(MONTH, month);
1221        set(DATE, date);
1222        set(HOUR_OF_DAY, hourOfDay);
1223        set(MINUTE, minute);
1224        set(SECOND, second);
1225    }
1226
1227    /**
1228     * Sets all the calendar field values and the time value
1229     * (millisecond offset from the <a HREF="#Epoch">Epoch</a>) of
1230     * this <code>Calendar</code> undefined. This means that {@link
1231     * #isSet(int) isSet()} will return <code>false</code> for all the
1232     * calendar fields, and the date and time calculations will treat
1233     * the fields as if they had never been set. A
1234     * <code>Calendar</code> implementation class may use its specific
1235     * default field values for date/time calculations. For example,
1236     * <code>GregorianCalendar</code> uses 1970 if the
1237     * <code>YEAR</code> field value is undefined.
1238     *
1239     * @see #clear(int)
1240     */

1241    public final void clear()
1242    {
1243    for (int i = 0; i < fields.length; ) {
1244        stamp[i] = fields[i] = 0; // UNSET == 0
1245
isSet[i++] = false;
1246    }
1247        areAllFieldsSet = areFieldsSet = false;
1248        isTimeSet = false;
1249    }
1250
1251    /**
1252     * Sets the given calendar field value and the time value
1253     * (millisecond offset from the <a HREF="#Epoch">Epoch</a>) of
1254     * this <code>Calendar</code> undefined. This means that {@link
1255     * #isSet(int) isSet(field)} will return <code>false</code>, and
1256     * the date and time calculations will treat the field as if it
1257     * had never been set. A <code>Calendar</code> implementation
1258     * class may use the field's specific default value for date and
1259     * time calculations.
1260     *
1261     * <p>The {@link #HOUR_OF_DAY}, {@link #HOUR} and {@link #AM_PM}
1262     * fields are handled independently and the <a
1263     * HREF="#time_resolution">the resolution rule for the time of
1264     * day</a> is applied. Clearing one of the fields doesn't reset
1265     * the hour of day value of this <code>Calendar</code>. Use {@link
1266     * #set(int,int) set(Calendar.HOUR_OF_DAY, 0)} to reset the hour
1267     * value.
1268     *
1269     * @param field the calendar field to be cleared.
1270     * @see #clear()
1271     */

1272    public final void clear(int field)
1273    {
1274    fields[field] = 0;
1275    stamp[field] = UNSET;
1276    isSet[field] = false;
1277
1278    areAllFieldsSet = areFieldsSet = false;
1279    isTimeSet = false;
1280    }
1281
1282    /**
1283     * Determines if the given calendar field has a value set,
1284     * including cases that the value has been set by internal fields
1285     * calculations triggered by a <code>get</code> method call.
1286     *
1287     * @return <code>true</code> if the given calendar field has a value set;
1288     * <code>false</code> otherwise.
1289     */

1290    public final boolean isSet(int field)
1291    {
1292        return stamp[field] != UNSET;
1293    }
1294
1295    /**
1296     * Fills in any unset fields in the calendar fields. First, the {@link
1297     * #computeTime()} method is called if the time value (millisecond offset
1298     * from the <a HREF="#Epoch">Epoch</a>) has not been calculated from
1299     * calendar field values. Then, the {@link #computeFields()} method is
1300     * called to calculate all calendar field values.
1301     */

1302    protected void complete()
1303    {
1304        if (!isTimeSet)
1305        updateTime();
1306        if (!areFieldsSet || !areAllFieldsSet) {
1307            computeFields(); // fills in unset fields
1308
areAllFieldsSet = areFieldsSet = true;
1309        } else {
1310        // When a computeTime() call happens to calculate all the
1311
// fields, stamp[] are not modified to preserve what the
1312
// application has set. We need to normalize all stamp
1313
// elements to COMPUTED here. (5078053)
1314
setFieldsComputed(ALL_FIELDS);
1315    }
1316    }
1317
1318    /**
1319     * Returns whether the value of the specified calendar field has been set
1320     * externally by calling one of the setter methods rather than by the
1321     * internal time calculation.
1322     *
1323     * @return <code>true</code> if the field has been set externally,
1324     * <code>false</code> otherwise.
1325     * @exception IndexOutOfBoundsException if the specified
1326     * <code>field</code> is out of range
1327     * (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
1328     * @see #selectFields()
1329     * @see #setFieldsComputed(int)
1330     */

1331    final boolean isExternallySet(int field) {
1332    return stamp[field] >= MINIMUM_USER_STAMP;
1333    }
1334
1335    /**
1336     * Returns a field mask (bit mask) indicating all calendar fields that
1337     * have the state of externally or internally set.
1338     *
1339     * @return a bit mask indicating set state fields
1340     */

1341    final int getSetStateFields() {
1342    int mask = 0;
1343    for (int i = 0; i < fields.length; i++) {
1344        if (stamp[i] != UNSET) {
1345        mask |= 1 << i;
1346        }
1347    }
1348    return mask;
1349    }
1350
1351    /**
1352     * Sets the state of the specified calendar fields to
1353     * <em>computed</em>. This state means that the specified calendar fields
1354     * have valid values that have been set by internal time calculation
1355     * rather than by calling one of the setter methods.
1356     *
1357     * @param fieldMask the field to be marked as computed.
1358     * @exception IndexOutOfBoundsException if the specified
1359     * <code>field</code> is out of range
1360     * (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
1361     * @see #isExternallySet(int)
1362     * @see #selectFields()
1363     */

1364    final void setFieldsComputed(int fieldMask) {
1365    if (fieldMask == ALL_FIELDS) {
1366        for (int i = 0; i < fields.length; i++) {
1367        stamp[i] = COMPUTED;
1368        isSet[i] = true;
1369        }
1370        areFieldsSet = areAllFieldsSet = true;
1371    } else {
1372        for (int i = 0; i < fields.length; i++) {
1373        if ((fieldMask & 1) == 1) {
1374            stamp[i] = COMPUTED;
1375            isSet[i] = true;
1376        } else {
1377            if (areAllFieldsSet && !isSet[i]) {
1378            areAllFieldsSet = false;
1379            }
1380        }
1381        fieldMask >>>= 1;
1382        }
1383    }
1384    }
1385
1386    /**
1387     * Sets the state of the calendar fields that are <em>not</em> specified
1388     * by <code>fieldMask</code> to <em>unset</em>. If <code>fieldMask</code>
1389     * specifies all the calendar fields, then the state of this
1390     * <code>Calendar</code> becomes that all the calendar fields are in sync
1391     * with the time value (millisecond offset from the Epoch).
1392     *
1393     * @param fieldMask the field mask indicating which calendar fields are in
1394     * sync with the time value.
1395     * @exception IndexOutOfBoundsException if the specified
1396     * <code>field</code> is out of range
1397     * (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
1398     * @see #isExternallySet(int)
1399     * @see #selectFields()
1400     */

1401    final void setFieldsNormalized(int fieldMask) {
1402    if (fieldMask == ALL_FIELDS) {
1403        // all calendar fields are in sync with the time value
1404
areFieldsSet = areAllFieldsSet = true;
1405        return;
1406    }
1407
1408    for (int i = 0; i < fields.length; i++) {
1409        if ((fieldMask & 1) == 0) {
1410        stamp[i] = fields[i] = 0; // UNSET == 0
1411
isSet[i] = false;
1412        }
1413        fieldMask >>= 1;
1414    }
1415
1416    // Some fields are in sync with the milliseconds, but not all
1417
// fields have been calculated.
1418
areFieldsSet = true;
1419    areAllFieldsSet = false;
1420    }
1421
1422    /**
1423     * Returns whether the calendar fields are partially in sync with the time
1424     * value.
1425     */

1426    final boolean isPartiallyNormalized() {
1427    return areFieldsSet && !areAllFieldsSet;
1428    }
1429
1430    /**
1431     * Returns whether the calendar fields are fully in sync with the time
1432     * value.
1433     */

1434    final boolean isFullyNormalized() {
1435    return areFieldsSet && areAllFieldsSet;
1436    }
1437
1438    /**
1439     * Marks this Calendar as not sync'd.
1440     */

1441    final void setUnnormalized() {
1442    areFieldsSet = areAllFieldsSet = false;
1443    }
1444
1445    /**
1446     * Returns whether the specified <code>field</code> is on in the
1447     * <code>fieldMask</code>.
1448     */

1449    static final boolean isFieldSet(int fieldMask, int field) {
1450    return (fieldMask & (1 << field)) != 0;
1451    }
1452
1453    /**
1454     * Returns a field mask indicating which calendar field values
1455     * to be used to calculate the time value. The calendar fields are
1456     * returned as a bit mask, each bit of which corresponds to a field, i.e.,
1457     * the mask value of <code>field</code> is <code>(1 &lt;&lt;
1458     * field)</code>. For example, 0x26 represents the <code>YEAR</code>,
1459     * <code>MONTH</code>, and <code>DAY_OF_MONTH</code> fields (i.e., 0x26 is
1460     * equal to
1461     * <code>(1&lt;&lt;YEAR)|(1&lt;&lt;MONTH)|(1&lt;&lt;DAY_OF_MONTH))</code>.
1462     *
1463     * <p>This method supports the calendar fields resolution as described in
1464     * the class description. If the bit mask for a given field is on and its
1465     * field has not been set (i.e., <code>isSet(field)</code> is
1466     * <code>false</code>), then the default value of the field has to be
1467     * used, which case means that the field has been selected because the
1468     * selected combination involves the field.
1469     *
1470     * @return a bit mask of selected fields
1471     * @see #isExternallySet(int)
1472     * @see #setInternallySetState(int)
1473     */

1474    final int selectFields() {
1475    // This implementation has been taken from the GregorianCalendar class.
1476

1477    // The YEAR field must always be used regardless of its SET
1478
// state because YEAR is a mandatory field to determine the date
1479
// and the default value (EPOCH_YEAR) may change through the
1480
// normalization process.
1481
int fieldMask = YEAR_MASK;
1482
1483    if (stamp[ERA] != UNSET) {
1484        fieldMask |= ERA_MASK;
1485    }
1486        // Find the most recent group of fields specifying the day within
1487
// the year. These may be any of the following combinations:
1488
// MONTH + DAY_OF_MONTH
1489
// MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
1490
// MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
1491
// DAY_OF_YEAR
1492
// WEEK_OF_YEAR + DAY_OF_WEEK
1493
// We look for the most recent of the fields in each group to determine
1494
// the age of the group. For groups involving a week-related field such
1495
// as WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR, both the
1496
// week-related field and the DAY_OF_WEEK must be set for the group as a
1497
// whole to be considered. (See bug 4153860 - liu 7/24/98.)
1498
int dowStamp = stamp[DAY_OF_WEEK];
1499        int monthStamp = stamp[MONTH];
1500        int domStamp = stamp[DAY_OF_MONTH];
1501        int womStamp = aggregateStamp(stamp[WEEK_OF_MONTH], dowStamp);
1502        int dowimStamp = aggregateStamp(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
1503        int doyStamp = stamp[DAY_OF_YEAR];
1504        int woyStamp = aggregateStamp(stamp[WEEK_OF_YEAR], dowStamp);
1505
1506        int bestStamp = domStamp;
1507        if (womStamp > bestStamp) {
1508        bestStamp = womStamp;
1509    }
1510        if (dowimStamp > bestStamp) {
1511        bestStamp = dowimStamp;
1512    }
1513        if (doyStamp > bestStamp) {
1514        bestStamp = doyStamp;
1515    }
1516        if (woyStamp > bestStamp) {
1517        bestStamp = woyStamp;
1518    }
1519
1520        /* No complete combination exists. Look for WEEK_OF_MONTH,
1521         * DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR alone. Treat DAY_OF_WEEK alone
1522         * as DAY_OF_WEEK_IN_MONTH.
1523         */

1524        if (bestStamp == UNSET) {
1525            womStamp = stamp[WEEK_OF_MONTH];
1526            dowimStamp = Math.max(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
1527            woyStamp = stamp[WEEK_OF_YEAR];
1528            bestStamp = Math.max(Math.max(womStamp, dowimStamp), woyStamp);
1529
1530            /* Treat MONTH alone or no fields at all as DAY_OF_MONTH. This may
1531             * result in bestStamp = domStamp = UNSET if no fields are set,
1532             * which indicates DAY_OF_MONTH.
1533             */

1534            if (bestStamp == UNSET) {
1535                bestStamp = domStamp = monthStamp;
1536            }
1537        }
1538
1539        if (bestStamp == domStamp ||
1540           (bestStamp == womStamp && stamp[WEEK_OF_MONTH] >= stamp[WEEK_OF_YEAR]) ||
1541           (bestStamp == dowimStamp && stamp[DAY_OF_WEEK_IN_MONTH] >= stamp[WEEK_OF_YEAR])) {
1542        fieldMask |= MONTH_MASK;
1543            if (bestStamp == domStamp) {
1544        fieldMask |= DAY_OF_MONTH_MASK;
1545            } else {
1546        assert (bestStamp == womStamp || bestStamp == dowimStamp);
1547                if (dowStamp != UNSET) {
1548            fieldMask |= DAY_OF_WEEK_MASK;
1549                }
1550                if (bestStamp == womStamp) {
1551            fieldMask |= WEEK_OF_MONTH_MASK;
1552                } else {
1553            assert (bestStamp == dowimStamp);
1554            if (stamp[DAY_OF_WEEK_IN_MONTH] != UNSET) {
1555            fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK;
1556            }
1557        }
1558        }
1559        } else {
1560            assert (bestStamp == doyStamp || bestStamp == woyStamp ||
1561            bestStamp == UNSET);
1562            if (bestStamp == doyStamp) {
1563        fieldMask |= DAY_OF_YEAR_MASK;
1564            } else {
1565        assert (bestStamp == woyStamp);
1566                if (dowStamp != UNSET) {
1567            fieldMask |= DAY_OF_WEEK_MASK;
1568                }
1569        fieldMask |= WEEK_OF_YEAR_MASK;
1570        }
1571    }
1572
1573        // Find the best set of fields specifying the time of day. There
1574
// are only two possibilities here; the HOUR_OF_DAY or the
1575
// AM_PM and the HOUR.
1576
int hourOfDayStamp = stamp[HOUR_OF_DAY];
1577        int hourStamp = aggregateStamp(stamp[HOUR], stamp[AM_PM]);
1578        bestStamp = (hourStamp > hourOfDayStamp) ? hourStamp : hourOfDayStamp;
1579
1580    // if bestStamp is still UNSET, then take HOUR or AM_PM. (See 4846659)
1581
if (bestStamp == UNSET) {
1582        bestStamp = Math.max(stamp[HOUR], stamp[AM_PM]);
1583    }
1584
1585        // Hours
1586
if (bestStamp != UNSET) {
1587            if (bestStamp == hourOfDayStamp) {
1588        fieldMask |= HOUR_OF_DAY_MASK;
1589            } else {
1590        fieldMask |= HOUR_MASK;
1591        if (stamp[AM_PM] != UNSET) {
1592            fieldMask |= AM_PM_MASK;
1593        }
1594            }
1595        }
1596    if (stamp[MINUTE] != UNSET) {
1597        fieldMask |= MINUTE_MASK;
1598    }
1599    if (stamp[SECOND] != UNSET) {
1600        fieldMask |= SECOND_MASK;
1601    }
1602    if (stamp[MILLISECOND] != UNSET) {
1603        fieldMask |= MILLISECOND_MASK;
1604    }
1605    if (stamp[ZONE_OFFSET] >= MINIMUM_USER_STAMP) {
1606        fieldMask |= ZONE_OFFSET_MASK;
1607    }
1608    if (stamp[DST_OFFSET] >= MINIMUM_USER_STAMP) {
1609        fieldMask |= DST_OFFSET_MASK;
1610    }
1611
1612    return fieldMask;
1613    }
1614
1615    /**
1616     * Returns the pseudo-time-stamp for two fields, given their
1617     * individual pseudo-time-stamps. If either of the fields
1618     * is unset, then the aggregate is unset. Otherwise, the
1619     * aggregate is the later of the two stamps.
1620     */

1621    private static final int aggregateStamp(int stamp_a, int stamp_b) {
1622    if (stamp_a == UNSET || stamp_b == UNSET) {
1623        return UNSET;
1624    }
1625        return (stamp_a > stamp_b) ? stamp_a : stamp_b;
1626    }
1627
1628    /**
1629     * Compares this <code>Calendar</code> to the specified
1630     * <code>Object</code>. The result is <code>true</code> if and only if
1631     * the argument is a <code>Calendar</code> object of the same calendar
1632     * system that represents the same time value (millisecond offset from the
1633     * <a HREF="#Epoch">Epoch</a>) under the same
1634     * <code>Calendar</code> parameters as this object.
1635     *
1636     * <p>The <code>Calendar</code> parameters are the values represented
1637     * by the <code>isLenient</code>, <code>getFirstDayOfWeek</code>,
1638     * <code>getMinimalDaysInFirstWeek</code> and <code>getTimeZone</code>
1639     * methods. If there is any difference in those parameters
1640     * between the two <code>Calendar</code>s, this method returns
1641     * <code>false</code>.
1642     *
1643     * <p>Use the {@link #compareTo(Calendar) compareTo} method to
1644     * compare only the time values.
1645     *
1646     * @param obj the object to compare with.
1647     * @return <code>true</code> if this object is equal to <code>obj</code>;
1648     * <code>false</code> otherwise.
1649     */

1650    public boolean equals(Object JavaDoc obj) {
1651        if (this == obj)
1652            return true;
1653    try {
1654        Calendar JavaDoc that = (Calendar JavaDoc)obj;
1655        return compareTo(getMillisOf(that)) == 0 &&
1656        lenient == that.lenient &&
1657        firstDayOfWeek == that.firstDayOfWeek &&
1658        minimalDaysInFirstWeek == that.minimalDaysInFirstWeek &&
1659        zone.equals(that.zone);
1660    } catch (Exception JavaDoc e) {
1661        // Note: GregorianCalendar.computeTime throws
1662
// IllegalArgumentException if the ERA value is invalid
1663
// even it's in lenient mode.
1664
}
1665    return false;
1666    }
1667
1668    /**
1669     * Returns a hash code for this calendar.
1670     *
1671     * @return a hash code value for this object.
1672     * @since 1.2
1673     */

1674    public int hashCode() {
1675    // 'otheritems' represents the hash code for the previous versions.
1676
int otheritems = (lenient ? 1 : 0)
1677            | (firstDayOfWeek << 1)
1678            | (minimalDaysInFirstWeek << 4)
1679            | (zone.hashCode() << 7);
1680    long t = getMillisOf(this);
1681    return (int) t ^ (int)(t >> 32) ^ otheritems;
1682    }
1683
1684    /**
1685     * Returns whether this <code>Calendar</code> represents a time
1686     * before the time represented by the specified
1687     * <code>Object</code>. This method is equivalent to:
1688     * <pre><blockquote>
1689     * compareTo(when) < 0
1690     * </blockquote></pre>
1691     * if and only if <code>when</code> is a <code>Calendar</code>
1692     * instance. Otherwise, the method returns <code>false</code>.
1693     *
1694     * @param when the <code>Object</code> to be compared
1695     * @return <code>true</code> if the time of this
1696     * <code>Calendar</code> is before the time represented by
1697     * <code>when</code>; <code>false</code> otherwise.
1698     * @see #compareTo(Calendar)
1699     */

1700    public boolean before(Object JavaDoc when) {
1701    return when instanceof Calendar JavaDoc
1702        && compareTo((Calendar JavaDoc)when) < 0;
1703    }
1704
1705    /**
1706     * Returns whether this <code>Calendar</code> represents a time
1707     * after the time represented by the specified
1708     * <code>Object</code>. This method is equivalent to:
1709     * <pre><blockquote>
1710     * compareTo(when) > 0
1711     * </blockquote></pre>
1712     * if and only if <code>when</code> is a <code>Calendar</code>
1713     * instance. Otherwise, the method returns <code>false</code>.
1714     *
1715     * @param when the <code>Object</code> to be compared
1716     * @return <code>true</code> if the time of this <code>Calendar</code> is
1717     * after the time represented by <code>when</code>; <code>false</code>
1718     * otherwise.
1719     * @see #compareTo(Calendar)
1720     */

1721    public boolean after(Object JavaDoc when) {
1722    return when instanceof Calendar JavaDoc
1723        && compareTo((Calendar JavaDoc)when) > 0;
1724    }
1725
1726    /**
1727     * Compares the time values (millisecond offsets from the <a
1728     * HREF="#Epoch">Epoch</a>) represented by two
1729     * <code>Calendar</code> objects.
1730     *
1731     * @param anotherCalendar the <code>Calendar</code> to be compared.
1732     * @return the value <code>0</code> if the time represented by the argument
1733     * is equal to the time represented by this <code>Calendar</code>; a value
1734     * less than <code>0</code> if the time of this <code>Calendar</code> is
1735     * before the time represented by the argument; and a value greater than
1736     * <code>0</code> if the time of this <code>Calendar</code> is after the
1737     * time represented by the argument.
1738     * @exception NullPointerException if the specified <code>Calendar</code> is
1739     * <code>null</code>.
1740     * @exception IllegalArgumentException if the time value of the
1741     * specified <code>Calendar</code> object can't be obtained due to
1742     * any invalid calendar values.
1743     * @since 1.5
1744     */

1745    public int compareTo(Calendar JavaDoc anotherCalendar) {
1746    return compareTo(getMillisOf(anotherCalendar));
1747    }
1748
1749    /**
1750     * Adds or subtracts the specified amount of time to the given calendar field,
1751     * based on the calendar's rules. For example, to subtract 5 days from
1752     * the current time of the calendar, you can achieve it by calling:
1753     * <p><code>add(Calendar.DAY_OF_MONTH, -5)</code>.
1754     *
1755     * @param field the calendar field.
1756     * @param amount the amount of date or time to be added to the field.
1757     * @see #roll(int,int)
1758     * @see #set(int,int)
1759     */

1760    abstract public void add(int field, int amount);
1761
1762    /**
1763     * Adds or subtracts (up/down) a single unit of time on the given time
1764     * field without changing larger fields. For example, to roll the current
1765     * date up by one day, you can achieve it by calling:
1766     * <p>roll(Calendar.DATE, true).
1767     * When rolling on the year or Calendar.YEAR field, it will roll the year
1768     * value in the range between 1 and the value returned by calling
1769     * <code>getMaximum(Calendar.YEAR)</code>.
1770     * When rolling on the month or Calendar.MONTH field, other fields like
1771     * date might conflict and, need to be changed. For instance,
1772     * rolling the month on the date 01/31/96 will result in 02/29/96.
1773     * When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field, it will
1774     * roll the hour value in the range between 0 and 23, which is zero-based.
1775     *
1776     * @param field the time field.
1777     * @param up indicates if the value of the specified time field is to be
1778     * rolled up or rolled down. Use true if rolling up, false otherwise.
1779     * @see Calendar#add(int,int)
1780     * @see Calendar#set(int,int)
1781     */

1782    abstract public void roll(int field, boolean up);
1783
1784    /**
1785     * Adds the specified (signed) amount to the specified calendar field
1786     * without changing larger fields. A negative amount means to roll
1787     * down.
1788     *
1789     * <p>NOTE: This default implementation on <code>Calendar</code> just repeatedly calls the
1790     * version of {@link #roll(int,boolean) roll()} that rolls by one unit. This may not
1791     * always do the right thing. For example, if the <code>DAY_OF_MONTH</code> field is 31,
1792     * rolling through February will leave it set to 28. The <code>GregorianCalendar</code>
1793     * version of this function takes care of this problem. Other subclasses
1794     * should also provide overrides of this function that do the right thing.
1795     *
1796     * @param field the calendar field.
1797     * @param amount the signed amount to add to the calendar <code>field</code>.
1798     * @since 1.2
1799     * @see #roll(int,boolean)
1800     * @see #add(int,int)
1801     * @see #set(int,int)
1802     */

1803    public void roll(int field, int amount)
1804    {
1805        while (amount > 0) {
1806            roll(field, true);
1807            amount--;
1808        }
1809        while (amount < 0) {
1810            roll(field, false);
1811            amount++;
1812        }
1813    }
1814
1815    /**
1816     * Sets the time zone with the given time zone value.
1817     *
1818     * @param value the given time zone.
1819     */

1820    public void setTimeZone(TimeZone JavaDoc value)
1821    {
1822        zone = value;
1823    sharedZone = false;
1824        /* Recompute the fields from the time using the new zone. This also
1825         * works if isTimeSet is false (after a call to set()). In that case
1826         * the time will be computed from the fields using the new zone, then
1827         * the fields will get recomputed from that. Consider the sequence of
1828         * calls: cal.setTimeZone(EST); cal.set(HOUR, 1); cal.setTimeZone(PST).
1829         * Is cal set to 1 o'clock EST or 1 o'clock PST? Answer: PST. More
1830         * generally, a call to setTimeZone() affects calls to set() BEFORE AND
1831         * AFTER it up to the next call to complete().
1832         */

1833        areAllFieldsSet = areFieldsSet = false;
1834    }
1835
1836    /**
1837     * Gets the time zone.
1838     *
1839     * @return the time zone object associated with this calendar.
1840     */

1841    public TimeZone JavaDoc getTimeZone()
1842    {
1843    // If the TimeZone object is shared by other Calendar instances, then
1844
// create a clone.
1845
if (sharedZone) {
1846        zone = (TimeZone JavaDoc) zone.clone();
1847        sharedZone = false;
1848    }
1849        return zone;
1850    }
1851
1852    /**
1853     * Returns the time zone (without cloning).
1854     */

1855    TimeZone JavaDoc getZone() {
1856    return zone;
1857    }
1858
1859    /**
1860     * Sets the sharedZone flag to <code>shared</code>.
1861     */

1862    void setZoneShared(boolean shared) {
1863    sharedZone = shared;
1864    }
1865
1866    /**
1867     * Specifies whether or not date/time interpretation is to be lenient. With
1868     * lenient interpretation, a date such as "February 942, 1996" will be
1869     * treated as being equivalent to the 941st day after February 1, 1996.
1870     * With strict (non-lenient) interpretation, such dates will cause an exception to be
1871     * thrown. The default is lenient.
1872     *
1873     * @param lenient <code>true</code> if the lenient mode is to be turned
1874     * on; <code>false</code> if it is to be turned off.
1875     * @see #isLenient()
1876     * @see java.text.DateFormat#setLenient
1877     */

1878    public void setLenient(boolean lenient)
1879    {
1880        this.lenient = lenient;
1881    }
1882
1883    /**
1884     * Tells whether date/time interpretation is to be lenient.
1885     *
1886     * @return <code>true</code> if the interpretation mode of this calendar is lenient;
1887     * <code>false</code> otherwise.
1888     * @see #setLenient(boolean)
1889     */

1890    public boolean isLenient()
1891    {
1892        return lenient;
1893    }
1894
1895    /**
1896     * Sets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
1897     * <code>MONDAY</code> in France.
1898     *
1899     * @param value the given first day of the week.
1900     * @see #getFirstDayOfWeek()
1901     * @see #getMinimalDaysInFirstWeek()
1902     */

1903    public void setFirstDayOfWeek(int value)
1904    {
1905    if (firstDayOfWeek == value) {
1906        return;
1907    }
1908        firstDayOfWeek = value;
1909    invalidateWeekFields();
1910    }
1911
1912    /**
1913     * Gets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
1914     * <code>MONDAY</code> in France.
1915     *
1916     * @return the first day of the week.
1917     * @see #setFirstDayOfWeek(int)
1918     * @see #getMinimalDaysInFirstWeek()
1919     */

1920    public int getFirstDayOfWeek()
1921    {
1922        return firstDayOfWeek;
1923    }
1924
1925    /**
1926     * Sets what the minimal days required in the first week of the year are;
1927     * For example, if the first week is defined as one that contains the first
1928     * day of the first month of a year, call this method with value 1. If it
1929     * must be a full week, use value 7.
1930     *
1931     * @param value the given minimal days required in the first week
1932     * of the year.
1933     * @see #getMinimalDaysInFirstWeek()
1934     */

1935    public void setMinimalDaysInFirstWeek(int value)
1936    {
1937        if (minimalDaysInFirstWeek == value) {
1938        return;
1939    }
1940        minimalDaysInFirstWeek = value;
1941    invalidateWeekFields();
1942    }
1943
1944    /**
1945     * Gets what the minimal days required in the first week of the year are;
1946     * e.g., if the first week is defined as one that contains the first day
1947     * of the first month of a year, this method returns 1. If
1948     * the minimal days required must be a full week, this method
1949     * returns 7.
1950     *
1951     * @return the minimal days required in the first week of the year.
1952     * @see #setMinimalDaysInFirstWeek(int)
1953     */

1954    public int getMinimalDaysInFirstWeek()
1955    {
1956        return minimalDaysInFirstWeek;
1957    }
1958
1959    /**
1960     * Returns the minimum value for the given calendar field of this
1961     * <code>Calendar</code> instance. The minimum value is defined as
1962     * the smallest value returned by the {@link #get(int) get} method
1963     * for any possible time value. The minimum value depends on
1964     * calendar system specific parameters of the instance.
1965     *
1966     * @param field the calendar field.
1967     * @return the minimum value for the given calendar field.
1968     * @see #getMaximum(int)
1969     * @see #getGreatestMinimum(int)
1970     * @see #getLeastMaximum(int)
1971     * @see #getActualMinimum(int)
1972     * @see #getActualMaximum(int)
1973     */

1974    abstract public int getMinimum(int field);
1975
1976    /**
1977     * Returns the maximum value for the given calendar field of this
1978     * <code>Calendar</code> instance. The maximum value is defined as
1979     * the largest value returned by the {@link #get(int) get} method
1980     * for any possible time value. The maximum value depends on
1981     * calendar system specific parameters of the instance.
1982     *
1983     * @param field the calendar field.
1984     * @return the maximum value for the given calendar field.
1985     * @see #getMinimum(int)
1986     * @see #getGreatestMinimum(int)
1987     * @see #getLeastMaximum(int)
1988     * @see #getActualMinimum(int)
1989     * @see #getActualMaximum(int)
1990     */

1991    abstract public int getMaximum(int field);
1992
1993    /**
1994     * Returns the highest minimum value for the given calendar field
1995     * of this <code>Calendar</code> instance. The highest minimum
1996     * value is defined as the largest value returned by {@link
1997     * #getActualMinimum(int)} for any possible time value. The
1998     * greatest minimum value depends on calendar system specific
1999     * parameters of the instance.
2000     *
2001     * @param field the calendar field.
2002     * @return the highest minimum value for the given calendar field.
2003     * @see #getMinimum(int)
2004     * @see #getMaximum(int)
2005     * @see #getLeastMaximum(int)
2006     * @see #getActualMinimum(int)
2007     * @see #getActualMaximum(int)
2008     */

2009    abstract public int getGreatestMinimum(int field);
2010
2011    /**
2012     * Returns the lowest maximum value for the given calendar field
2013     * of this <code>Calendar</code> instance. The lowest maximum
2014     * value is defined as the smallest value returned by {@link
2015     * #getActualMaximum(int)} for any possible time value. The least
2016     * maximum value depends on calendar system specific parameters of
2017     * the instance. For example, a <code>Calendar</code> for the
2018     * Gregorian calendar system returns 28 for the
2019     * <code>DAY_OF_MONTH</code> field, because the 28th is the last
2020     * day of the shortest month of this calendar, February in a
2021     * common year.
2022     *
2023     * @param field the calendar field.
2024     * @return the lowest maximum value for the given calendar field.
2025     * @see #getMinimum(int)
2026     * @see #getMaximum(int)
2027     * @see #getGreatestMinimum(int)
2028     * @see #getActualMinimum(int)
2029     * @see #getActualMaximum(int)
2030     */

2031    abstract public int getLeastMaximum(int field);
2032
2033    /**
2034     * Returns the minimum value that the specified calendar field
2035     * could have, given the time value of this <code>Calendar</code>.
2036     *
2037     * <p>The default implementation of this method uses an iterative
2038     * algorithm to determine the actual minimum value for the
2039     * calendar field. Subclasses should, if possible, override this
2040     * with a more efficient implementation - in many cases, they can
2041     * simply return <code>getMinimum()</code>.
2042     *
2043     * @param field the calendar field
2044     * @return the minimum of the given calendar field for the time
2045     * value of this <code>Calendar</code>
2046     * @see #getMinimum(int)
2047     * @see #getMaximum(int)
2048     * @see #getGreatestMinimum(int)
2049     * @see #getLeastMaximum(int)
2050     * @see #getActualMaximum(int)
2051     * @since 1.2
2052     */

2053    public int getActualMinimum(int field) {
2054        int fieldValue = getGreatestMinimum(field);
2055        int endValue = getMinimum(field);
2056
2057        // if we know that the minimum value is always the same, just return it
2058
if (fieldValue == endValue) {
2059            return fieldValue;
2060        }
2061
2062        // clone the calendar so we don't mess with the real one, and set it to
2063
// accept anything for the field values
2064
Calendar JavaDoc work = (Calendar JavaDoc)this.clone();
2065        work.setLenient(true);
2066
2067        // now try each value from getLeastMaximum() to getMaximum() one by one until
2068
// we get a value that normalizes to another value. The last value that
2069
// normalizes to itself is the actual minimum for the current date
2070
int result = fieldValue;
2071
2072        do {
2073            work.set(field, fieldValue);
2074            if (work.get(field) != fieldValue) {
2075                break;
2076            } else {
2077                result = fieldValue;
2078                fieldValue--;
2079            }
2080        } while (fieldValue >= endValue);
2081
2082        return result;
2083    }
2084
2085    /**
2086     * Returns the maximum value that the specified calendar field
2087     * could have, given the time value of this
2088     * <code>Calendar</code>. For example, the actual maximum value of
2089     * the <code>MONTH</code> field is 12 in some years, and 13 in
2090     * other years in the Hebrew calendar system.
2091     *
2092     * <p>The default implementation of this method uses an iterative
2093     * algorithm to determine the actual maximum value for the
2094     * calendar field. Subclasses should, if possible, override this
2095     * with a more efficient implementation.
2096     *
2097     * @param field the calendar field
2098     * @return the maximum of the given calendar field for the time
2099     * value of this <code>Calendar</code>
2100     * @see #getMinimum(int)
2101     * @see #getMaximum(int)
2102     * @see #getGreatestMinimum(int)
2103     * @see #getLeastMaximum(int)
2104     * @see #getActualMinimum(int)
2105     * @since 1.2
2106     */

2107    public int getActualMaximum(int field) {
2108        int fieldValue = getLeastMaximum(field);
2109        int endValue = getMaximum(field);
2110
2111        // if we know that the maximum value is always the same, just return it.
2112
if (fieldValue == endValue) {
2113            return fieldValue;
2114        }
2115
2116        // clone the calendar so we don't mess with the real one, and set it to
2117
// accept anything for the field values.
2118
Calendar JavaDoc work = (Calendar JavaDoc)this.clone();
2119        work.setLenient(true);
2120
2121        // if we're counting weeks, set the day of the week to Sunday. We know the
2122
// last week of a month or year will contain the first day of the week.
2123
if (field == WEEK_OF_YEAR || field == WEEK_OF_MONTH)
2124            work.set(DAY_OF_WEEK, firstDayOfWeek);
2125
2126        // now try each value from getLeastMaximum() to getMaximum() one by one until
2127
// we get a value that normalizes to another value. The last value that
2128
// normalizes to itself is the actual maximum for the current date
2129
int result = fieldValue;
2130
2131        do {
2132            work.set(field, fieldValue);
2133            if (work.get(field) != fieldValue) {
2134                break;
2135            } else {
2136                result = fieldValue;
2137                fieldValue++;
2138            }
2139        } while (fieldValue <= endValue);
2140
2141        return result;
2142    }
2143
2144    /**
2145     * Creates and returns a copy of this object.
2146     *
2147     * @return a copy of this object.
2148     */

2149    public Object JavaDoc clone()
2150    {
2151        try {
2152            Calendar JavaDoc other = (Calendar JavaDoc) super.clone();
2153
2154            other.fields = new int[FIELD_COUNT];
2155            other.isSet = new boolean[FIELD_COUNT];
2156            other.stamp = new int[FIELD_COUNT];
2157        for (int i = 0; i < FIELD_COUNT; i++) {
2158        other.fields[i] = fields[i];
2159        other.stamp[i] = stamp[i];
2160        other.isSet[i] = isSet[i];
2161        }
2162            other.zone = (TimeZone JavaDoc) zone.clone();
2163            return other;
2164        }
2165        catch (CloneNotSupportedException JavaDoc e) {
2166            // this shouldn't happen, since we are Cloneable
2167
throw new InternalError JavaDoc();
2168        }
2169    }
2170
2171    private static final String JavaDoc[] FIELD_NAME = {
2172        "ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH", "DAY_OF_MONTH",
2173        "DAY_OF_YEAR", "DAY_OF_WEEK", "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR",
2174        "HOUR_OF_DAY", "MINUTE", "SECOND", "MILLISECOND", "ZONE_OFFSET",
2175        "DST_OFFSET"
2176    };
2177
2178    /**
2179     * Returns the name of the specified calendar field.
2180     *
2181     * @param field the calendar field
2182     * @return the calendar field name
2183     * @exception IndexOutOfBoundsException if <code>field</code> is negative,
2184     * equal to or greater then <code>FIELD_COUNT</code>.
2185     */

2186    static final String JavaDoc getFieldName(int field) {
2187    return FIELD_NAME[field];
2188    }
2189
2190    /**
2191     * Return a string representation of this calendar. This method
2192     * is intended to be used only for debugging purposes, and the
2193     * format of the returned string may vary between implementations.
2194     * The returned string may be empty but may not be <code>null</code>.
2195     *
2196     * @return a string representation of this calendar.
2197     */

2198    public String JavaDoc toString() {
2199    // NOTE: BuddhistCalendar.toString() interprets the string
2200
// produced by this method so that the Gregorian year number
2201
// is substituted by its B.E. year value. It relies on
2202
// "...,YEAR=<year>,..." or "...,YEAR=?,...".
2203
StringBuilder JavaDoc buffer = new StringBuilder JavaDoc(800);
2204        buffer.append(getClass().getName()).append('[');
2205    appendValue(buffer, "time", isTimeSet, time);
2206        buffer.append(",areFieldsSet=").append(areFieldsSet);
2207        buffer.append(",areAllFieldsSet=").append(areAllFieldsSet);
2208        buffer.append(",lenient=").append(lenient);
2209        buffer.append(",zone=").append(zone);
2210        appendValue(buffer, ",firstDayOfWeek", true, (long) firstDayOfWeek);
2211        appendValue(buffer, ",minimalDaysInFirstWeek", true, (long) minimalDaysInFirstWeek);
2212        for (int i = 0; i < FIELD_COUNT; ++i) {
2213            buffer.append(',');
2214        appendValue(buffer, FIELD_NAME[i], isSet(i), (long) fields[i]);
2215        }
2216        buffer.append(']');
2217        return buffer.toString();
2218    }
2219
2220    // =======================privates===============================
2221

2222    private static final void appendValue(StringBuilder JavaDoc sb, String JavaDoc item, boolean valid, long value) {
2223    sb.append(item).append('=');
2224    if (valid) {
2225        sb.append(value);
2226    } else {
2227        sb.append('?');
2228    }
2229    }
2230
2231    /**
2232     * Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent.
2233     * They are used to figure out the week count for a specific date for
2234     * a given locale. These must be set when a Calendar is constructed.
2235     * @param desiredLocale the given locale.
2236     */

2237    private void setWeekCountData(Locale JavaDoc desiredLocale)
2238    {
2239    /* try to get the Locale data from the cache */
2240    int[] data = cachedLocaleData.get(desiredLocale);
2241    if (data == null) { /* cache miss */
2242        ResourceBundle JavaDoc resource = LocaleData.getLocaleElements(desiredLocale);
2243        String JavaDoc[] dateTimePatterns =
2244            resource.getStringArray("DateTimeElements");
2245        data = new int[2];
2246        data[0] = Integer.parseInt(dateTimePatterns[0]);
2247        data[1] = Integer.parseInt(dateTimePatterns[1]);
2248        cachedLocaleData.put(desiredLocale, data);
2249    }
2250    firstDayOfWeek = data[0];
2251    minimalDaysInFirstWeek = data[1];
2252    }
2253
2254    /**
2255     * Recomputes the time and updates the status fields isTimeSet
2256     * and areFieldsSet. Callers should check isTimeSet and only
2257     * call this method if isTimeSet is false.
2258     */

2259    private void updateTime() {
2260        computeTime();
2261    // The areFieldsSet and areAllFieldsSet values are no longer
2262
// controlled here (as of 1.5).
2263
isTimeSet = true;
2264    }
2265
2266    private int compareTo(long t) {
2267    long thisTime = getMillisOf(this);
2268    return (thisTime > t) ? 1 : (thisTime == t) ? 0 : -1;
2269    }
2270
2271    private static final long getMillisOf(Calendar JavaDoc calendar) {
2272    if (calendar.isTimeSet) {
2273        return calendar.time;
2274    }
2275    Calendar JavaDoc cal = (Calendar JavaDoc) calendar.clone();
2276    cal.setLenient(true);
2277    return cal.getTimeInMillis();
2278    }
2279
2280    /**
2281     * Adjusts the stamp[] values before nextStamp overflow. nextStamp
2282     * is set to the next stamp value upon the return.
2283     */

2284    private final void adjustStamp() {
2285    int max = MINIMUM_USER_STAMP;
2286    int newStamp = MINIMUM_USER_STAMP;
2287
2288    for (;;) {
2289        int min = Integer.MAX_VALUE;
2290        for (int i = 0; i < stamp.length; i++) {
2291        int v = stamp[i];
2292        if (v >= newStamp && min > v) {
2293            min = v;
2294        }
2295        if (max < v) {
2296            max = v;
2297        }
2298        }
2299        if (max != min && min == Integer.MAX_VALUE) {
2300        break;
2301        }
2302        for (int i = 0; i < stamp.length; i++) {
2303        if (stamp[i] == min) {
2304            stamp[i] = newStamp;
2305        }
2306        }
2307        newStamp++;
2308        if (min == max) {
2309        break;
2310        }
2311    }
2312    nextStamp = newStamp;
2313    }
2314
2315    /**
2316     * Sets the WEEK_OF_MONTH and WEEK_OF_YEAR fields to new values with the
2317     * new parameter value if they have been calculated internally.
2318     */

2319    private void invalidateWeekFields()
2320    {
2321    if (stamp[WEEK_OF_MONTH] != COMPUTED &&
2322        stamp[WEEK_OF_YEAR] != COMPUTED) {
2323        return;
2324    }
2325
2326    // We have to check the new values of these fields after changing
2327
// firstDayOfWeek and/or minimalDaysInFirstWeek. If the field values
2328
// have been changed, then set the new values. (4822110)
2329
Calendar JavaDoc cal = (Calendar JavaDoc) clone();
2330    cal.setLenient(true);
2331    cal.clear(WEEK_OF_MONTH);
2332    cal.clear(WEEK_OF_YEAR);
2333
2334    if (stamp[WEEK_OF_MONTH] == COMPUTED) {
2335        int weekOfMonth = cal.get(WEEK_OF_MONTH);
2336        if (fields[WEEK_OF_MONTH] != weekOfMonth) {
2337        fields[WEEK_OF_MONTH] = weekOfMonth;
2338        }
2339    }
2340
2341    if (stamp[WEEK_OF_YEAR] == COMPUTED) {
2342        int weekOfYear = cal.get(WEEK_OF_YEAR);
2343        if (fields[WEEK_OF_YEAR] != weekOfYear) {
2344        fields[WEEK_OF_YEAR] = weekOfYear;
2345        }
2346    }
2347    }
2348
2349    /**
2350     * Save the state of this object to a stream (i.e., serialize it).
2351     *
2352     * Ideally, <code>Calendar</code> would only write out its state data and
2353     * the current time, and not write any field data out, such as
2354     * <code>fields[]</code>, <code>isTimeSet</code>, <code>areFieldsSet</code>,
2355     * and <code>isSet[]</code>. <code>nextStamp</code> also should not be part
2356     * of the persistent state. Unfortunately, this didn't happen before JDK 1.1
2357     * shipped. To be compatible with JDK 1.1, we will always have to write out
2358     * the field values and state flags. However, <code>nextStamp</code> can be
2359     * removed from the serialization stream; this will probably happen in the
2360     * near future.
2361     */

2362    private void writeObject(ObjectOutputStream JavaDoc stream)
2363         throws IOException JavaDoc
2364    {
2365        // Try to compute the time correctly, for the future (stream
2366
// version 2) in which we don't write out fields[] or isSet[].
2367
if (!isTimeSet) {
2368            try {
2369                updateTime();
2370            }
2371            catch (IllegalArgumentException JavaDoc e) {}
2372        }
2373
2374    // If this Calendar has a ZoneInfo, save it and set a
2375
// SimpleTimeZone equivalent (as a single DST schedule) for
2376
// backward compatibility.
2377
TimeZone JavaDoc savedZone = null;
2378    if (zone instanceof ZoneInfo) {
2379        SimpleTimeZone JavaDoc stz = ((ZoneInfo)zone).getLastRuleInstance();
2380        if (stz == null) {
2381        stz = new SimpleTimeZone JavaDoc(zone.getRawOffset(), zone.getID());
2382        }
2383        savedZone = zone;
2384        zone = stz;
2385    }
2386
2387        // Write out the 1.1 FCS object.
2388
stream.defaultWriteObject();
2389
2390    // Write out the ZoneInfo object
2391
// 4802409: we write out even if it is null, a temporary workaround
2392
// the real fix for bug 4844924 in corba-iiop
2393
stream.writeObject(savedZone);
2394    if (savedZone != null) {
2395        zone = savedZone;
2396    }
2397    }
2398
2399    /**
2400     * Reconstitutes this object from a stream (i.e., deserialize it).
2401     */

2402    private void readObject(ObjectInputStream JavaDoc stream)
2403         throws IOException JavaDoc, ClassNotFoundException JavaDoc
2404    {
2405    final ObjectInputStream JavaDoc input = stream;
2406        input.defaultReadObject();
2407
2408        stamp = new int[FIELD_COUNT];
2409
2410        // Starting with version 2 (not implemented yet), we expect that
2411
// fields[], isSet[], isTimeSet, and areFieldsSet may not be
2412
// streamed out anymore. We expect 'time' to be correct.
2413
if (serialVersionOnStream >= 2)
2414        {
2415            isTimeSet = true;
2416            if (fields == null) fields = new int[FIELD_COUNT];
2417            if (isSet == null) isSet = new boolean[FIELD_COUNT];
2418        }
2419        else if (serialVersionOnStream >= 0)
2420        {
2421            for (int i=0; i<FIELD_COUNT; ++i)
2422                stamp[i] = isSet[i] ? COMPUTED : UNSET;
2423        }
2424
2425        serialVersionOnStream = currentSerialVersion;
2426
2427    // If there's a ZoneInfo object, use it for zone.
2428
try {
2429        ZoneInfo zi = (ZoneInfo) AccessController.doPrivileged(
2430        new PrivilegedExceptionAction JavaDoc() {
2431            public Object JavaDoc run() throws Exception JavaDoc {
2432            return input.readObject();
2433            }
2434        });
2435        if (zi != null) {
2436        zone = zi;
2437        }
2438    } catch (Exception JavaDoc e) {
2439    }
2440
2441    // If the deserialized object has a SimpleTimeZone, try to
2442
// replace it with a ZoneInfo equivalent (as of 1.4) in order
2443
// to be compatible with the SimpleTimeZone-based
2444
// implementation as much as possible.
2445
if (zone instanceof SimpleTimeZone JavaDoc) {
2446        String JavaDoc id = zone.getID();
2447        TimeZone JavaDoc zi = TimeZone.getTimeZone(id);
2448        if (zi != null && zi.hasSameRules(zone) && zi.getID().equals(id)) {
2449        zone = zi;
2450        }
2451    }
2452    }
2453}
2454
Popular Tags