KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ibm > icu > util > Calendar


1 /*
2 * Copyright (C) 1996-2007, International Business Machines
3 * Corporation and others. All Rights Reserved.
4 */

5
6 package com.ibm.icu.util;
7
8 import java.io.IOException JavaDoc;
9 import java.io.ObjectInputStream JavaDoc;
10 import java.io.ObjectOutputStream JavaDoc;
11 import java.io.Serializable JavaDoc;
12 import java.util.Date JavaDoc;
13 import java.util.Hashtable JavaDoc;
14 import java.util.Locale JavaDoc;
15 import java.util.MissingResourceException JavaDoc;
16 import java.util.Set JavaDoc;
17
18 import com.ibm.icu.impl.CalendarData;
19 import com.ibm.icu.impl.ICUCache;
20 import com.ibm.icu.impl.ICUResourceBundle;
21 import com.ibm.icu.impl.SimpleCache;
22 import com.ibm.icu.text.DateFormat;
23 import com.ibm.icu.text.DateFormatSymbols;
24 import com.ibm.icu.text.MessageFormat;
25 import com.ibm.icu.text.SimpleDateFormat;
26
27 /**
28  * <code>Calendar</code> is an abstract base class for converting between
29  * a <code>Date</code> object and a set of integer fields such as
30  * <code>YEAR</code>, <code>MONTH</code>, <code>DAY</code>, <code>HOUR</code>,
31  * and so on. (A <code>Date</code> object represents a specific instant in
32  * time with millisecond precision. See
33  * {@link Date}
34  * for information about the <code>Date</code> class.)
35  *
36  * <p><b>Note:</b> This class is similar, but not identical, to the class
37  * <code>java.util.Calendar</code>. Changes are detailed below.
38  *
39  * <p>
40  * Subclasses of <code>Calendar</code> interpret a <code>Date</code>
41  * according to the rules of a specific calendar system. ICU4J contains
42  * several subclasses implementing different international calendar systems.
43  *
44  * <p>
45  * Like other locale-sensitive classes, <code>Calendar</code> provides a
46  * class method, <code>getInstance</code>, for getting a generally useful
47  * object of this type. <code>Calendar</code>'s <code>getInstance</code> method
48  * returns a calendar of a type appropriate to the locale, whose
49  * time fields have been initialized with the current date and time:
50  * <blockquote>
51  * <pre>Calendar rightNow = Calendar.getInstance()</pre>
52  * </blockquote>
53  *
54  * <p>When a <code>ULocale</code> is used by <code>getInstance</code>, its
55  * '<code>calendar</code>' tag and value are retrieved if present. If a recognized
56  * value is supplied, a calendar is provided and configured as appropriate.
57  * Currently recognized tags are "buddhist", "chinese", "coptic", "ethiopic",
58  * "gregorian", "hebrew", "islamic", "islamic-civil", and "japanese". For
59  * example: <blockquote>
60  * <pre>Calendar cal = Calendar.getInstance(new ULocale("en_US@calendar=japanese"));</pre>
61  * </blockquote> will return an instance of JapaneseCalendar (using en_US conventions for
62  * minimum days in first week, start day of week, et cetera).
63  *
64  * <p>A <code>Calendar</code> object can produce all the time field values
65  * needed to implement the date-time formatting for a particular language and
66  * calendar style (for example, Japanese-Gregorian, Japanese-Traditional).
67  * <code>Calendar</code> defines the range of values returned by certain fields,
68  * as well as their meaning. For example, the first month of the year has value
69  * <code>MONTH</code> == <code>JANUARY</code> for all calendars. Other values
70  * are defined by the concrete subclass, such as <code>ERA</code> and
71  * <code>YEAR</code>. See individual field documentation and subclass
72  * documentation for details.
73  *
74  * <p>When a <code>Calendar</code> is <em>lenient</em>, it accepts a wider range
75  * of field values than it produces. For example, a lenient
76  * <code>GregorianCalendar</code> interprets <code>MONTH</code> ==
77  * <code>JANUARY</code>, <code>DAY_OF_MONTH</code> == 32 as February 1. A
78  * non-lenient <code>GregorianCalendar</code> throws an exception when given
79  * out-of-range field settings. When calendars recompute field values for
80  * return by <code>get()</code>, they normalize them. For example, a
81  * <code>GregorianCalendar</code> always produces <code>DAY_OF_MONTH</code>
82  * values between 1 and the length of the month.
83  *
84  * <p><code>Calendar</code> defines a locale-specific seven day week using two
85  * parameters: the first day of the week and the minimal days in first week
86  * (from 1 to 7). These numbers are taken from the locale resource data when a
87  * <code>Calendar</code> is constructed. They may also be specified explicitly
88  * through the API.
89  *
90  * <p>When setting or getting the <code>WEEK_OF_MONTH</code> or
91  * <code>WEEK_OF_YEAR</code> fields, <code>Calendar</code> must determine the
92  * first week of the month or year as a reference point. The first week of a
93  * month or year is defined as the earliest seven day period beginning on
94  * <code>getFirstDayOfWeek()</code> and containing at least
95  * <code>getMinimalDaysInFirstWeek()</code> days of that month or year. Weeks
96  * numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow
97  * it. Note that the normalized numbering returned by <code>get()</code> may be
98  * different. For example, a specific <code>Calendar</code> subclass may
99  * designate the week before week 1 of a year as week <em>n</em> of the previous
100  * year.
101  *
102  * <p> When computing a <code>Date</code> from time fields, two special
103  * circumstances may arise: there may be insufficient information to compute the
104  * <code>Date</code> (such as only year and month but no day in the month), or
105  * there may be inconsistent information (such as "Tuesday, July 15, 1996" --
106  * July 15, 1996 is actually a Monday).
107  *
108  * <p>
109  * <strong>Insufficient information.</strong> The calendar will use default
110  * information to specify the missing fields. This may vary by calendar; for
111  * the Gregorian calendar, the default for a field is the same as that of the
112  * start of the epoch: i.e., YEAR = 1970, MONTH = JANUARY, DATE = 1, etc.
113  *
114  * <p>
115  * <strong>Inconsistent information.</strong> If fields conflict, the calendar
116  * will give preference to fields set more recently. For example, when
117  * determining the day, the calendar will look for one of the following
118  * combinations of fields. The most recent combination, as determined by the
119  * most recently set single field, will be used.
120  *
121  * <blockquote>
122  * <pre>
123  * MONTH + DAY_OF_MONTH
124  * MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
125  * MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
126  * DAY_OF_YEAR
127  * DAY_OF_WEEK + WEEK_OF_YEAR</pre>
128  * </blockquote>
129  *
130  * For the time of day:
131  *
132  * <blockquote>
133  * <pre>
134  * HOUR_OF_DAY
135  * AM_PM + HOUR</pre>
136  * </blockquote>
137  *
138  * <p>
139  * <strong>Note:</strong> for some non-Gregorian calendars, different
140  * fields may be necessary for complete disambiguation. For example, a full
141  * specification of the historial Arabic astronomical calendar requires year,
142  * month, day-of-month <em>and</em> day-of-week in some cases.
143  *
144  * <p>
145  * <strong>Note:</strong> There are certain possible ambiguities in
146  * interpretation of certain singular times, which are resolved in the
147  * following ways:
148  * <ol>
149  * <li> 24:00:00 "belongs" to the following day. That is,
150  * 23:59 on Dec 31, 1969 &lt; 24:00 on Jan 1, 1970 &lt; 24:01:00 on Jan 1, 1970
151  *
152  * <li> Although historically not precise, midnight also belongs to "am",
153  * and noon belongs to "pm", so on the same day,
154  * 12:00 am (midnight) &lt; 12:01 am, and 12:00 pm (noon) &lt; 12:01 pm
155  * </ol>
156  *
157  * <p>
158  * The date or time format strings are not part of the definition of a
159  * calendar, as those must be modifiable or overridable by the user at
160  * runtime. Use {@link DateFormat}
161  * to format dates.
162  *
163  * <p><strong>Field manipulation methods</strong></p>
164  *
165  * <p><code>Calendar</code> fields can be changed using three methods:
166  * <code>set()</code>, <code>add()</code>, and <code>roll()</code>.</p>
167  *
168  * <p><strong><code>set(f, value)</code></strong> changes field
169  * <code>f</code> to <code>value</code>. In addition, it sets an
170  * internal member variable to indicate that field <code>f</code> has
171  * been changed. Although field <code>f</code> is changed immediately,
172  * the calendar's milliseconds is not recomputed until the next call to
173  * <code>get()</code>, <code>getTime()</code>, or
174  * <code>getTimeInMillis()</code> is made. Thus, multiple calls to
175  * <code>set()</code> do not trigger multiple, unnecessary
176  * computations. As a result of changing a field using
177  * <code>set()</code>, other fields may also change, depending on the
178  * field, the field value, and the calendar system. In addition,
179  * <code>get(f)</code> will not necessarily return <code>value</code>
180  * after the fields have been recomputed. The specifics are determined by
181  * the concrete calendar class.</p>
182  *
183  * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
184  * originally set to August 31, 1999. Calling <code>set(Calendar.MONTH,
185  * Calendar.SEPTEMBER)</code> sets the calendar to September 31,
186  * 1999. This is a temporary internal representation that resolves to
187  * October 1, 1999 if <code>getTime()</code>is then called. However, a
188  * call to <code>set(Calendar.DAY_OF_MONTH, 30)</code> before the call to
189  * <code>getTime()</code> sets the calendar to September 30, 1999, since
190  * no recomputation occurs after <code>set()</code> itself.</p>
191  *
192  * <p><strong><code>add(f, delta)</code></strong> adds <code>delta</code>
193  * to field <code>f</code>. This is equivalent to calling <code>set(f,
194  * get(f) + delta)</code> with two adjustments:</p>
195  *
196  * <blockquote>
197  * <p><strong>Add rule 1</strong>. The value of field <code>f</code>
198  * after the call minus the value of field <code>f</code> before the
199  * call is <code>delta</code>, modulo any overflow that has occurred in
200  * field <code>f</code>. Overflow occurs when a field value exceeds its
201  * range and, as a result, the next larger field is incremented or
202  * decremented and the field value is adjusted back into its range.</p>
203  *
204  * <p><strong>Add rule 2</strong>. If a smaller field is expected to be
205  * invariant, but &nbsp; it is impossible for it to be equal to its
206  * prior value because of changes in its minimum or maximum after field
207  * <code>f</code> is changed, then its value is adjusted to be as close
208  * as possible to its expected value. A smaller field represents a
209  * smaller unit of time. <code>HOUR</code> is a smaller field than
210  * <code>DAY_OF_MONTH</code>. No adjustment is made to smaller fields
211  * that are not expected to be invariant. The calendar system
212  * determines what fields are expected to be invariant.</p>
213  * </blockquote>
214  *
215  * <p>In addition, unlike <code>set()</code>, <code>add()</code> forces
216  * an immediate recomputation of the calendar's milliseconds and all
217  * fields.</p>
218  *
219  * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
220  * originally set to August 31, 1999. Calling <code>add(Calendar.MONTH,
221  * 13)</code> sets the calendar to September 30, 2000. <strong>Add rule
222  * 1</strong> sets the <code>MONTH</code> field to September, since
223  * adding 13 months to August gives September of the next year. Since
224  * <code>DAY_OF_MONTH</code> cannot be 31 in September in a
225  * <code>GregorianCalendar</code>, <strong>add rule 2</strong> sets the
226  * <code>DAY_OF_MONTH</code> to 30, the closest possible value. Although
227  * it is a smaller field, <code>DAY_OF_WEEK</code> is not adjusted by
228  * rule 2, since it is expected to change when the month changes in a
229  * <code>GregorianCalendar</code>.</p>
230  *
231  * <p><strong><code>roll(f, delta)</code></strong> adds
232  * <code>delta</code> to field <code>f</code> without changing larger
233  * fields. This is equivalent to calling <code>add(f, delta)</code> with
234  * the following adjustment:</p>
235  *
236  * <blockquote>
237  * <p><strong>Roll rule</strong>. Larger fields are unchanged after the
238  * call. A larger field represents a larger unit of
239  * time. <code>DAY_OF_MONTH</code> is a larger field than
240  * <code>HOUR</code>.</p>
241  * </blockquote>
242  *
243  * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
244  * originally set to August 31, 1999. Calling <code>roll(Calendar.MONTH,
245  * 8)</code> sets the calendar to April 30, <strong>1999</strong>. Add
246  * rule 1 sets the <code>MONTH</code> field to April. Using a
247  * <code>GregorianCalendar</code>, the <code>DAY_OF_MONTH</code> cannot
248  * be 31 in the month April. Add rule 2 sets it to the closest possible
249  * value, 30. Finally, the <strong>roll rule</strong> maintains the
250  * <code>YEAR</code> field value of 1999.</p>
251  *
252  * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
253  * originally set to Sunday June 6, 1999. Calling
254  * <code>roll(Calendar.WEEK_OF_MONTH, -1)</code> sets the calendar to
255  * Tuesday June 1, 1999, whereas calling
256  * <code>add(Calendar.WEEK_OF_MONTH, -1)</code> sets the calendar to
257  * Sunday May 30, 1999. This is because the roll rule imposes an
258  * additional constraint: The <code>MONTH</code> must not change when the
259  * <code>WEEK_OF_MONTH</code> is rolled. Taken together with add rule 1,
260  * the resultant date must be between Tuesday June 1 and Saturday June
261  * 5. According to add rule 2, the <code>DAY_OF_WEEK</code>, an invariant
262  * when changing the <code>WEEK_OF_MONTH</code>, is set to Tuesday, the
263  * closest possible value to Sunday (where Sunday is the first day of the
264  * week).</p>
265  *
266  * <p><strong>Usage model</strong>. To motivate the behavior of
267  * <code>add()</code> and <code>roll()</code>, consider a user interface
268  * component with increment and decrement buttons for the month, day, and
269  * year, and an underlying <code>GregorianCalendar</code>. If the
270  * interface reads January 31, 1999 and the user presses the month
271  * increment button, what should it read? If the underlying
272  * implementation uses <code>set()</code>, it might read March 3, 1999. A
273  * better result would be February 28, 1999. Furthermore, if the user
274  * presses the month increment button again, it should read March 31,
275  * 1999, not March 28, 1999. By saving the original date and using either
276  * <code>add()</code> or <code>roll()</code>, depending on whether larger
277  * fields should be affected, the user interface can behave as most users
278  * will intuitively expect.</p>
279  *
280  * <p><b>Note:</b> You should always use {@link #roll roll} and {@link #add add} rather
281  * than attempting to perform arithmetic operations directly on the fields
282  * of a <tt>Calendar</tt>. It is quite possible for <tt>Calendar</tt> subclasses
283  * to have fields with non-linear behavior, for example missing months
284  * or days during non-leap years. The subclasses' <tt>add</tt> and <tt>roll</tt>
285  * methods will take this into account, while simple arithmetic manipulations
286  * may give invalid results.
287  *
288  * <p><big><big><b>Calendar Architecture in ICU4J</b></big></big></p>
289  *
290  * <p>Recently the implementation of <code>Calendar</code> has changed
291  * significantly in order to better support subclassing. The original
292  * <code>Calendar</code> class was designed to support subclassing, but
293  * it had only one implemented subclass, <code>GregorianCalendar</code>.
294  * With the implementation of several new calendar subclasses, including
295  * the <code>BuddhistCalendar</code>, <code>ChineseCalendar</code>,
296  * <code>HebrewCalendar</code>, <code>IslamicCalendar</code>, and
297  * <code>JapaneseCalendar</code>, the subclassing API has been reworked
298  * thoroughly. This section details the new subclassing API and other
299  * ways in which <code>com.ibm.icu.util.Calendar</code> differs from
300  * <code>java.util.Calendar</code>.
301  * </p>
302  *
303  * <p><big><b>Changes</b></big></p>
304  *
305  * <p>Overview of changes between the classic <code>Calendar</code>
306  * architecture and the new architecture.
307  *
308  * <ul>
309  *
310  * <li>The <code>fields[]</code> array is <code>private</code> now
311  * instead of <code>protected</code>. Subclasses must access it
312  * using the methods {@link #internalSet} and
313  * {@link #internalGet}. <b>Motivation:</b> Subclasses should
314  * not directly access data members.</li>
315  *
316  * <li>The <code>time</code> long word is <code>private</code> now
317  * instead of <code>protected</code>. Subclasses may access it using
318  * the method {@link #internalGetTimeInMillis}, which does not
319  * provoke an update. <b>Motivation:</b> Subclasses should not
320  * directly access data members.</li>
321  *
322  * <li>The scope of responsibility of subclasses has been drastically
323  * reduced. As much functionality as possible is implemented in the
324  * <code>Calendar</code> base class. As a result, it is much easier
325  * to subclass <code>Calendar</code>. <b>Motivation:</b> Subclasses
326  * should not have to reimplement common code. Certain behaviors are
327  * common across calendar systems: The definition and behavior of
328  * week-related fields and time fields, the arithmetic
329  * ({@link #add(int, int) add} and {@link #roll(int, int) roll}) behavior of many
330  * fields, and the field validation system.</li>
331  *
332  * <li>The subclassing API has been completely redesigned.</li>
333  *
334  * <li>The <code>Calendar</code> base class contains some Gregorian
335  * calendar algorithmic support that subclasses can use (specifically
336  * in {@link #handleComputeFields}). Subclasses can use the
337  * methods <code>getGregorianXxx()</code> to obtain precomputed
338  * values. <b>Motivation:</b> This is required by all
339  * <code>Calendar</code> subclasses in order to implement consistent
340  * time zone behavior, and Gregorian-derived systems can use the
341  * already computed data.</li>
342  *
343  * <li>The <code>FIELD_COUNT</code> constant has been removed. Use
344  * {@link #getFieldCount}. In addition, framework API has been
345  * added to allow subclasses to define additional fields.
346  * <b>Motivation: </b>The number of fields is not constant across
347  * calendar systems.</li>
348  *
349  * <li>The range of handled dates has been narrowed from +/-
350  * ~300,000,000 years to +/- ~5,000,000 years. In practical terms
351  * this should not affect clients. However, it does mean that client
352  * code cannot be guaranteed well-behaved results with dates such as
353  * <code>Date(Long.MIN_VALUE)</code> or
354  * <code>Date(Long.MAX_VALUE)</code>. Instead, the
355  * <code>Calendar</code> constants {@link #MIN_DATE},
356  * {@link #MAX_DATE}, {@link #MIN_MILLIS},
357  * {@link #MAX_MILLIS}, {@link #MIN_JULIAN}, and
358  * {@link #MAX_JULIAN} should be used. <b>Motivation:</b> With
359  * the addition of the {@link #JULIAN_DAY} field, Julian day
360  * numbers must be restricted to a 32-bit <code>int</code>. This
361  * restricts the overall supported range. Furthermore, restricting
362  * the supported range simplifies the computations by removing
363  * special case code that was used to accomodate arithmetic overflow
364  * at millis near <code>Long.MIN_VALUE</code> and
365  * <code>Long.MAX_VALUE</code>.</li>
366  *
367  * <li>New fields are implemented: {@link #JULIAN_DAY} defines
368  * single-field specification of the
369  * date. {@link #MILLISECONDS_IN_DAY} defines a single-field
370  * specification of the wall time. {@link #DOW_LOCAL} and
371  * {@link #YEAR_WOY} implement localized day-of-week and
372  * week-of-year behavior.</li>
373  *
374  * <li>Subclasses can access millisecond constants
375  * {@link #ONE_SECOND}, {@link #ONE_MINUTE},
376  * {@link #ONE_HOUR}, {@link #ONE_DAY}, and
377  * {@link #ONE_WEEK} defined in <code>Calendar</code>.</li>
378  *
379  * <li>New API has been added to suport calendar-specific subclasses
380  * of <code>DateFormat</code>.</li>
381  *
382  * <li>Several subclasses have been implemented, representing
383  * various international calendar systems.</li>
384  *
385  * </ul>
386  *
387  * <p><big><b>Subclass API</b></big></p>
388  *
389  * <p>The original <code>Calendar</code> API was based on the experience
390  * of implementing a only a single subclass,
391  * <code>GregorianCalendar</code>. As a result, all of the subclassing
392  * kinks had not been worked out. The new subclassing API has been
393  * refined based on several implemented subclasses. This includes methods
394  * that must be overridden and methods for subclasses to call. Subclasses
395  * no longer have direct access to <code>fields</code> and
396  * <code>stamp</code>. Instead, they have new API to access
397  * these. Subclasses are able to allocate the <code>fields</code> array
398  * through a protected framework method; this allows subclasses to
399  * specify additional fields. </p>
400  *
401  * <p>More functionality has been moved into the base class. The base
402  * class now contains much of the computational machinery to support the
403  * Gregorian calendar. This is based on two things: (1) Many calendars
404  * are based on the Gregorian calendar (such as the Buddhist and Japanese
405  * imperial calendars). (2) <em>All</em> calendars require basic
406  * Gregorian support in order to handle timezone computations. </p>
407  *
408  * <p>Common computations have been moved into
409  * <code>Calendar</code>. Subclasses no longer compute the week related
410  * fields and the time related fields. These are commonly handled for all
411  * calendars by the base class. </p>
412  *
413  * <p><b>Subclass computation of time <tt>=&gt;</tt> fields</b>
414  *
415  * <p>The {@link #ERA}, {@link #YEAR},
416  * {@link #EXTENDED_YEAR}, {@link #MONTH},
417  * {@link #DAY_OF_MONTH}, and {@link #DAY_OF_YEAR} fields are
418  * computed by the subclass, based on the Julian day. All other fields
419  * are computed by <code>Calendar</code>.
420  *
421  * <ul>
422  *
423  * <li>Subclasses should implement {@link #handleComputeFields}
424  * to compute the {@link #ERA}, {@link #YEAR},
425  * {@link #EXTENDED_YEAR}, {@link #MONTH},
426  * {@link #DAY_OF_MONTH}, and {@link #DAY_OF_YEAR} fields,
427  * based on the value of the {@link #JULIAN_DAY} field. If there
428  * are calendar-specific fields not defined by <code>Calendar</code>,
429  * they must also be computed. These are the only fields that the
430  * subclass should compute. All other fields are computed by the base
431  * class, so time and week fields behave in a consistent way across
432  * all calendars. The default version of this method in
433  * <code>Calendar</code> implements a proleptic Gregorian
434  * calendar. Within this method, subclasses may call
435  * <code>getGregorianXxx()</code> to obtain the Gregorian calendar
436  * month, day of month, and extended year for the given date.</li>
437  *
438  * </ul>
439  *
440  * <p><b>Subclass computation of fields <tt>=&gt;</tt> time</b>
441  *
442  * <p>The interpretation of most field values is handled entirely by
443  * <code>Calendar</code>. <code>Calendar</code> determines which fields
444  * are set, which are not, which are set more recently, and so on. In
445  * addition, <code>Calendar</code> handles the computation of the time
446  * from the time fields and handles the week-related fields. The only
447  * thing the subclass must do is determine the extended year, based on
448  * the year fields, and then, given an extended year and a month, it must
449  * return a Julian day number.
450  *
451  * <ul>
452  *
453  * <li>Subclasses should implement {@link #handleGetExtendedYear}
454  * to return the extended year for this calendar system, based on the
455  * {@link #YEAR}, {@link #EXTENDED_YEAR}, and any fields that
456  * the calendar system uses that are larger than a year, such as
457  * {@link #ERA}.</li>
458  *
459  * <li>Subclasses should implement {@link #handleComputeMonthStart}
460  * to return the Julian day number
461  * associated with a month and extended year. This is the Julian day
462  * number of the day before the first day of the month. The month
463  * number is zero-based. This computation should not depend on any
464  * field values.</li>
465  *
466  * </ul>
467  *
468  * <p><b>Other methods</b>
469  *
470  * <ul>
471  *
472  * <li>Subclasses should implement {@link #handleGetMonthLength}
473  * to return the number of days in a
474  * given month of a given extended year. The month number, as always,
475  * is zero-based.</li>
476  *
477  * <li>Subclasses should implement {@link #handleGetYearLength}
478  * to return the number of days in the given
479  * extended year. This method is used by
480  * <tt>computeWeekFields</tt> to compute the
481  * {@link #WEEK_OF_YEAR} and {@link #YEAR_WOY} fields.</li>
482  *
483  * <li>Subclasses should implement {@link #handleGetLimit}
484  * to return the {@link #MINIMUM},
485  * {@link #GREATEST_MINIMUM}, {@link #LEAST_MAXIMUM}, or
486  * {@link #MAXIMUM} of a field, depending on the value of
487  * <code>limitType</code>. This method only needs to handle the
488  * fields {@link #ERA}, {@link #YEAR}, {@link #MONTH},
489  * {@link #WEEK_OF_YEAR}, {@link #WEEK_OF_MONTH},
490  * {@link #DAY_OF_MONTH}, {@link #DAY_OF_YEAR},
491  * {@link #DAY_OF_WEEK_IN_MONTH}, {@link #YEAR_WOY}, and
492  * {@link #EXTENDED_YEAR}. Other fields are invariant (with
493  * respect to calendar system) and are handled by the base
494  * class.</li>
495  *
496  * <li>Optionally, subclasses may override {@link #validateField}
497  * to check any subclass-specific fields. If the
498  * field's value is out of range, the method should throw an
499  * <code>IllegalArgumentException</code>. The method may call
500  * <code>super.validateField(field)</code> to handle fields in a
501  * generic way, that is, to compare them to the range
502  * <code>getMinimum(field)</code>..<code>getMaximum(field)</code>.</li>
503  *
504  * <li>Optionally, subclasses may override
505  * {@link #handleCreateFields} to create an <code>int[]</code>
506  * array large enough to hold the calendar's fields. This is only
507  * necessary if the calendar defines additional fields beyond those
508  * defined by <code>Calendar</code>. The length of the result must be
509  * at least {@link #BASE_FIELD_COUNT} and no more than
510  * {@link #MAX_FIELD_COUNT}.</li>
511  *
512  * <li>Optionally, subclasses may override
513  * {@link #handleGetDateFormat} to create a
514  * <code>DateFormat</code> appropriate to this calendar. This is only
515  * required if a calendar subclass redefines the use of a field (for
516  * example, changes the {@link #ERA} field from a symbolic field
517  * to a numeric one) or defines an additional field.</li>
518  *
519  * <li>Optionally, subclasses may override {@link #roll roll} and
520  * {@link #add add} to handle fields that are discontinuous. For
521  * example, in the Hebrew calendar the month &quot;Adar I&quot; only
522  * occurs in leap years; in other years the calendar jumps from
523  * Shevat (month #4) to Adar (month #6). The {@link
524  * HebrewCalendar#add HebrewCalendar.add} and {@link
525  * HebrewCalendar#roll HebrewCalendar.roll} methods take this into
526  * account, so that adding 1 month to Shevat gives the proper result
527  * (Adar) in a non-leap year. The protected utility method {@link
528  * #pinField pinField} is often useful when implementing these two
529  * methods. </li>
530  *
531  * </ul>
532  *
533  * <p><big><b>Normalized behavior</b></big>
534  *
535  * <p>The behavior of certain fields has been made consistent across all
536  * calendar systems and implemented in <code>Calendar</code>.
537  *
538  * <ul>
539  *
540  * <li>Time is normalized. Even though some calendar systems transition
541  * between days at sunset or at other times, all ICU4J calendars
542  * transition between days at <em>local zone midnight</em>. This
543  * allows ICU4J to centralize the time computations in
544  * <code>Calendar</code> and to maintain basic correpsondences
545  * between calendar systems. Affected fields: {@link #AM_PM},
546  * {@link #HOUR}, {@link #HOUR_OF_DAY}, {@link #MINUTE},
547  * {@link #SECOND}, {@link #MILLISECOND},
548  * {@link #ZONE_OFFSET}, and {@link #DST_OFFSET}.</li>
549  *
550  * <li>DST behavior is normalized. Daylight savings time behavior is
551  * computed the same for all calendar systems, and depends on the
552  * value of several <code>GregorianCalendar</code> fields: the
553  * {@link #YEAR}, {@link #MONTH}, and
554  * {@link #DAY_OF_MONTH}. As a result, <code>Calendar</code>
555  * always computes these fields, even for non-Gregorian calendar
556  * systems. These fields are available to subclasses.</li>
557  *
558  * <li>Weeks are normalized. Although locales define the week
559  * differently, in terms of the day on which it starts, and the
560  * designation of week number one of a month or year, they all use a
561  * common mechanism. Furthermore, the day of the week has a simple
562  * and consistent definition throughout history. For example,
563  * although the Gregorian calendar introduced a discontinuity when
564  * first instituted, the day of week was not disrupted. For this
565  * reason, the fields {@link #DAY_OF_WEEK}, <code>WEEK_OF_YEAR,
566  * WEEK_OF_MONTH</code>, {@link #DAY_OF_WEEK_IN_MONTH},
567  * {@link #DOW_LOCAL}, {@link #YEAR_WOY} are all computed in
568  * a consistent way in the base class, based on the
569  * {@link #EXTENDED_YEAR}, {@link #DAY_OF_YEAR},
570  * {@link #MONTH}, and {@link #DAY_OF_MONTH}, which are
571  * computed by the subclass.</li>
572  *
573  * </ul>
574  *
575  * <p><big><b>Supported range</b></big>
576  *
577  * <p>The allowable range of <code>Calendar</code> has been
578  * narrowed. <code>GregorianCalendar</code> used to attempt to support
579  * the range of dates with millisecond values from
580  * <code>Long.MIN_VALUE</code> to <code>Long.MAX_VALUE</code>. This
581  * introduced awkward constructions (hacks) which slowed down
582  * performance. It also introduced non-uniform behavior at the
583  * boundaries. The new <code>Calendar</code> protocol specifies the
584  * maximum range of supportable dates as those having Julian day numbers
585  * of <code>-0x7F000000</code> to <code>+0x7F000000</code>. This
586  * corresponds to years from ~5,000,000 BCE to ~5,000,000 CE. Programmers
587  * should use the constants {@link #MIN_DATE} (or
588  * {@link #MIN_MILLIS} or {@link #MIN_JULIAN}) and
589  * {@link #MAX_DATE} (or {@link #MAX_MILLIS} or
590  * {@link #MAX_JULIAN}) in <code>Calendar</code> to specify an
591  * extremely early or extremely late date.</p>
592  *
593  * <p><big><b>General notes</b></big>
594  *
595  * <ul>
596  *
597  * <li>Calendars implementations are <em>proleptic</em>. For example,
598  * even though the Gregorian calendar was not instituted until the
599  * 16th century, the <code>GregorianCalendar</code> class supports
600  * dates before the historical onset of the calendar by extending the
601  * calendar system backward in time. Similarly, the
602  * <code>HebrewCalendar</code> extends backward before the start of
603  * its epoch into zero and negative years. Subclasses do not throw
604  * exceptions because a date precedes the historical start of a
605  * calendar system. Instead, they implement
606  * {@link #handleGetLimit} to return appropriate limits on
607  * {@link #YEAR}, {@link #ERA}, etc. fields. Then, if the
608  * calendar is set to not be lenient, out-of-range field values will
609  * trigger an exception.</li>
610  *
611  * <li>Calendar system subclasses compute a <em>extended
612  * year</em>. This differs from the {@link #YEAR} field in that
613  * it ranges over all integer values, including zero and negative
614  * values, and it encapsulates the information of the
615  * {@link #YEAR} field and all larger fields. Thus, for the
616  * Gregorian calendar, the {@link #EXTENDED_YEAR} is computed as
617  * <code>ERA==AD ? YEAR : 1-YEAR</code>. Another example is the Mayan
618  * long count, which has years (<code>KUN</code>) and nested cycles
619  * of years (<code>KATUN</code> and <code>BAKTUN</code>). The Mayan
620  * {@link #EXTENDED_YEAR} is computed as <code>TUN + 20 * (KATUN
621  * + 20 * BAKTUN)</code>. The <code>Calendar</code> base class uses
622  * the {@link #EXTENDED_YEAR} field to compute the week-related
623  * fields.</li>
624  *
625  * </ul>
626  *
627  * @see Date
628  * @see GregorianCalendar
629  * @see TimeZone
630  * @see DateFormat
631  * @author Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu, Laura Werner
632  * @stable ICU 2.0
633  */

634 public abstract class Calendar implements Serializable JavaDoc, Cloneable JavaDoc, Comparable JavaDoc {
635
636     // Data flow in Calendar
637
// ---------------------
638

639     // The current time is represented in two ways by Calendar: as UTC
640
// milliseconds from the epoch start (1 January 1970 0:00 UTC), and as local
641
// fields such as MONTH, HOUR, AM_PM, etc. It is possible to compute the
642
// millis from the fields, and vice versa. The data needed to do this
643
// conversion is encapsulated by a TimeZone object owned by the Calendar.
644
// The data provided by the TimeZone object may also be overridden if the
645
// user sets the ZONE_OFFSET and/or DST_OFFSET fields directly. The class
646
// keeps track of what information was most recently set by the caller, and
647
// uses that to compute any other information as needed.
648

649     // If the user sets the fields using set(), the data flow is as follows.
650
// This is implemented by the Calendar subclass's computeTime() method.
651
// During this process, certain fields may be ignored. The disambiguation
652
// algorithm for resolving which fields to pay attention to is described
653
// above.
654

655     // local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
656
// |
657
// | Using Calendar-specific algorithm
658
// V
659
// local standard millis
660
// |
661
// | Using TimeZone or user-set ZONE_OFFSET / DST_OFFSET
662
// V
663
// UTC millis (in time data member)
664

665     // If the user sets the UTC millis using setTime(), the data flow is as
666
// follows. This is implemented by the Calendar subclass's computeFields()
667
// method.
668

669     // UTC millis (in time data member)
670
// |
671
// | Using TimeZone getOffset()
672
// V
673
// local standard millis
674
// |
675
// | Using Calendar-specific algorithm
676
// V
677
// local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
678

679     // In general, a round trip from fields, through local and UTC millis, and
680
// back out to fields is made when necessary. This is implemented by the
681
// complete() method. Resolving a partial set of fields into a UTC millis
682
// value allows all remaining fields to be generated from that value. If
683
// the Calendar is lenient, the fields are also renormalized to standard
684
// ranges when they are regenerated.
685

686     /**
687      * Field number for <code>get</code> and <code>set</code> indicating the
688      * era, e.g., AD or BC in the Julian calendar. This is a calendar-specific
689      * value; see subclass documentation.
690      * @see GregorianCalendar#AD
691      * @see GregorianCalendar#BC
692      * @stable ICU 2.0
693      */

694     public final static int ERA = 0;
695
696     /**
697      * Field number for <code>get</code> and <code>set</code> indicating the
698      * year. This is a calendar-specific value; see subclass documentation.
699      * @stable ICU 2.0
700      */

701     public final static int YEAR = 1;
702
703     /**
704      * Field number for <code>get</code> and <code>set</code> indicating the
705      * month. This is a calendar-specific value. The first month of the year is
706      * <code>JANUARY</code>; the last depends on the number of months in a year.
707      * @see #JANUARY
708      * @see #FEBRUARY
709      * @see #MARCH
710      * @see #APRIL
711      * @see #MAY
712      * @see #JUNE
713      * @see #JULY
714      * @see #AUGUST
715      * @see #SEPTEMBER
716      * @see #OCTOBER
717      * @see #NOVEMBER
718      * @see #DECEMBER
719      * @see #UNDECIMBER
720      * @stable ICU 2.0
721      */

722     public final static int MONTH = 2;
723
724     /**
725      * Field number for <code>get</code> and <code>set</code> indicating the
726      * week number within the current year. The first week of the year, as
727      * defined by <code>getFirstDayOfWeek()</code> and
728      * <code>getMinimalDaysInFirstWeek()</code>, has value 1. Subclasses define
729      * the value of <code>WEEK_OF_YEAR</code> for days before the first week of
730      * the year.
731      * @see #getFirstDayOfWeek
732      * @see #getMinimalDaysInFirstWeek
733      * @stable ICU 2.0
734      */

735     public final static int WEEK_OF_YEAR = 3;
736
737     /**
738      * Field number for <code>get</code> and <code>set</code> indicating the
739      * week number within the current month. The first week of the month, as
740      * defined by <code>getFirstDayOfWeek()</code> and
741      * <code>getMinimalDaysInFirstWeek()</code>, has value 1. Subclasses define
742      * the value of <code>WEEK_OF_MONTH</code> for days before the first week of
743      * the month.
744      * @see #getFirstDayOfWeek
745      * @see #getMinimalDaysInFirstWeek
746      * @stable ICU 2.0
747      */

748     public final static int WEEK_OF_MONTH = 4;
749
750     /**
751      * Field number for <code>get</code> and <code>set</code> indicating the
752      * day of the month. This is a synonym for <code>DAY_OF_MONTH</code>.
753      * The first day of the month has value 1.
754      * @see #DAY_OF_MONTH
755      * @stable ICU 2.0
756      */

757     public final static int DATE = 5;
758
759     /**
760      * Field number for <code>get</code> and <code>set</code> indicating the
761      * day of the month. This is a synonym for <code>DATE</code>.
762      * The first day of the month has value 1.
763      * @see #DATE
764      * @stable ICU 2.0
765      */

766     public final static int DAY_OF_MONTH = 5;
767
768     /**
769      * Field number for <code>get</code> and <code>set</code> indicating the day
770      * number within the current year. The first day of the year has value 1.
771      * @stable ICU 2.0
772      */

773     public final static int DAY_OF_YEAR = 6;
774
775     /**
776      * Field number for <code>get</code> and <code>set</code> indicating the day
777      * of the week. This field takes values <code>SUNDAY</code>,
778      * <code>MONDAY</code>, <code>TUESDAY</code>, <code>WEDNESDAY</code>,
779      * <code>THURSDAY</code>, <code>FRIDAY</code>, and <code>SATURDAY</code>.
780      * @see #SUNDAY
781      * @see #MONDAY
782      * @see #TUESDAY
783      * @see #WEDNESDAY
784      * @see #THURSDAY
785      * @see #FRIDAY
786      * @see #SATURDAY
787      * @stable ICU 2.0
788      */

789     public final static int DAY_OF_WEEK = 7;
790
791     /**
792      * Field number for <code>get</code> and <code>set</code> indicating the
793      * ordinal number of the day of the week within the current month. Together
794      * with the <code>DAY_OF_WEEK</code> field, this uniquely specifies a day
795      * within a month. Unlike <code>WEEK_OF_MONTH</code> and
796      * <code>WEEK_OF_YEAR</code>, this field's value does <em>not</em> depend on
797      * <code>getFirstDayOfWeek()</code> or
798      * <code>getMinimalDaysInFirstWeek()</code>. <code>DAY_OF_MONTH 1</code>
799      * through <code>7</code> always correspond to <code>DAY_OF_WEEK_IN_MONTH
800      * 1</code>; <code>8</code> through <code>15</code> correspond to
801      * <code>DAY_OF_WEEK_IN_MONTH 2</code>, and so on.
802      * <code>DAY_OF_WEEK_IN_MONTH 0</code> indicates the week before
803      * <code>DAY_OF_WEEK_IN_MONTH 1</code>. Negative values count back from the
804      * end of the month, so the last Sunday of a month is specified as
805      * <code>DAY_OF_WEEK = SUNDAY, DAY_OF_WEEK_IN_MONTH = -1</code>. Because
806      * negative values count backward they will usually be aligned differently
807      * within the month than positive values. For example, if a month has 31
808      * days, <code>DAY_OF_WEEK_IN_MONTH -1</code> will overlap
809      * <code>DAY_OF_WEEK_IN_MONTH 5</code> and the end of <code>4</code>.
810      * @see #DAY_OF_WEEK
811      * @see #WEEK_OF_MONTH
812      * @stable ICU 2.0
813      */

814     public final static int DAY_OF_WEEK_IN_MONTH = 8;
815
816     /**
817      * Field number for <code>get</code> and <code>set</code> indicating
818      * whether the <code>HOUR</code> is before or after noon.
819      * E.g., at 10:04:15.250 PM the <code>AM_PM</code> is <code>PM</code>.
820      * @see #AM
821      * @see #PM
822      * @see #HOUR
823      * @stable ICU 2.0
824      */

825     public final static int AM_PM = 9;
826
827     /**
828      * Field number for <code>get</code> and <code>set</code> indicating the
829      * hour of the morning or afternoon. <code>HOUR</code> is used for the 12-hour
830      * clock.
831      * E.g., at 10:04:15.250 PM the <code>HOUR</code> is 10.
832      * @see #AM_PM
833      * @see #HOUR_OF_DAY
834      * @stable ICU 2.0
835      */

836     public final static int HOUR = 10;
837
838     /**
839      * Field number for <code>get</code> and <code>set</code> indicating the
840      * hour of the day. <code>HOUR_OF_DAY</code> is used for the 24-hour clock.
841      * E.g., at 10:04:15.250 PM the <code>HOUR_OF_DAY</code> is 22.
842      * @see #HOUR
843      * @stable ICU 2.0
844      */

845     public final static int HOUR_OF_DAY = 11;
846
847     /**
848      * Field number for <code>get</code> and <code>set</code> indicating the
849      * minute within the hour.
850      * E.g., at 10:04:15.250 PM the <code>MINUTE</code> is 4.
851      * @stable ICU 2.0
852      */

853     public final static int MINUTE = 12;
854
855     /**
856      * Field number for <code>get</code> and <code>set</code> indicating the
857      * second within the minute.
858      * E.g., at 10:04:15.250 PM the <code>SECOND</code> is 15.
859      * @stable ICU 2.0
860      */

861     public final static int SECOND = 13;
862
863     /**
864      * Field number for <code>get</code> and <code>set</code> indicating the
865      * millisecond within the second.
866      * E.g., at 10:04:15.250 PM the <code>MILLISECOND</code> is 250.
867      * @stable ICU 2.0
868      */

869     public final static int MILLISECOND = 14;
870
871     /**
872      * Field number for <code>get</code> and <code>set</code> indicating the
873      * raw offset from GMT in milliseconds.
874      * @stable ICU 2.0
875      */

876     public final static int ZONE_OFFSET = 15;
877
878     /**
879      * Field number for <code>get</code> and <code>set</code> indicating the
880      * daylight savings offset in milliseconds.
881      * @stable ICU 2.0
882      */

883     public final static int DST_OFFSET = 16;
884
885     /**
886      * Field number for <code>get()</code> and <code>set()</code>
887      * indicating the extended year corresponding to the
888      * <code>WEEK_OF_YEAR</code> field. This may be one greater or less
889      * than the value of <code>EXTENDED_YEAR</code>.
890      * @stable ICU 2.0
891      */

892     public static final int YEAR_WOY = 17;
893
894     /**
895      * Field number for <code>get()</code> and <code>set()</code>
896      * indicating the localized day of week. This will be a value from 1
897      * to 7 inclusive, with 1 being the localized first day of the week.
898      * @stable ICU 2.0
899      */

900     public static final int DOW_LOCAL = 18;
901
902     /**
903      * Field number for <code>get()</code> and <code>set()</code>
904      * indicating the extended year. This is a single number designating
905      * the year of this calendar system, encompassing all supra-year
906      * fields. For example, for the Julian calendar system, year numbers
907      * are positive, with an era of BCE or CE. An extended year value for
908      * the Julian calendar system assigns positive values to CE years and
909      * negative values to BCE years, with 1 BCE being year 0.
910      * @stable ICU 2.0
911      */

912     public static final int EXTENDED_YEAR = 19;
913
914     /**
915      * Field number for <code>get()</code> and <code>set()</code>
916      * indicating the modified Julian day number. This is different from
917      * the conventional Julian day number in two regards. First, it
918      * demarcates days at local zone midnight, rather than noon GMT.
919      * Second, it is a local number; that is, it depends on the local time
920      * zone. It can be thought of as a single number that encompasses all
921      * the date-related fields.
922      * @stable ICU 2.0
923      */

924     public static final int JULIAN_DAY = 20;
925
926     /**
927      * Field number for <code>get()</code> and <code>set()</code>
928      * indicating the milliseconds in the day. This ranges from 0 to
929      * 23:59:59.999 (regardless of DST). This field behaves
930      * <em>exactly</em> like a composite of all time-related fields, not
931      * including the zone fields. As such, it also reflects
932      * discontinuities of those fields on DST transition days. On a day of
933      * DST onset, it will jump forward. On a day of DST cessation, it will
934      * jump backward. This reflects the fact that is must be combined with
935      * the DST_OFFSET field to obtain a unique local time value.
936      * @stable ICU 2.0
937      */

938     public static final int MILLISECONDS_IN_DAY = 21;
939
940     /**
941      * The number of fields defined by this class. Subclasses may define
942      * addition fields starting with this number.
943      * @stable ICU 2.0
944      */

945     protected static final int BASE_FIELD_COUNT = 22;
946
947     /**
948      * The maximum number of fields possible. Subclasses must not define
949      * more total fields than this number.
950      * @stable ICU 2.0
951      */

952     protected static final int MAX_FIELD_COUNT = 32;
953
954     /**
955      * Value of the <code>DAY_OF_WEEK</code> field indicating
956      * Sunday.
957      * @stable ICU 2.0
958      */

959     public final static int SUNDAY = 1;
960
961     /**
962      * Value of the <code>DAY_OF_WEEK</code> field indicating
963      * Monday.
964      * @stable ICU 2.0
965      */

966     public final static int MONDAY = 2;
967
968     /**
969      * Value of the <code>DAY_OF_WEEK</code> field indicating
970      * Tuesday.
971      * @stable ICU 2.0
972      */

973     public final static int TUESDAY = 3;
974
975     /**
976      * Value of the <code>DAY_OF_WEEK</code> field indicating
977      * Wednesday.
978      * @stable ICU 2.0
979      */

980     public final static int WEDNESDAY = 4;
981
982     /**
983      * Value of the <code>DAY_OF_WEEK</code> field indicating
984      * Thursday.
985      * @stable ICU 2.0
986      */

987     public final static int THURSDAY = 5;
988
989     /**
990      * Value of the <code>DAY_OF_WEEK</code> field indicating
991      * Friday.
992      * @stable ICU 2.0
993      */

994     public final static int FRIDAY = 6;
995
996     /**
997      * Value of the <code>DAY_OF_WEEK</code> field indicating
998      * Saturday.
999      * @stable ICU 2.0
1000     */

1001    public final static int SATURDAY = 7;
1002
1003    /**
1004     * Value of the <code>MONTH</code> field indicating the
1005     * first month of the year.
1006     * @stable ICU 2.0
1007     */

1008    public final static int JANUARY = 0;
1009
1010    /**
1011     * Value of the <code>MONTH</code> field indicating the
1012     * second month of the year.
1013     * @stable ICU 2.0
1014     */

1015    public final static int FEBRUARY = 1;
1016
1017    /**
1018     * Value of the <code>MONTH</code> field indicating the
1019     * third month of the year.
1020     * @stable ICU 2.0
1021     */

1022    public final static int MARCH = 2;
1023
1024    /**
1025     * Value of the <code>MONTH</code> field indicating the
1026     * fourth month of the year.
1027     * @stable ICU 2.0
1028     */

1029    public final static int APRIL = 3;
1030
1031    /**
1032     * Value of the <code>MONTH</code> field indicating the
1033     * fifth month of the year.
1034     * @stable ICU 2.0
1035     */

1036    public final static int MAY = 4;
1037
1038    /**
1039     * Value of the <code>MONTH</code> field indicating the
1040     * sixth month of the year.
1041     * @stable ICU 2.0
1042     */

1043    public final static int JUNE = 5;
1044
1045    /**
1046     * Value of the <code>MONTH</code> field indicating the
1047     * seventh month of the year.
1048     * @stable ICU 2.0
1049     */

1050    public final static int JULY = 6;
1051
1052    /**
1053     * Value of the <code>MONTH</code> field indicating the
1054     * eighth month of the year.
1055     * @stable ICU 2.0
1056     */

1057    public final static int AUGUST = 7;
1058
1059    /**
1060     * Value of the <code>MONTH</code> field indicating the
1061     * ninth month of the year.
1062     * @stable ICU 2.0
1063     */

1064    public final static int SEPTEMBER = 8;
1065
1066    /**
1067     * Value of the <code>MONTH</code> field indicating the
1068     * tenth month of the year.
1069     * @stable ICU 2.0
1070     */

1071    public final static int OCTOBER = 9;
1072
1073    /**
1074     * Value of the <code>MONTH</code> field indicating the
1075     * eleventh month of the year.
1076     * @stable ICU 2.0
1077     */

1078    public final static int NOVEMBER = 10;
1079
1080    /**
1081     * Value of the <code>MONTH</code> field indicating the
1082     * twelfth month of the year.
1083     * @stable ICU 2.0
1084     */

1085    public final static int DECEMBER = 11;
1086
1087    /**
1088     * Value of the <code>MONTH</code> field indicating the
1089     * thirteenth month of the year. Although <code>GregorianCalendar</code>
1090     * does not use this value, lunar calendars do.
1091     * @stable ICU 2.0
1092     */

1093    public final static int UNDECIMBER = 12;
1094
1095    /**
1096     * Value of the <code>AM_PM</code> field indicating the
1097     * period of the day from midnight to just before noon.
1098     * @stable ICU 2.0
1099     */

1100    public final static int AM = 0;
1101
1102    /**
1103     * Value of the <code>AM_PM</code> field indicating the
1104     * period of the day from noon to just before midnight.
1105     * @stable ICU 2.0
1106     */

1107    public final static int PM = 1;
1108
1109    /**
1110     * Value returned by getDayOfWeekType(int dayOfWeek) to indicate a
1111     * weekday.
1112     * @see #WEEKEND
1113     * @see #WEEKEND_ONSET
1114     * @see #WEEKEND_CEASE
1115     * @see #getDayOfWeekType
1116     * @stable ICU 2.0
1117     */

1118    public static final int WEEKDAY = 0;
1119
1120    /**
1121     * Value returned by getDayOfWeekType(int dayOfWeek) to indicate a
1122     * weekend day.
1123     * @see #WEEKDAY
1124     * @see #WEEKEND_ONSET
1125     * @see #WEEKEND_CEASE
1126     * @see #getDayOfWeekType
1127     * @stable ICU 2.0
1128     */

1129    public static final int WEEKEND = 1;
1130
1131    /**
1132     * Value returned by getDayOfWeekType(int dayOfWeek) to indicate a
1133     * day that starts as a weekday and transitions to the weekend.
1134     * Call getWeekendTransition() to get the point of transition.
1135     * @see #WEEKDAY
1136     * @see #WEEKEND
1137     * @see #WEEKEND_CEASE
1138     * @see #getDayOfWeekType
1139     * @stable ICU 2.0
1140     */

1141    public static final int WEEKEND_ONSET = 2;
1142
1143    /**
1144     * Value returned by getDayOfWeekType(int dayOfWeek) to indicate a
1145     * day that starts as the weekend and transitions to a weekday.
1146     * Call getWeekendTransition() to get the point of transition.
1147     * @see #WEEKDAY
1148     * @see #WEEKEND
1149     * @see #WEEKEND_ONSET
1150     * @see #getDayOfWeekType
1151     * @stable ICU 2.0
1152     */

1153    public static final int WEEKEND_CEASE = 3;
1154
1155    /**
1156     * The number of milliseconds in one second.
1157     * @stable ICU 2.0
1158     */

1159    protected static final int ONE_SECOND = 1000;
1160
1161    /**
1162     * The number of milliseconds in one minute.
1163     * @stable ICU 2.0
1164     */

1165    protected static final int ONE_MINUTE = 60*ONE_SECOND;
1166
1167    /**
1168     * The number of milliseconds in one hour.
1169     * @stable ICU 2.0
1170     */

1171    protected static final int ONE_HOUR = 60*ONE_MINUTE;
1172
1173    /**
1174     * The number of milliseconds in one day. Although ONE_DAY and
1175     * ONE_WEEK can fit into ints, they must be longs in order to prevent
1176     * arithmetic overflow when performing (bug 4173516).
1177     * @stable ICU 2.0
1178     */

1179    protected static final long ONE_DAY = 24*ONE_HOUR;
1180
1181    /**
1182     * The number of milliseconds in one week. Although ONE_DAY and
1183     * ONE_WEEK can fit into ints, they must be longs in order to prevent
1184     * arithmetic overflow when performing (bug 4173516).
1185     * @stable ICU 2.0
1186     */

1187    protected static final long ONE_WEEK = 7*ONE_DAY;
1188
1189    /**
1190     * The Julian day of the Gregorian epoch, that is, January 1, 1 on the
1191     * Gregorian calendar.
1192     * @stable ICU 2.0
1193     */

1194    protected static final int JAN_1_1_JULIAN_DAY = 1721426;
1195
1196    /**
1197     * The Julian day of the epoch, that is, January 1, 1970 on the
1198     * Gregorian calendar.
1199     * @stable ICU 2.0
1200     */

1201    protected static final int EPOCH_JULIAN_DAY = 2440588;
1202
1203    /**
1204     * The minimum supported Julian day. This value is equivalent to
1205     * <code>MIN_MILLIS</code> and <code>MIN_DATE</code>.
1206     * @see #JULIAN_DAY
1207     * @stable ICU 2.0
1208     */

1209    protected static final int MIN_JULIAN = -0x7F000000;
1210
1211    /**
1212     * The minimum supported epoch milliseconds. This value is equivalent
1213     * to <code>MIN_JULIAN</code> and <code>MIN_DATE</code>.
1214     * @stable ICU 2.0
1215     */

1216    protected static final long MIN_MILLIS = -184303902528000000L;
1217
1218    // Get around bug in jikes 1.12 for now. Later, use:
1219
//protected static final long MIN_MILLIS = (MIN_JULIAN - EPOCH_JULIAN_DAY) * ONE_DAY;
1220

1221    /**
1222     * The minimum supported <code>Date</code>. This value is equivalent
1223     * to <code>MIN_JULIAN</code> and <code>MIN_MILLIS</code>.
1224     * @stable ICU 2.0
1225     */

1226    protected static final Date JavaDoc MIN_DATE = new Date JavaDoc(MIN_MILLIS);
1227
1228    /**
1229     * The maximum supported Julian day. This value is equivalent to
1230     * <code>MAX_MILLIS</code> and <code>MAX_DATE</code>.
1231     * @see #JULIAN_DAY
1232     * @stable ICU 2.0
1233     */

1234    protected static final int MAX_JULIAN = +0x7F000000;
1235
1236    /**
1237     * The maximum supported epoch milliseconds. This value is equivalent
1238     * to <code>MAX_JULIAN</code> and <code>MAX_DATE</code>.
1239     * @stable ICU 2.0
1240     */

1241    protected static final long MAX_MILLIS = (MAX_JULIAN - EPOCH_JULIAN_DAY) * ONE_DAY;
1242
1243    /**
1244     * The maximum supported <code>Date</code>. This value is equivalent
1245     * to <code>MAX_JULIAN</code> and <code>MAX_MILLIS</code>.
1246     * @stable ICU 2.0
1247     */

1248    protected static final Date JavaDoc MAX_DATE = new Date JavaDoc(MAX_MILLIS);
1249
1250    // Internal notes:
1251
// Calendar contains two kinds of time representations: current "time" in
1252
// milliseconds, and a set of time "fields" representing the current time.
1253
// The two representations are usually in sync, but can get out of sync
1254
// as follows.
1255
// 1. Initially, no fields are set, and the time is invalid.
1256
// 2. If the time is set, all fields are computed and in sync.
1257
// 3. If a single field is set, the time is invalid.
1258
// Recomputation of the time and fields happens when the object needs
1259
// to return a result to the user, or use a result for a computation.
1260

1261    /**
1262     * The field values for the currently set time for this calendar.
1263     * This is an array of at least <code>BASE_FIELD_COUNT</code> integers.
1264     * @see #handleCreateFields
1265     * @serial
1266     */

1267    private transient int fields[];
1268
1269    /**
1270     * Pseudo-time-stamps which specify when each field was set. There
1271     * are two special values, UNSET and INTERNALLY_SET. Values from
1272     * MINIMUM_USER_SET to Integer.MAX_VALUE are legal user set values.
1273     */

1274    private transient int stamp[];
1275
1276    /**
1277     * The currently set time for this calendar, expressed in milliseconds after
1278     * January 1, 1970, 0:00:00 GMT.
1279     * @see <tt>isTimeSet</tt>
1280     * @serial
1281     */

1282    private long time;
1283
1284    /**
1285     * True if then the value of <code>time</code> is valid.
1286     * The time is made invalid by a change to an item of <code>field[]</code>.
1287     * @see #time
1288     * @serial
1289     */

1290    private transient boolean isTimeSet;
1291
1292    /**
1293     * True if <code>fields[]</code> are in sync with the currently set time.
1294     * If false, then the next attempt to get the value of a field will
1295     * force a recomputation of all fields from the current value of
1296     * <code>time</code>.
1297     * @serial
1298     */

1299    private transient boolean areFieldsSet;
1300
1301    /**
1302     * True if all fields have been set. This is only false in a few
1303     * situations: In a newly created, partially constructed object. After
1304     * a call to clear(). In an object just read from a stream using
1305     * readObject(). Once computeFields() has been called this is set to
1306     * true and stays true until one of the above situations recurs.
1307     * @serial
1308     */

1309    private transient boolean areAllFieldsSet;
1310
1311    /**
1312     * True if all fields have been virtually set, but have not yet been
1313     * computed. This occurs only in setTimeInMillis(). A calendar set
1314     * to this state will compute all fields from the time if it becomes
1315     * necessary, but otherwise will delay such computation.
1316     */

1317    private transient boolean areFieldsVirtuallySet;
1318
1319    /**
1320     * True if this calendar allows out-of-range field values during computation
1321     * of <code>time</code> from <code>fields[]</code>.
1322     * @see #setLenient
1323     * @serial
1324     */

1325    private boolean lenient = true;
1326
1327    /**
1328     * The <code>TimeZone</code> used by this calendar. </code>Calendar</code>
1329     * uses the time zone data to translate between locale and GMT time.
1330     * @serial
1331     */

1332    private TimeZone zone;
1333
1334    /**
1335     * The first day of the week, with possible values <code>SUNDAY</code>,
1336     * <code>MONDAY</code>, etc. This is a locale-dependent value.
1337     * @serial
1338     */

1339    private int firstDayOfWeek;
1340
1341    /**
1342     * The number of days required for the first week in a month or year,
1343     * with possible values from 1 to 7. This is a locale-dependent value.
1344     * @serial
1345     */

1346    private int minimalDaysInFirstWeek;
1347
1348    /**
1349     * First day of the weekend in this calendar's locale. Must be in
1350     * the range SUNDAY...SATURDAY (1..7). The weekend starts at
1351     * weekendOnsetMillis milliseconds after midnight on that day of
1352     * the week. This value is taken from locale resource data.
1353     */

1354    private int weekendOnset;
1355
1356    /**
1357     * Milliseconds after midnight at which the weekend starts on the
1358     * day of the week weekendOnset. Times that are greater than or
1359     * equal to weekendOnsetMillis are considered part of the weekend.
1360     * Must be in the range 0..24*60*60*1000-1. This value is taken
1361     * from locale resource data.
1362     */

1363    private int weekendOnsetMillis;
1364
1365    /**
1366     * Day of the week when the weekend stops in this calendar's
1367     * locale. Must be in the range SUNDAY...SATURDAY (1..7). The
1368     * weekend stops at weekendCeaseMillis milliseconds after midnight
1369     * on that day of the week. This value is taken from locale
1370     * resource data.
1371     */

1372    private int weekendCease;
1373
1374    /**
1375     * Milliseconds after midnight at which the weekend stops on the
1376     * day of the week weekendCease. Times that are greater than or
1377     * equal to weekendCeaseMillis are considered not to be the
1378     * weekend. Must be in the range 0..24*60*60*1000-1. This value
1379     * is taken from locale resource data.
1380     */

1381    private int weekendCeaseMillis;
1382
1383    /**
1384     * Cache to hold the firstDayOfWeek and minimalDaysInFirstWeek
1385     * of a Locale.
1386     */

1387    private static Hashtable JavaDoc cachedLocaleData = new Hashtable JavaDoc(3);
1388
1389    /**
1390     * Value of the time stamp <code>stamp[]</code> indicating that
1391     * a field has not been set since the last call to <code>clear()</code>.
1392     * @see #INTERNALLY_SET
1393     * @see #MINIMUM_USER_STAMP
1394     * @stable ICU 2.0
1395     */

1396    protected static final int UNSET = 0;
1397
1398    /**
1399     * Value of the time stamp <code>stamp[]</code> indicating that a field
1400     * has been set via computations from the time or from other fields.
1401     * @see #UNSET
1402     * @see #MINIMUM_USER_STAMP
1403     * @stable ICU 2.0
1404     */

1405    protected static final int INTERNALLY_SET = 1;
1406
1407    /**
1408     * If the time stamp <code>stamp[]</code> has a value greater than or
1409     * equal to <code>MINIMUM_USER_SET</code> then it has been set by the
1410     * user via a call to <code>set()</code>.
1411     * @see #UNSET
1412     * @see #INTERNALLY_SET
1413     * @stable ICU 2.0
1414     */

1415    protected static final int MINIMUM_USER_STAMP = 2;
1416
1417    /**
1418     * The next available value for <code>stamp[]</code>, an internal array.
1419     * This actually should not be written out to the stream, and will probably
1420     * be removed from the stream in the near future. In the meantime,
1421     * a value of <code>MINIMUM_USER_STAMP</code> should be used.
1422     * @serial
1423     */

1424    private transient int nextStamp = MINIMUM_USER_STAMP;
1425
1426    // the internal serial version which says which version was written
1427
// - 0 (default) for version up to JDK 1.1.5
1428
// - 1 for version from JDK 1.1.6, which writes a correct 'time' value
1429
// as well as compatible values for other fields. This is a
1430
// transitional format.
1431
// - 2 (not implemented yet) a future version, in which fields[],
1432
// areFieldsSet, and isTimeSet become transient, and isSet[] is
1433
// removed. In JDK 1.1.6 we write a format compatible with version 2.
1434
// static final int currentSerialVersion = 1;
1435

1436    /**
1437     * The version of the serialized data on the stream. Possible values:
1438     * <dl>
1439     * <dt><b>0</b> or not present on stream</dt>
1440     * <dd>
1441     * JDK 1.1.5 or earlier.
1442     * </dd>
1443     * <dt><b>1</b></dt>
1444     * <dd>
1445     * JDK 1.1.6 or later. Writes a correct 'time' value
1446     * as well as compatible values for other fields. This is a
1447     * transitional format.
1448     * </dd>
1449     * </dl>
1450     * When streaming out this class, the most recent format
1451     * and the highest allowable <code>serialVersionOnStream</code>
1452     * is written.
1453     * @serial
1454     * @since JDK1.1.6
1455     */

1456    // private int serialVersionOnStream = currentSerialVersion;
1457

1458    // Proclaim serialization compatibility with JDK 1.1
1459
// static final long serialVersionUID = -1807547505821590642L;
1460

1461    // haven't been compatible for awhile, no longer try
1462
// jdk1.4.2 serialver
1463
private static final long serialVersionUID = 6222646104888790989L;
1464
1465    /**
1466     * Bitmask for internalSet() defining which fields may legally be set
1467     * by subclasses. Any attempt to set a field not in this bitmask
1468     * results in an exception, because such fields must be set by the base
1469     * class.
1470     */

1471    private transient int internalSetMask;
1472
1473    /**
1474     * The Gregorian year, as computed by computeGregorianFields() and
1475     * returned by getGregorianYear().
1476     */

1477    private transient int gregorianYear;
1478
1479    /**
1480     * The Gregorian month, as computed by computeGregorianFields() and
1481     * returned by getGregorianMonth().
1482     */

1483    private transient int gregorianMonth;
1484
1485    /**
1486     * The Gregorian day of the year, as computed by
1487     * computeGregorianFields() and returned by getGregorianDayOfYear().
1488     */

1489    private transient int gregorianDayOfYear;
1490
1491    /**
1492     * The Gregorian day of the month, as computed by
1493     * computeGregorianFields() and returned by getGregorianDayOfMonth().
1494     */

1495    private transient int gregorianDayOfMonth;
1496
1497    /**
1498     * Constructs a Calendar with the default time zone
1499     * and locale.
1500     * @see TimeZone#getDefault
1501     * @stable ICU 2.0
1502     */

1503    protected Calendar()
1504    {
1505        this(TimeZone.getDefault(), ULocale.getDefault());
1506    }
1507
1508    /**
1509     * Constructs a calendar with the specified time zone and locale.
1510     * @param zone the time zone to use
1511     * @param aLocale the locale for the week data
1512     * @stable ICU 2.0
1513     */

1514    protected Calendar(TimeZone zone, Locale JavaDoc aLocale)
1515    {
1516        this(zone, ULocale.forLocale(aLocale));
1517    }
1518
1519    /**
1520     * Constructs a calendar with the specified time zone and locale.
1521     * @param zone the time zone to use
1522     * @param locale the ulocale for the week data
1523     * @draft ICU 3.2
1524     * @provisional This API might change or be removed in a future release.
1525     */

1526    protected Calendar(TimeZone zone, ULocale locale)
1527    {
1528        this.zone = zone;
1529        setWeekData(locale);
1530        initInternal();
1531    }
1532
1533    private void initInternal()
1534    {
1535        // Allocate fields through the framework method. Subclasses
1536
// may override this to define additional fields.
1537
fields = handleCreateFields();
1538        ///CLOVER:OFF
1539
// todo: fix, difficult to test without subclassing
1540
if (fields == null || fields.length < BASE_FIELD_COUNT ||
1541            fields.length > MAX_FIELD_COUNT) {
1542            throw new IllegalStateException JavaDoc("Invalid fields[]");
1543        }
1544        ///CLOVER:ON
1545
stamp = new int[fields.length];
1546        int mask = (1 << ERA) |
1547            (1 << YEAR) |
1548            (1 << MONTH) |
1549            (1 << DAY_OF_MONTH) |
1550            (1 << DAY_OF_YEAR) |
1551            (1 << EXTENDED_YEAR);
1552        for (int i=BASE_FIELD_COUNT; i<fields.length; ++i) {
1553            mask |= (1 << i);
1554        }
1555        internalSetMask = mask;
1556    }
1557
1558    /**
1559     * Gets a calendar using the default time zone and locale.
1560     * @return a Calendar.
1561     * @stable ICU 2.0
1562     */

1563    public static synchronized Calendar getInstance()
1564    {
1565        return getInstanceInternal(null, null);
1566    }
1567
1568    /**
1569     * Gets a calendar using the specified time zone and default locale.
1570     * @param zone the time zone to use
1571     * @return a Calendar.
1572     * @stable ICU 2.0
1573     */

1574    public static synchronized Calendar getInstance(TimeZone zone)
1575    {
1576        return getInstanceInternal(zone, null);
1577    }
1578
1579    /**
1580     * Gets a calendar using the default time zone and specified locale.
1581     * @param aLocale the locale for the week data
1582     * @return a Calendar.
1583     * @stable ICU 2.0
1584     */

1585    public static synchronized Calendar getInstance(Locale JavaDoc aLocale)
1586    {
1587        return getInstanceInternal(null, ULocale.forLocale(aLocale));
1588    }
1589
1590    /**
1591     * Gets a calendar using the default time zone and specified locale.
1592     * @param locale the ulocale for the week data
1593     * @return a Calendar.
1594     * @draft ICU 3.2
1595     * @provisional This API might change or be removed in a future release.
1596     */

1597    public static synchronized Calendar getInstance(ULocale locale)
1598    {
1599        return getInstanceInternal(null, locale);
1600    }
1601
1602    /**
1603     * Gets a calendar with the specified time zone and locale.
1604     * @param zone the time zone to use
1605     * @param aLocale the locale for the week data
1606     * @return a Calendar.
1607     * @stable ICU 2.0
1608     */

1609    public static synchronized Calendar getInstance(TimeZone zone,
1610                                                    Locale JavaDoc aLocale) {
1611        return getInstanceInternal(zone, ULocale.forLocale(aLocale));
1612    }
1613
1614    /**
1615     * Gets a calendar with the specified time zone and locale.
1616     * @param zone the time zone to use
1617     * @param locale the ulocale for the week data
1618     * @return a Calendar.
1619     * @draft ICU 3.2
1620     * @provisional This API might change or be removed in a future release.
1621     */

1622    public static synchronized Calendar getInstance(TimeZone zone,
1623                                                    ULocale locale) {
1624        return getInstanceInternal(zone, locale);
1625    }
1626
1627    /*
1628     * All getInstance implementations call this private method to create a new
1629     * Calendar instance.
1630     */

1631    private static Calendar getInstanceInternal(TimeZone tz, ULocale locale) {
1632        if (locale == null) {
1633            locale = ULocale.getDefault();
1634        }
1635        if (tz == null) {
1636            tz = TimeZone.getDefault();
1637        }
1638        Calendar cal = getShim().createInstance(locale);
1639        cal.setTimeZone(tz);
1640        cal.setTimeInMillis(System.currentTimeMillis());
1641        return cal;
1642    }
1643
1644    private static final int BUDDHIST = 0;
1645    private static final int CHINESE = 1;
1646    private static final int COPTIC = 2;
1647    private static final int ETHIOPIC = 3;
1648    private static final int GREGORIAN = 4;
1649    private static final int HEBREW = 5;
1650    private static final int ISLAMIC = 6;
1651    private static final int ISLAMIC_CIVIL = 7;
1652    private static final int JAPANESE = 8;
1653
1654    private static final String JavaDoc[] calTypes = {
1655        "buddhist", "chinese", "coptic", "ethiopic", "gregorian", "hebrew",
1656        "islamic", "islamic-civil", "japanese",
1657    };
1658
1659    private static int getCalendarType(ULocale l) {
1660        String JavaDoc s = l.getKeywordValue("calendar");
1661        if (s == null) {
1662            l = ICUResourceBundle.getFunctionalEquivalent(
1663                ICUResourceBundle.ICU_BASE_NAME, "calendar", "calendar", l, null);
1664            s = l.getKeywordValue("calendar");
1665        }
1666        return getCalendarType(s);
1667    }
1668
1669    private static int getCalendarType(String JavaDoc s) {
1670        if (s != null) {
1671            s = s.toLowerCase();
1672            for (int i = 0; i < calTypes.length; ++i) {
1673                if (s.equals(calTypes[i])) {
1674                    return i;
1675                }
1676            }
1677        }
1678        return GREGORIAN;
1679    }
1680
1681    /**
1682     * Gets the list of locales for which Calendars are installed.
1683     * @return the list of locales for which Calendars are installed.
1684     * @stable ICU 2.0
1685     */

1686    public static Locale JavaDoc[] getAvailableLocales()
1687    {
1688        if (shim == null) {
1689            return ICUResourceBundle.getAvailableLocales(ICUResourceBundle.ICU_BASE_NAME);
1690        }
1691        return getShim().getAvailableLocales();
1692    }
1693
1694    /**
1695     * Gets the list of locales for which Calendars are installed.
1696     * @return the list of locales for which Calendars are installed.
1697     * @draft ICU 3.2
1698     * @provisional This API might change or be removed in a future release.
1699     */

1700    public static ULocale[] getAvailableULocales()
1701    {
1702        if (shim == null) {
1703            return ICUResourceBundle.getAvailableULocales(ICUResourceBundle.ICU_BASE_NAME);
1704        }
1705        return getShim().getAvailableULocales();
1706    }
1707
1708    // ==== Factory Stuff ====
1709
/**
1710     * A CalendarFactory is used to register new calendar implementation.
1711     * The factory should be able to create a calendar instance for the
1712     * specified locale.
1713     *
1714     * @prototype
1715     */

1716    /* public */ static abstract class CalendarFactory {
1717        public boolean visible() {
1718            return true;
1719        }
1720
1721        public abstract Set JavaDoc getSupportedLocaleNames();
1722
1723        public Calendar createCalendar(ULocale loc) {
1724            return null;
1725        }
1726
1727        protected CalendarFactory() {
1728        }
1729    }
1730
1731    // shim so we can build without service code
1732
static abstract class CalendarShim {
1733        abstract Locale JavaDoc[] getAvailableLocales();
1734        abstract ULocale[] getAvailableULocales();
1735        abstract Object JavaDoc registerFactory(CalendarFactory factory);
1736        abstract boolean unregister(Object JavaDoc k);
1737        abstract Calendar createInstance(ULocale l);
1738    }
1739
1740    private static CalendarShim shim;
1741    private static CalendarShim getShim() {
1742        if (shim == null) {
1743            try {
1744                Class JavaDoc cls = Class.forName("com.ibm.icu.util.CalendarServiceShim");
1745                shim = (CalendarShim)cls.newInstance();
1746            }
1747            catch (MissingResourceException JavaDoc e) {
1748                throw e;
1749            }
1750            catch (Exception JavaDoc e) {
1751                throw new RuntimeException JavaDoc(e.getMessage());
1752            }
1753        }
1754        return shim;
1755    }
1756
1757    static Calendar createInstance(ULocale locale) {
1758        int calType = getCalendarType(locale);
1759        TimeZone zone = TimeZone.getDefault();
1760
1761        switch (calType) {
1762        case BUDDHIST:
1763            return new BuddhistCalendar(zone, locale);
1764        case CHINESE:
1765            return new ChineseCalendar(zone, locale);
1766        case COPTIC:
1767            return new CopticCalendar(zone, locale);
1768        case ETHIOPIC:
1769            return new EthiopicCalendar(zone, locale);
1770        case GREGORIAN:
1771            return new GregorianCalendar(zone, locale);
1772        case HEBREW:
1773            return new HebrewCalendar(zone, locale);
1774        case ISLAMIC:
1775        case ISLAMIC_CIVIL: {
1776            IslamicCalendar result = new IslamicCalendar(zone, locale);
1777            result.setCivil(calType == ISLAMIC_CIVIL);
1778            return result;
1779        }
1780        case JAPANESE:
1781            return new JapaneseCalendar(zone, locale);
1782        default:
1783            throw new IllegalStateException JavaDoc();
1784        }
1785    }
1786
1787    ///CLOVER:OFF
1788
/**
1789     * Register a new CalendarFactory. getInstance(TimeZone, ULocale, String) will
1790     * try to locate a registered factories matching the factoryName. Only registered
1791     * factories will be found.
1792     * @prototype
1793     */

1794    /* public */ static Object JavaDoc registerFactory(CalendarFactory factory) {
1795        if (factory == null) {
1796            throw new IllegalArgumentException JavaDoc("factory must not be null");
1797        }
1798        return getShim().registerFactory(factory);
1799    }
1800
1801    /**
1802     * Unregister the CalendarFactory associated with this key
1803     * (obtained from register).
1804     * @prototype
1805     */

1806    /* public */ static boolean unregister(Object JavaDoc registryKey) {
1807        if (registryKey == null) {
1808            throw new IllegalArgumentException JavaDoc("registryKey must not be null");
1809        }
1810
1811        if (shim == null) {
1812            return false;
1813        }
1814
1815        return shim.unregister(registryKey);
1816    }
1817
1818    ///CLOVER:ON
1819
// ==== End of factory Stuff ====
1820

1821    /**
1822     * Gets this Calendar's current time.
1823     * @return the current time.
1824     * @stable ICU 2.0
1825     */

1826    public final Date JavaDoc getTime() {
1827        return new Date JavaDoc( getTimeInMillis() );
1828    }
1829
1830    /**
1831     * Sets this Calendar's current time with the given Date.
1832     * <p>
1833     * Note: Calling <code>setTime()</code> with
1834     * <code>Date(Long.MAX_VALUE)</code> or <code>Date(Long.MIN_VALUE)</code>
1835     * may yield incorrect field values from <code>get()</code>.
1836     * @param date the given Date.
1837     * @stable ICU 2.0
1838     */

1839    public final void setTime(Date JavaDoc date) {
1840        setTimeInMillis( date.getTime() );
1841    }
1842
1843    /**
1844     * Gets this Calendar's current time as a long.
1845     * @return the current time as UTC milliseconds from the epoch.
1846     * @stable ICU 2.0
1847     */

1848    public long getTimeInMillis() {
1849        if (!isTimeSet) updateTime();
1850        return time;
1851    }
1852
1853    /**
1854     * Sets this Calendar's current time from the given long value.
1855     * @param millis the new time in UTC milliseconds from the epoch.
1856     * @stable ICU 2.0
1857     */

1858    public void setTimeInMillis( long millis ) {
1859        if (millis > MAX_MILLIS) {
1860            millis = MAX_MILLIS;
1861        } else if (millis < MIN_MILLIS) {
1862            millis = MIN_MILLIS;
1863        }
1864        time = millis;
1865        areFieldsSet = areAllFieldsSet = false;
1866        isTimeSet = areFieldsVirtuallySet = true;
1867    }
1868
1869    /**
1870     * Gets the value for a given time field.
1871     * @param field the given time field.
1872     * @return the value for the given time field.
1873     * @stable ICU 2.0
1874     */

1875    public final int get(int field)
1876    {
1877        complete();
1878        return fields[field];
1879    }
1880
1881    /**
1882     * Gets the value for a given time field. This is an internal method
1883     * for subclasses that does <em>not</em> trigger any calculations.
1884     * @param field the given time field.
1885     * @return the value for the given time field.
1886     * @stable ICU 2.0
1887     */

1888    protected final int internalGet(int field)
1889    {
1890        return fields[field];
1891    }
1892
1893    /**
1894     * Get the value for a given time field, or return the given default
1895     * value if the field is not set. This is an internal method for
1896     * subclasses that does <em>not</em> trigger any calculations.
1897     * @param field the given time field.
1898     * @param defaultValue value to return if field is not set
1899     * @return the value for the given time field of defaultValue if the
1900     * field is unset
1901     * @stable ICU 2.0
1902     */

1903    protected final int internalGet(int field, int defaultValue) {
1904        return (stamp[field] > UNSET) ? fields[field] : defaultValue;
1905    }
1906
1907    /**
1908     * Sets the time field with the given value.
1909     * @param field the given time field.
1910     * @param value the value to be set for the given time field.
1911     * @stable ICU 2.0
1912     */

1913    public final void set(int field, int value)
1914    {
1915        if (areFieldsVirtuallySet) {
1916            computeFields();
1917        }
1918        fields[field] = value;
1919        stamp[field] = nextStamp++;
1920        isTimeSet = areFieldsSet = areFieldsVirtuallySet = false;
1921    }
1922
1923    /**
1924     * Sets the values for the fields year, month, and date.
1925     * Previous values of other fields are retained. If this is not desired,
1926     * call <code>clear</code> first.
1927     * @param year the value used to set the YEAR time field.
1928     * @param month the value used to set the MONTH time field.
1929     * Month value is 0-based. e.g., 0 for January.
1930     * @param date the value used to set the DATE time field.
1931     * @stable ICU 2.0
1932     */

1933    public final void set(int year, int month, int date)
1934    {
1935        set(YEAR, year);
1936        set(MONTH, month);
1937        set(DATE, date);
1938    }
1939
1940    /**
1941     * Sets the values for the fields year, month, date, hour, and minute.
1942     * Previous values of other fields are retained. If this is not desired,
1943     * call <code>clear</code> first.
1944     * @param year the value used to set the YEAR time field.
1945     * @param month the value used to set the MONTH time field.
1946     * Month value is 0-based. e.g., 0 for January.
1947     * @param date the value used to set the DATE time field.
1948     * @param hour the value used to set the HOUR_OF_DAY time field.
1949     * @param minute the value used to set the MINUTE time field.
1950     * @stable ICU 2.0
1951     */

1952    public final void set(int year, int month, int date, int hour, int minute)
1953    {
1954        set(YEAR, year);
1955        set(MONTH, month);
1956        set(DATE, date);
1957        set(HOUR_OF_DAY, hour);
1958        set(MINUTE, minute);
1959    }
1960
1961    /**
1962     * Sets the values for the fields year, month, date, hour, minute, and second.
1963     * Previous values of other fields are retained. If this is not desired,
1964     * call <code>clear</code> first.
1965     * @param year the value used to set the YEAR time field.
1966     * @param month the value used to set the MONTH time field.
1967     * Month value is 0-based. e.g., 0 for January.
1968     * @param date the value used to set the DATE time field.
1969     * @param hour the value used to set the HOUR_OF_DAY time field.
1970     * @param minute the value used to set the MINUTE time field.
1971     * @param second the value used to set the SECOND time field.
1972     * @stable ICU 2.0
1973     */

1974    public final void set(int year, int month, int date, int hour, int minute,
1975                          int second)
1976    {
1977        set(YEAR, year);
1978        set(MONTH, month);
1979        set(DATE, date);
1980        set(HOUR_OF_DAY, hour);
1981        set(MINUTE, minute);
1982        set(SECOND, second);
1983    }
1984
1985    /**
1986     * Clears the values of all the time fields.
1987     * @stable ICU 2.0
1988     */

1989    public final void clear()
1990    {
1991        for (int i=0; i<fields.length; ++i) {
1992            fields[i] = stamp[i] = 0; // UNSET == 0
1993
}
1994        isTimeSet = areFieldsSet = areAllFieldsSet = areFieldsVirtuallySet = false;
1995    }
1996
1997    /**
1998     * Clears the value in the given time field.
1999     * @param field the time field to be cleared.
2000     * @stable ICU 2.0
2001     */

2002    public final void clear(int field)
2003    {
2004        if (areFieldsVirtuallySet) {
2005            computeFields();
2006        }
2007        fields[field] = 0;
2008        stamp[field] = UNSET;
2009        isTimeSet = areFieldsSet = areAllFieldsSet = areFieldsVirtuallySet = false;
2010    }
2011
2012    /**
2013     * Determines if the given time field has a value set.
2014     * @return true if the given time field has a value set; false otherwise.
2015     * @stable ICU 2.0
2016     */

2017    public final boolean isSet(int field)
2018    {
2019        return areFieldsVirtuallySet || (stamp[field] != UNSET);
2020    }
2021
2022    /**
2023     * Fills in any unset fields in the time field list.
2024     * @stable ICU 2.0
2025     */

2026    protected void complete()
2027    {
2028        if (!isTimeSet) updateTime();
2029        if (!areFieldsSet) {
2030            computeFields(); // fills in unset fields
2031
areFieldsSet = true;
2032            areAllFieldsSet = true;
2033        }
2034    }
2035
2036    /**
2037     * Compares this calendar to the specified object.
2038     * The result is <code>true</code> if and only if the argument is
2039     * not <code>null</code> and is a <code>Calendar</code> object that
2040     * represents the same calendar as this object.
2041     * @param obj the object to compare with.
2042     * @return <code>true</code> if the objects are the same;
2043     * <code>false</code> otherwise.
2044     * @stable ICU 2.0
2045     */

2046    public boolean equals(Object JavaDoc obj) {
2047        if (this == obj) {
2048            return true;
2049        }
2050        if (this.getClass() != obj.getClass()) {
2051            return false;
2052        }
2053
2054        Calendar that = (Calendar) obj;
2055
2056        return isEquivalentTo(that) &&
2057            getTimeInMillis() == that.getTime().getTime();
2058    }
2059
2060    /**
2061     * Returns true if the given Calendar object is equivalent to this
2062     * one. An equivalent Calendar will behave exactly as this one
2063     * does, but it may be set to a different time. By contrast, for
2064     * the equals() method to return true, the other Calendar must
2065     * be set to the same time.
2066     *
2067     * @param other the Calendar to be compared with this Calendar
2068     * @stable ICU 2.4
2069     */

2070    public boolean isEquivalentTo(Calendar other) {
2071        return this.getClass() == other.getClass() &&
2072            isLenient() == other.isLenient() &&
2073            getFirstDayOfWeek() == other.getFirstDayOfWeek() &&
2074            getMinimalDaysInFirstWeek() == other.getMinimalDaysInFirstWeek() &&
2075            getTimeZone().equals(other.getTimeZone());
2076    }
2077
2078    /**
2079     * Returns a hash code for this calendar.
2080     * @return a hash code value for this object.
2081     * @stable ICU 2.0
2082     */

2083    public int hashCode() {
2084        /* Don't include the time because (a) we don't want the hash value to
2085         * move around just because a calendar is set to different times, and
2086         * (b) we don't want to trigger a time computation just to get a hash.
2087         * Note that it is not necessary for unequal objects to always have
2088         * unequal hashes, but equal objects must have equal hashes. */

2089        return (lenient ? 1 : 0)
2090            | (firstDayOfWeek << 1)
2091            | (minimalDaysInFirstWeek << 4)
2092            | (zone.hashCode() << 7);
2093    }
2094
2095    /**
2096     * Return the difference in milliseconds between the moment this
2097     * calendar is set to and the moment the given calendar or Date object
2098     * is set to.
2099     */

2100    private long compare(Object JavaDoc that) {
2101        long thatMs;
2102        if (that instanceof Calendar) {
2103            thatMs = ((Calendar)that).getTimeInMillis();
2104        } else if (that instanceof Date JavaDoc) {
2105            thatMs = ((Date JavaDoc)that).getTime();
2106        } else {
2107            throw new IllegalArgumentException JavaDoc(that + "is not a Calendar or Date");
2108        }
2109        return getTimeInMillis() - thatMs;
2110    }
2111
2112    /**
2113     * Compares the time field records.
2114     * Equivalent to comparing result of conversion to UTC.
2115     * @param when the Calendar to be compared with this Calendar.
2116     * @return true if the current time of this Calendar is before
2117     * the time of Calendar when; false otherwise.
2118     * @stable ICU 2.0
2119     */

2120    public boolean before(Object JavaDoc when) {
2121        return compare(when) < 0;
2122    }
2123
2124    /**
2125     * Compares the time field records.
2126     * Equivalent to comparing result of conversion to UTC.
2127     * @param when the Calendar to be compared with this Calendar.
2128     * @return true if the current time of this Calendar is after
2129     * the time of Calendar when; false otherwise.
2130     * @stable ICU 2.0
2131     */

2132    public boolean after(Object JavaDoc when) {
2133        return compare(when) > 0;
2134    }
2135
2136    /**
2137     * Return the maximum value that this field could have, given the
2138     * current date. For example, with the Gregorian date February 3, 1997
2139     * and the {@link #DAY_OF_MONTH DAY_OF_MONTH} field, the actual maximum
2140     * is 28; for February 3, 1996 it is 29.
2141     *
2142     * <p>The actual maximum computation ignores smaller fields and the
2143     * current value of like-sized fields. For example, the actual maximum
2144     * of the DAY_OF_YEAR or MONTH depends only on the year and supra-year
2145     * fields. The actual maximum of the DAY_OF_MONTH depends, in
2146     * addition, on the MONTH field and any other fields at that
2147     * granularity (such as ChineseCalendar.IS_LEAP_MONTH). The
2148     * DAY_OF_WEEK_IN_MONTH field does not depend on the current
2149     * DAY_OF_WEEK; it returns the maximum for any day of week in the
2150     * current month. Likewise for the WEEK_OF_MONTH and WEEK_OF_YEAR
2151     * fields.
2152     *
2153     * @param field the field whose maximum is desired
2154     * @return the maximum of the given field for the current date of this calendar
2155     * @see #getMaximum
2156     * @see #getLeastMaximum
2157     * @stable ICU 2.0
2158     */

2159    public int getActualMaximum(int field) {
2160        int result;
2161
2162        switch (field) {
2163        case DAY_OF_MONTH:
2164            {
2165                Calendar cal = (Calendar) clone();
2166                cal.prepareGetActual(field, false);
2167                result = handleGetMonthLength(cal.get(EXTENDED_YEAR), cal.get(MONTH));
2168            }
2169            break;
2170
2171        case DAY_OF_YEAR:
2172            {
2173                Calendar cal = (Calendar) clone();
2174                cal.prepareGetActual(field, false);
2175                result = handleGetYearLength(cal.get(EXTENDED_YEAR));
2176            }
2177            break;
2178
2179        case DAY_OF_WEEK:
2180        case AM_PM:
2181        case HOUR:
2182        case HOUR_OF_DAY:
2183        case MINUTE:
2184        case SECOND:
2185        case MILLISECOND:
2186        case ZONE_OFFSET:
2187        case DST_OFFSET:
2188        case DOW_LOCAL:
2189        case JULIAN_DAY:
2190        case MILLISECONDS_IN_DAY:
2191            // These fields all have fixed minima/maxima
2192
result = getMaximum(field);
2193            break;
2194
2195        default:
2196            // For all other fields, do it the hard way....
2197
result = getActualHelper(field, getLeastMaximum(field), getMaximum(field));
2198            break;
2199        }
2200        return result;
2201    }
2202
2203    /**
2204     * Return the minimum value that this field could have, given the current date.
2205     * For most fields, this is the same as {@link #getMinimum getMinimum}
2206     * and {@link #getGreatestMinimum getGreatestMinimum}. However, some fields,
2207     * especially those related to week number, are more complicated.
2208     * <p>
2209     * For example, assume {@link #getMinimalDaysInFirstWeek getMinimalDaysInFirstWeek}
2210     * returns 4 and {@link #getFirstDayOfWeek getFirstDayOfWeek} returns SUNDAY.
2211     * If the first day of the month is Sunday, Monday, Tuesday, or Wednesday
2212     * there will be four or more days in the first week, so it will be week number 1,
2213     * and <code>getActualMinimum(WEEK_OF_MONTH)</code> will return 1. However,
2214     * if the first of the month is a Thursday, Friday, or Saturday, there are
2215     * <em>not</em> four days in that week, so it is week number 0, and
2216     * <code>getActualMinimum(WEEK_OF_MONTH)</code> will return 0.
2217     * <p>
2218     * @param field the field whose actual minimum value is desired.
2219     * @return the minimum of the given field for the current date of this calendar
2220     *
2221     * @see #getMinimum
2222     * @see #getGreatestMinimum
2223     * @stable ICU 2.0
2224     */

2225    public int getActualMinimum(int field) {
2226        int result;
2227
2228        switch (field) {
2229        case DAY_OF_WEEK:
2230        case AM_PM:
2231        case HOUR:
2232        case HOUR_OF_DAY:
2233        case MINUTE:
2234        case SECOND:
2235        case MILLISECOND:
2236        case ZONE_OFFSET:
2237        case DST_OFFSET:
2238        case DOW_LOCAL:
2239        case JULIAN_DAY:
2240        case MILLISECONDS_IN_DAY:
2241            // These fields all have fixed minima/maxima
2242
result = getMinimum(field);
2243            break;
2244
2245        default:
2246            // For all other fields, do it the hard way....
2247
result = getActualHelper(field, getGreatestMinimum(field), getMinimum(field));
2248            break;
2249        }
2250        return result;
2251    }
2252
2253    /**
2254     * Prepare this calendar for computing the actual minimum or maximum.
2255     * This method modifies this calendar's fields; it is called on a
2256     * temporary calendar.
2257     *
2258     * <p>Rationale: The semantics of getActualXxx() is to return the
2259     * maximum or minimum value that the given field can take, taking into
2260     * account other relevant fields. In general these other fields are
2261     * larger fields. For example, when computing the actual maximum
2262     * DAY_OF_MONTH, the current value of DAY_OF_MONTH itself is ignored,
2263     * as is the value of any field smaller.
2264     *
2265     * <p>The time fields all have fixed minima and maxima, so we don't
2266     * need to worry about them. This also lets us set the
2267     * MILLISECONDS_IN_DAY to zero to erase any effects the time fields
2268     * might have when computing date fields.
2269     *
2270     * <p>DAY_OF_WEEK is adjusted specially for the WEEK_OF_MONTH and
2271     * WEEK_OF_YEAR fields to ensure that they are computed correctly.
2272     * @stable ICU 2.0
2273     */

2274    protected void prepareGetActual(int field, boolean isMinimum) {
2275        set(MILLISECONDS_IN_DAY, 0);
2276
2277        switch (field) {
2278        case YEAR:
2279        case YEAR_WOY:
2280        case EXTENDED_YEAR:
2281            set(DAY_OF_YEAR, getGreatestMinimum(DAY_OF_YEAR));
2282            break;
2283
2284        case MONTH:
2285            set(DAY_OF_MONTH, getGreatestMinimum(DAY_OF_MONTH));
2286            break;
2287
2288        case DAY_OF_WEEK_IN_MONTH:
2289            // For dowim, the maximum occurs for the DOW of the first of the
2290
// month.
2291
set(DAY_OF_MONTH, 1);
2292            set(DAY_OF_WEEK, get(DAY_OF_WEEK)); // Make this user set
2293
break;
2294
2295        case WEEK_OF_MONTH:
2296        case WEEK_OF_YEAR:
2297            // If we're counting weeks, set the day of the week to either the
2298
// first or last localized DOW. We know the last week of a month
2299
// or year will contain the first day of the week, and that the
2300
// first week will contain the last DOW.
2301
{
2302                int dow = firstDayOfWeek;
2303                if (isMinimum) {
2304                    dow = (dow + 6) % 7; // set to last DOW
2305
if (dow < SUNDAY) {
2306                        dow += 7;
2307                    }
2308                }
2309                set(DAY_OF_WEEK, dow);
2310            }
2311            break;
2312        }
2313
2314        // Do this last to give it the newest time stamp
2315
set(field, getGreatestMinimum(field));
2316    }
2317
2318    private int getActualHelper(int field, int startValue, int endValue) {
2319
2320        if (startValue == endValue) {
2321            // if we know that the maximum value is always the same, just return it
2322
return startValue;
2323        }
2324
2325        final int delta = (endValue > startValue) ? 1 : -1;
2326
2327        // clone the calendar so we don't mess with the real one, and set it to
2328
// accept anything for the field values
2329
Calendar work = (Calendar) clone();
2330        work.setLenient(true);
2331        work.prepareGetActual(field, delta < 0);
2332
2333        // now try each value from the start to the end one by one until
2334
// we get a value that normalizes to another value. The last value that
2335
// normalizes to itself is the actual maximum for the current date
2336
int result = startValue;
2337        do {
2338            work.set(field, startValue);
2339            if (work.get(field) != startValue) {
2340                break;
2341            } else {
2342                result = startValue;
2343                startValue += delta;
2344            }
2345        } while (result != endValue);
2346
2347        return result;
2348    }
2349
2350    /**
2351     * Rolls (up/down) a single unit of time on the given field. If the
2352     * field is rolled past its maximum allowable value, it will "wrap" back
2353     * to its minimum and continue rolling. For
2354     * example, to roll the current date up by one day, you can call:
2355     * <p>
2356     * <code>roll({@link #DATE}, true)</code>
2357     * <p>
2358     * When rolling on the {@link #YEAR} field, it will roll the year
2359     * value in the range between 1 and the value returned by calling
2360     * {@link #getMaximum getMaximum}({@link #YEAR}).
2361     * <p>
2362     * When rolling on certain fields, the values of other fields may conflict and
2363     * need to be changed. For example, when rolling the <code>MONTH</code> field
2364     * for the Gregorian date 1/31/96 upward, the <code>DAY_OF_MONTH</code> field
2365     * must be adjusted so that the result is 2/29/96 rather than the invalid
2366     * 2/31/96.
2367     * <p>
2368     * <b>Note:</b> Calling <tt>roll(field, true)</tt> N times is <em>not</em>
2369     * necessarily equivalent to calling <tt>roll(field, N)</tt>. For example,
2370     * imagine that you start with the date Gregorian date January 31, 1995. If you call
2371     * <tt>roll(Calendar.MONTH, 2)</tt>, the result will be March 31, 1995.
2372     * But if you call <tt>roll(Calendar.MONTH, true)</tt>, the result will be
2373     * February 28, 1995. Calling it one more time will give March 28, 1995, which
2374     * is usually not the desired result.
2375     * <p>
2376     * <b>Note:</b> You should always use <tt>roll</tt> and <tt>add</tt> rather
2377     * than attempting to perform arithmetic operations directly on the fields
2378     * of a <tt>Calendar</tt>. It is quite possible for <tt>Calendar</tt> subclasses
2379     * to have fields with non-linear behavior, for example missing months
2380     * or days during non-leap years. The subclasses' <tt>add</tt> and <tt>roll</tt>
2381     * methods will take this into account, while simple arithmetic manipulations
2382     * may give invalid results.
2383     * <p>
2384     * @param field the calendar field to roll.
2385     *
2386     * @param up indicates if the value of the specified time field is to be
2387     * rolled up or rolled down. Use <code>true</code> if rolling up,
2388     * <code>false</code> otherwise.
2389     *
2390     * @exception IllegalArgumentException if the field is invalid or refers
2391     * to a field that cannot be handled by this method.
2392     * @see #roll(int, int)
2393     * @see #add
2394     * @stable ICU 2.0
2395     */

2396    public final void roll(int field, boolean up)
2397    {
2398        roll(field, up ? +1 : -1);
2399    }
2400
2401    /**
2402     * Rolls (up/down) a specified amount time on the given field. For
2403     * example, to roll the current date up by three days, you can call
2404     * <code>roll(Calendar.DATE, 3)</code>. If the
2405     * field is rolled past its maximum allowable value, it will "wrap" back
2406     * to its minimum and continue rolling.
2407     * For example, calling <code>roll(Calendar.DATE, 10)</code>
2408     * on a Gregorian calendar set to 4/25/96 will result in the date 4/5/96.
2409     * <p>
2410     * When rolling on certain fields, the values of other fields may conflict and
2411     * need to be changed. For example, when rolling the {@link #MONTH MONTH} field
2412     * for the Gregorian date 1/31/96 by +1, the {@link #DAY_OF_MONTH DAY_OF_MONTH} field
2413     * must be adjusted so that the result is 2/29/96 rather than the invalid
2414     * 2/31/96.
2415     * <p>
2416     * The <code>com.ibm.icu.util.Calendar</code> implementation of this method is able to roll
2417     * all fields except for {@link #ERA ERA}, {@link #DST_OFFSET DST_OFFSET},
2418     * and {@link #ZONE_OFFSET ZONE_OFFSET}. Subclasses may, of course, add support for
2419     * additional fields in their overrides of <code>roll</code>.
2420     * <p>
2421     * <b>Note:</b> You should always use <tt>roll</tt> and <tt>add</tt> rather
2422     * than attempting to perform arithmetic operations directly on the fields
2423     * of a <tt>Calendar</tt>. It is quite possible for <tt>Calendar</tt> subclasses
2424     * to have fields with non-linear behavior, for example missing months
2425     * or days during non-leap years. The subclasses' <tt>add</tt> and <tt>roll</tt>
2426     * methods will take this into account, while simple arithmetic manipulations
2427     * may give invalid results.
2428     * <p>
2429     * <b>Subclassing:</b><br>
2430     * This implementation of <code>roll</code> assumes that the behavior of the
2431     * field is continuous between its minimum and maximum, which are found by
2432     * calling {@link #getActualMinimum getActualMinimum} and {@link #getActualMaximum getActualMaximum}.
2433     * For most such fields, simple addition, subtraction, and modulus operations
2434     * are sufficient to perform the roll. For week-related fields,
2435     * the results of {@link #getFirstDayOfWeek getFirstDayOfWeek} and
2436     * {@link #getMinimalDaysInFirstWeek getMinimalDaysInFirstWeek} are also necessary.
2437     * Subclasses can override these two methods if their values differ from the defaults.
2438     * <p>
2439     * Subclasses that have fields for which the assumption of continuity breaks
2440     * down must overide <code>roll</code> to handle those fields specially.
2441     * For example, in the Hebrew calendar the month "Adar I"
2442     * only occurs in leap years; in other years the calendar jumps from
2443     * Shevat (month #4) to Adar (month #6). The
2444     * {@link HebrewCalendar#roll HebrewCalendar.roll} method takes this into account,
2445     * so that rolling the month of Shevat by one gives the proper result (Adar) in a
2446     * non-leap year.
2447     * <p>
2448     * @param field the calendar field to roll.
2449     * @param amount the amount by which the field should be rolled.
2450     *
2451     * @exception IllegalArgumentException if the field is invalid or refers
2452     * to a field that cannot be handled by this method.
2453     * @see #roll(int, boolean)
2454     * @see #add
2455     * @stable ICU 2.0
2456     */

2457    public void roll(int field, int amount) {
2458
2459        if (amount == 0) {
2460            return; // Nothing to do
2461
}
2462
2463        complete();
2464
2465        switch (field) {
2466        case DAY_OF_MONTH:
2467        case AM_PM:
2468        case MINUTE:
2469        case SECOND:
2470        case MILLISECOND:
2471        case MILLISECONDS_IN_DAY:
2472        case ERA:
2473            // These are the standard roll instructions. These work for all
2474
// simple cases, that is, cases in which the limits are fixed, such
2475
// as the hour, the day of the month, and the era.
2476
{
2477                int min = getActualMinimum(field);
2478                int max = getActualMaximum(field);
2479                int gap = max - min + 1;
2480
2481                int value = internalGet(field) + amount;
2482                value = (value - min) % gap;
2483                if (value < 0) {
2484                    value += gap;
2485                }
2486                value += min;
2487
2488                set(field, value);
2489                return;
2490            }
2491
2492        case HOUR:
2493        case HOUR_OF_DAY:
2494            // Rolling the hour is difficult on the ONSET and CEASE days of
2495
// daylight savings. For example, if the change occurs at
2496
// 2 AM, we have the following progression:
2497
// ONSET: 12 Std -> 1 Std -> 3 Dst -> 4 Dst
2498
// CEASE: 12 Dst -> 1 Dst -> 1 Std -> 2 Std
2499
// To get around this problem we don't use fields; we manipulate
2500
// the time in millis directly.
2501
{
2502                // Assume min == 0 in calculations below
2503
long start = getTimeInMillis();
2504                int oldHour = internalGet(field);
2505                int max = getMaximum(field);
2506                int newHour = (oldHour + amount) % (max + 1);
2507                if (newHour < 0) {
2508                    newHour += max + 1;
2509                }
2510                setTimeInMillis(start + ONE_HOUR * (newHour - oldHour));
2511                return;
2512            }
2513
2514        case MONTH:
2515            // Rolling the month involves both pinning the final value
2516
// and adjusting the DAY_OF_MONTH if necessary. We only adjust the
2517
// DAY_OF_MONTH if, after updating the MONTH field, it is illegal.
2518
// E.g., <jan31>.roll(MONTH, 1) -> <feb28> or <feb29>.
2519
{
2520                int max = getActualMaximum(MONTH);
2521                int mon = (internalGet(MONTH) + amount) % (max+1);
2522
2523                if (mon < 0) {
2524                    mon += (max + 1);
2525                }
2526                set(MONTH, mon);
2527
2528                // Keep the day of month in range. We don't want to spill over
2529
// into the next month; e.g., we don't want jan31 + 1 mo -> feb31 ->
2530
// mar3.
2531
pinField(DAY_OF_MONTH);
2532                return;
2533            }
2534
2535        case YEAR:
2536        case YEAR_WOY:
2537        case EXTENDED_YEAR:
2538            // Rolling the year can involve pinning the DAY_OF_MONTH.
2539
set(field, internalGet(field) + amount);
2540            pinField(MONTH);
2541            pinField(DAY_OF_MONTH);
2542            return;
2543
2544        case WEEK_OF_MONTH:
2545            {
2546                // This is tricky, because during the roll we may have to shift
2547
// to a different day of the week. For example:
2548

2549                // s m t w r f s
2550
// 1 2 3 4 5
2551
// 6 7 8 9 10 11 12
2552

2553                // When rolling from the 6th or 7th back one week, we go to the
2554
// 1st (assuming that the first partial week counts). The same
2555
// thing happens at the end of the month.
2556

2557                // The other tricky thing is that we have to figure out whether
2558
// the first partial week actually counts or not, based on the
2559
// minimal first days in the week. And we have to use the
2560
// correct first day of the week to delineate the week
2561
// boundaries.
2562

2563                // Here's our algorithm. First, we find the real boundaries of
2564
// the month. Then we discard the first partial week if it
2565
// doesn't count in this locale. Then we fill in the ends with
2566
// phantom days, so that the first partial week and the last
2567
// partial week are full weeks. We then have a nice square
2568
// block of weeks. We do the usual rolling within this block,
2569
// as is done elsewhere in this method. If we wind up on one of
2570
// the phantom days that we added, we recognize this and pin to
2571
// the first or the last day of the month. Easy, eh?
2572

2573                // Normalize the DAY_OF_WEEK so that 0 is the first day of the week
2574
// in this locale. We have dow in 0..6.
2575
int dow = internalGet(DAY_OF_WEEK) - getFirstDayOfWeek();
2576                if (dow < 0) dow += 7;
2577
2578                // Find the day of the week (normalized for locale) for the first
2579
// of the month.
2580
int fdm = (dow - internalGet(DAY_OF_MONTH) + 1) % 7;
2581                if (fdm < 0) fdm += 7;
2582
2583                // Get the first day of the first full week of the month,
2584
// including phantom days, if any. Figure out if the first week
2585
// counts or not; if it counts, then fill in phantom days. If
2586
// not, advance to the first real full week (skip the partial week).
2587
int start;
2588                if ((7 - fdm) < getMinimalDaysInFirstWeek())
2589                    start = 8 - fdm; // Skip the first partial week
2590
else
2591                    start = 1 - fdm; // This may be zero or negative
2592

2593                // Get the day of the week (normalized for locale) for the last
2594
// day of the month.
2595
int monthLen = getActualMaximum(DAY_OF_MONTH);
2596                int ldm = (monthLen - internalGet(DAY_OF_MONTH) + dow) % 7;
2597                // We know monthLen >= DAY_OF_MONTH so we skip the += 7 step here.
2598

2599                // Get the limit day for the blocked-off rectangular month; that
2600
// is, the day which is one past the last day of the month,
2601
// after the month has already been filled in with phantom days
2602
// to fill out the last week. This day has a normalized DOW of 0.
2603
int limit = monthLen + 7 - ldm;
2604
2605                // Now roll between start and (limit - 1).
2606
int gap = limit - start;
2607                int day_of_month = (internalGet(DAY_OF_MONTH) + amount*7 -
2608                                    start) % gap;
2609                if (day_of_month < 0) day_of_month += gap;
2610                day_of_month += start;
2611
2612                // Finally, pin to the real start and end of the month.
2613
if (day_of_month < 1) day_of_month = 1;
2614                if (day_of_month > monthLen) day_of_month = monthLen;
2615
2616                // Set the DAY_OF_MONTH. We rely on the fact that this field
2617
// takes precedence over everything else (since all other fields
2618
// are also set at this point). If this fact changes (if the
2619
// disambiguation algorithm changes) then we will have to unset
2620
// the appropriate fields here so that DAY_OF_MONTH is attended
2621
// to.
2622
set(DAY_OF_MONTH, day_of_month);
2623                return;
2624            }
2625        case WEEK_OF_YEAR:
2626            {
2627                // This follows the outline of WEEK_OF_MONTH, except it applies
2628
// to the whole year. Please see the comment for WEEK_OF_MONTH
2629
// for general notes.
2630

2631                // Normalize the DAY_OF_WEEK so that 0 is the first day of the week
2632
// in this locale. We have dow in 0..6.
2633
int dow = internalGet(DAY_OF_WEEK) - getFirstDayOfWeek();
2634                if (dow < 0) dow += 7;
2635
2636                // Find the day of the week (normalized for locale) for the first
2637
// of the year.
2638
int fdy = (dow - internalGet(DAY_OF_YEAR) + 1) % 7;
2639                if (fdy < 0) fdy += 7;
2640
2641                // Get the first day of the first full week of the year,
2642
// including phantom days, if any. Figure out if the first week
2643
// counts or not; if it counts, then fill in phantom days. If
2644
// not, advance to the first real full week (skip the partial week).
2645
int start;
2646                if ((7 - fdy) < getMinimalDaysInFirstWeek())
2647                    start = 8 - fdy; // Skip the first partial week
2648
else
2649                    start = 1 - fdy; // This may be zero or negative
2650

2651                // Get the day of the week (normalized for locale) for the last
2652
// day of the year.
2653
int yearLen = getActualMaximum(DAY_OF_YEAR);
2654                int ldy = (yearLen - internalGet(DAY_OF_YEAR) + dow) % 7;
2655                // We know yearLen >= DAY_OF_YEAR so we skip the += 7 step here.
2656

2657                // Get the limit day for the blocked-off rectangular year; that
2658
// is, the day which is one past the last day of the year,
2659
// after the year has already been filled in with phantom days
2660
// to fill out the last week. This day has a normalized DOW of 0.
2661
int limit = yearLen + 7 - ldy;
2662
2663                // Now roll between start and (limit - 1).
2664
int gap = limit - start;
2665                int day_of_year = (internalGet(DAY_OF_YEAR) + amount*7 -
2666                                    start) % gap;
2667                if (day_of_year < 0) day_of_year += gap;
2668                day_of_year += start;
2669
2670                // Finally, pin to the real start and end of the month.
2671
if (day_of_year < 1) day_of_year = 1;
2672                if (day_of_year > yearLen) day_of_year = yearLen;
2673
2674                // Make sure that the year and day of year are attended to by
2675
// clearing other fields which would normally take precedence.
2676
// If the disambiguation algorithm is changed, this section will
2677
// have to be updated as well.
2678
set(DAY_OF_YEAR, day_of_year);
2679                clear(MONTH);
2680                return;
2681            }
2682        case DAY_OF_YEAR:
2683            {
2684                // Roll the day of year using millis. Compute the millis for
2685
// the start of the year, and get the length of the year.
2686
long delta = amount * ONE_DAY; // Scale up from days to millis
2687
long min2 = time - (internalGet(DAY_OF_YEAR) - 1) * ONE_DAY;
2688                int yearLength = getActualMaximum(DAY_OF_YEAR);
2689                time = (time + delta - min2) % (yearLength*ONE_DAY);
2690                if (time < 0) time += yearLength*ONE_DAY;
2691                setTimeInMillis(time + min2);
2692                return;
2693            }
2694        case DAY_OF_WEEK:
2695        case DOW_LOCAL:
2696            {
2697                // Roll the day of week using millis. Compute the millis for
2698
// the start of the week, using the first day of week setting.
2699
// Restrict the millis to [start, start+7days).
2700
long delta = amount * ONE_DAY; // Scale up from days to millis
2701
// Compute the number of days before the current day in this
2702
// week. This will be a value 0..6.
2703
int leadDays = internalGet(field);
2704                leadDays -= (field == DAY_OF_WEEK) ? getFirstDayOfWeek() : 1;
2705                if (leadDays < 0) leadDays += 7;
2706                long min2 = time - leadDays * ONE_DAY;
2707                time = (time + delta - min2) % ONE_WEEK;
2708                if (time < 0) time += ONE_WEEK;
2709                setTimeInMillis(time + min2);
2710                return;
2711            }
2712        case DAY_OF_WEEK_IN_MONTH:
2713            {
2714                // Roll the day of week in the month using millis. Determine
2715
// the first day of the week in the month, and then the last,
2716
// and then roll within that range.
2717
long delta = amount * ONE_WEEK; // Scale up from weeks to millis
2718
// Find the number of same days of the week before this one
2719
// in this month.
2720
int preWeeks = (internalGet(DAY_OF_MONTH) - 1) / 7;
2721                // Find the number of same days of the week after this one
2722
// in this month.
2723
int postWeeks = (getActualMaximum(DAY_OF_MONTH) -
2724                                 internalGet(DAY_OF_MONTH)) / 7;
2725                // From these compute the min and gap millis for rolling.
2726
long min2 = time - preWeeks * ONE_WEEK;
2727                long gap2 = ONE_WEEK * (preWeeks + postWeeks + 1); // Must add 1!
2728
// Roll within this range
2729
time = (time + delta - min2) % gap2;
2730                if (time < 0) time += gap2;
2731                setTimeInMillis(time + min2);
2732                return;
2733            }
2734        case JULIAN_DAY:
2735            set(field, internalGet(field) + amount);
2736            return;
2737        default:
2738            // Other fields cannot be rolled by this method
2739
throw new IllegalArgumentException JavaDoc("Calendar.roll(" + fieldName(field) +
2740                                               ") not supported");
2741        }
2742    }
2743
2744    /**
2745     * Add a signed amount to a specified field, using this calendar's rules.
2746     * For example, to add three days to the current date, you can call
2747     * <code>add(Calendar.DATE, 3)</code>.
2748     * <p>
2749     * When adding to certain fields, the values of other fields may conflict and
2750     * need to be changed. For example, when adding one to the {@link #MONTH MONTH} field
2751     * for the Gregorian date 1/31/96, the {@link #DAY_OF_MONTH DAY_OF_MONTH} field
2752     * must be adjusted so that the result is 2/29/96 rather than the invalid
2753     * 2/31/96.
2754     * <p>
2755     * The <code>com.ibm.icu.util.Calendar</code> implementation of this method is able to add to
2756     * all fields except for {@link #ERA ERA}, {@link #DST_OFFSET DST_OFFSET},
2757     * and {@link #ZONE_OFFSET ZONE_OFFSET}. Subclasses may, of course, add support for
2758     * additional fields in their overrides of <code>add</code>.
2759     * <p>
2760     * <b>Note:</b> You should always use <tt>roll</tt> and <tt>add</tt> rather
2761     * than attempting to perform arithmetic operations directly on the fields
2762     * of a <tt>Calendar</tt>. It is quite possible for <tt>Calendar</tt> subclasses
2763     * to have fields with non-linear behavior, for example missing months
2764     * or days during non-leap years. The subclasses' <tt>add</tt> and <tt>roll</tt>
2765     * methods will take this into account, while simple arithmetic manipulations
2766     * may give invalid results.
2767     * <p>
2768     * <b>Subclassing:</b><br>
2769     * This implementation of <code>add</code> assumes that the behavior of the
2770     * field is continuous between its minimum and maximum, which are found by
2771     * calling {@link #getActualMinimum getActualMinimum} and
2772     * {@link #getActualMaximum getActualMaximum}.
2773     * For such fields, simple arithmetic operations are sufficient to
2774     * perform the add.
2775     * <p>
2776     * Subclasses that have fields for which this assumption of continuity breaks
2777     * down must overide <code>add</code> to handle those fields specially.
2778     * For example, in the Hebrew calendar the month "Adar I"
2779     * only occurs in leap years; in other years the calendar jumps from
2780     * Shevat (month #4) to Adar (month #6). The
2781     * {@link HebrewCalendar#add HebrewCalendar.add} method takes this into account,
2782     * so that adding one month
2783     * to a date in Shevat gives the proper result (Adar) in a non-leap year.
2784     * <p>
2785     * @param field the time field.
2786     * @param amount the amount to add to the field.
2787     *
2788     * @exception IllegalArgumentException if the field is invalid or refers
2789     * to a field that cannot be handled by this method.
2790     * @see #roll(int, int)
2791     * @stable ICU 2.0
2792     */

2793    public void add(int field, int amount) {
2794
2795        if (amount == 0) {
2796            return; // Do nothing!
2797
}
2798
2799        // We handle most fields in the same way. The algorithm is to add
2800
// a computed amount of millis to the current millis. The only
2801
// wrinkle is with DST -- for some fields, like the DAY_OF_MONTH,
2802
// we don't want the HOUR to shift due to changes in DST. If the
2803
// result of the add operation is to move from DST to Standard, or
2804
// vice versa, we need to adjust by an hour forward or back,
2805
// respectively. For such fields we set keepHourInvariant to true.
2806

2807        // We only adjust the DST for fields larger than an hour. For
2808
// fields smaller than an hour, we cannot adjust for DST without
2809
// causing problems. for instance, if you add one hour to April 5,
2810
// 1998, 1:00 AM, in PST, the time becomes "2:00 AM PDT" (an
2811
// illegal value), but then the adjustment sees the change and
2812
// compensates by subtracting an hour. As a result the time
2813
// doesn't advance at all.
2814

2815        // For some fields larger than a day, such as a MONTH, we pin the
2816
// DAY_OF_MONTH. This allows <March 31>.add(MONTH, 1) to be
2817
// <April 30>, rather than <April 31> => <May 1>.
2818

2819        long delta = amount; // delta in ms
2820
boolean keepHourInvariant = true;
2821
2822        switch (field) {
2823        case ERA:
2824            set(field, get(field) + amount);
2825            pinField(ERA);
2826            return;
2827
2828        case YEAR:
2829        case EXTENDED_YEAR:
2830        case YEAR_WOY:
2831        case MONTH:
2832            set(field, get(field) + amount);
2833            pinField(DAY_OF_MONTH);
2834            return;
2835
2836        case WEEK_OF_YEAR:
2837        case WEEK_OF_MONTH:
2838        case DAY_OF_WEEK_IN_MONTH:
2839            delta *= ONE_WEEK;
2840            break;
2841
2842        case AM_PM:
2843            delta *= 12 * ONE_HOUR;
2844            break;
2845
2846        case DAY_OF_MONTH:
2847        case DAY_OF_YEAR:
2848        case DAY_OF_WEEK:
2849        case DOW_LOCAL:
2850        case JULIAN_DAY:
2851            delta *= ONE_DAY;
2852            break;
2853
2854        case HOUR_OF_DAY:
2855        case HOUR:
2856            delta *= ONE_HOUR;
2857            keepHourInvariant = false;
2858            break;
2859
2860        case MINUTE:
2861            delta *= ONE_MINUTE;
2862            keepHourInvariant = false;
2863            break;
2864
2865        case SECOND:
2866            delta *= ONE_SECOND;
2867            keepHourInvariant = false;
2868            break;
2869
2870        case MILLISECOND:
2871        case MILLISECONDS_IN_DAY:
2872            keepHourInvariant = false;
2873            break;
2874
2875        default:
2876            throw new IllegalArgumentException JavaDoc("Calendar.add(" + fieldName(field) +
2877                                               ") not supported");
2878        }
2879
2880        // In order to keep the hour invariant (for fields where this is
2881
// appropriate), record the DST_OFFSET before and after the add()
2882
// operation. If it has changed, then adjust the millis to
2883
// compensate.
2884
int dst = 0;
2885        int hour = 0;
2886        if (keepHourInvariant) {
2887            dst = get(DST_OFFSET);
2888            hour = internalGet(HOUR_OF_DAY);
2889        }
2890
2891        setTimeInMillis(getTimeInMillis() + delta);
2892
2893        if (keepHourInvariant) {
2894            dst -= get(DST_OFFSET);
2895            if (dst != 0) {
2896                // We have done an hour-invariant adjustment but the
2897
// DST offset has altered. We adjust millis to keep
2898
// the hour constant. In cases such as midnight after
2899
// a DST change which occurs at midnight, there is the
2900
// danger of adjusting into a different day. To avoid
2901
// this we make the adjustment only if it actually
2902
// maintains the hour.
2903
long t = time;
2904                setTimeInMillis(time + dst);
2905                if (get(HOUR_OF_DAY) != hour) {
2906                    setTimeInMillis(t);
2907                }
2908            }
2909        }
2910    }
2911
2912    /**
2913     * Return the name of this calendar in the language of the given locale.
2914     * @stable ICU 2.0
2915     */

2916    public String JavaDoc getDisplayName(Locale JavaDoc loc) {
2917        return this.getClass().getName();
2918    }
2919
2920    /**
2921     * Return the name of this calendar in the language of the given locale.
2922     * @draft ICU 3.2
2923     * @provisional This API might change or be removed in a future release.
2924     */

2925    public String JavaDoc getDisplayName(ULocale loc) {
2926        return this.getClass().getName();
2927    }
2928
2929    /**
2930     * Compares the times (in millis) represented by two
2931     * <code>Calendar</code> objects.
2932     *
2933     * @param that the <code>Calendar</code> to compare to this.
2934     * @return <code>0</code> if the time represented by
2935     * this <code>Calendar</code> is equal to the time represented
2936     * by that <code>Calendar</code>, a value less than
2937     * <code>0</code> if the time represented by this is before
2938     * the time represented by that, and a value greater than
2939     * <code>0</code> if the time represented by this
2940     * is after the time represented by that.
2941     * @throws NullPointerException if that
2942     * <code>Calendar</code> is null.
2943     * @throws IllegalArgumentException if the time of that
2944     * <code>Calendar</code> can't be obtained because of invalid
2945     * calendar values.
2946     * @draft ICU 3.4
2947     * @provisional This API might change or be removed in a future release.
2948     */

2949    public int compareTo(Calendar that) {
2950        long v = getTimeInMillis() - that.getTimeInMillis();
2951        return v < 0 ? -1 : (v > 0 ? 1 : 0);
2952    }
2953
2954    /**
2955     * Implement comparable API as a convenience override of
2956     * {@link #compareTo(Calendar)}.
2957     * @draft ICU 3.4
2958     * @provisional This API might change or be removed in a future release.
2959     */

2960    public int compareTo(Object JavaDoc that) {
2961        return compareTo((Calendar)that);
2962    }
2963
2964    //-------------------------------------------------------------------------
2965
// Interface for creating custon DateFormats for different types of Calendars
2966
//-------------------------------------------------------------------------
2967

2968    /**
2969     * Return a <code>DateFormat</code> appropriate to this calendar.
2970     * Subclasses wishing to specialize this behavior should override
2971     * <code>handleGetDateFormat()</code>
2972     * @see #handleGetDateFormat
2973     * @stable ICU 2.0
2974     */

2975    public DateFormat getDateTimeFormat(int dateStyle, int timeStyle, Locale JavaDoc loc) {
2976        return formatHelper(this, ULocale.forLocale(loc), dateStyle, timeStyle);
2977    }
2978
2979    /**
2980     * Return a <code>DateFormat</code> appropriate to this calendar.
2981     * Subclasses wishing to specialize this behavior should override
2982     * <code>handleGetDateFormat()</code>
2983     * @see #handleGetDateFormat
2984     * @draft ICU 3.2
2985     * @provisional This API might change or be removed in a future release.
2986     */

2987    public DateFormat getDateTimeFormat(int dateStyle, int timeStyle, ULocale loc) {
2988        return formatHelper(this, loc, dateStyle, timeStyle);
2989    }
2990
2991    /**
2992     * Create a <code>DateFormat</code> appropriate to this calendar.
2993     * This is a framework method for subclasses to override. This method
2994     * is responsible for creating the calendar-specific DateFormat and
2995     * DateFormatSymbols objects as needed.
2996     * @param pattern the pattern, specific to the <code>DateFormat</code>
2997     * subclass
2998     * @param locale the locale for which the symbols should be drawn
2999     * @return a <code>DateFormat</code> appropriate to this calendar
3000     * @stable ICU 2.0
3001     */

3002    protected DateFormat handleGetDateFormat(String JavaDoc pattern, Locale JavaDoc locale) {
3003        return handleGetDateFormat(pattern, ULocale.forLocale(locale));
3004    }
3005
3006    /**
3007     * Create a <code>DateFormat</code> appropriate to this calendar.
3008     * This is a framework method for subclasses to override. This method
3009     * is responsible for creating the calendar-specific DateFormat and
3010     * DateFormatSymbols objects as needed.
3011     * @param pattern the pattern, specific to the <code>DateFormat</code>
3012     * subclass
3013     * @param locale the locale for which the symbols should be drawn
3014     * @return a <code>DateFormat</code> appropriate to this calendar
3015     * @draft ICU 3.2
3016     * @provisional This API might change or be removed in a future release.
3017     */

3018    protected DateFormat handleGetDateFormat(String JavaDoc pattern, ULocale locale) {
3019        FormatConfiguration fmtConfig = new FormatConfiguration();
3020        fmtConfig.pattern = pattern;
3021        fmtConfig.formatData = new DateFormatSymbols(this, locale);
3022        fmtConfig.loc = locale;
3023        fmtConfig.cal = this;
3024
3025        return SimpleDateFormat.getInstance(fmtConfig);
3026    }
3027
3028    // date format pattern cache
3029
private static final ICUCache PATTERN_CACHE = new SimpleCache();
3030    // final fallback patterns
3031
private static final String JavaDoc[] DEFAULT_PATTERNS = {
3032        "HH:mm:ss z",
3033        "HH:mm:ss z",
3034        "HH:mm:ss",
3035        "HH:mm",
3036        "EEEE, yyyy MMMM dd",
3037        "yyyy MMMM d",
3038        "yyyy MMM d",
3039        "yy/MM/dd",
3040        "{1} {0}"
3041    };
3042
3043    static private DateFormat formatHelper(Calendar cal, ULocale loc, int dateStyle, int timeStyle) {
3044        // First, try to get a pattern from PATTERN_CACHE
3045
String JavaDoc key = loc.toString() + cal.getType();
3046        String JavaDoc[] patterns = (String JavaDoc[])PATTERN_CACHE.get(key);
3047        if (patterns == null) {
3048            // Cache missed. Get one from bundle
3049
try {
3050                CalendarData calData = new CalendarData(loc, cal.getType());
3051                patterns = calData.get("DateTimePatterns").getStringArray();
3052            } catch (MissingResourceException JavaDoc e) {
3053                patterns = DEFAULT_PATTERNS;
3054            }
3055            PATTERN_CACHE.put(key, patterns);
3056        }
3057        // Resolve a pattern for the date/time style
3058
String JavaDoc pattern = null;
3059        if ((timeStyle >= 0) && (dateStyle >= 0)) {
3060            pattern = MessageFormat.format(patterns[8],
3061                    new Object JavaDoc[] {patterns[timeStyle], patterns[dateStyle + 4]});
3062        } else if (timeStyle >= 0) {
3063            pattern = patterns[timeStyle];
3064        } else if (dateStyle >= 0) {
3065            pattern = patterns[dateStyle + 4];
3066        } else {
3067            throw new IllegalArgumentException JavaDoc("No date or time style specified");
3068        }
3069        DateFormat result = cal.handleGetDateFormat(pattern, loc);
3070        result.setCalendar(cal);
3071        return result;
3072    }
3073
3074    /**
3075     * An instance of FormatConfiguration represents calendar specific
3076     * date format configuration and used for calling the ICU private
3077     * SimpleDateFormat factory method.
3078     *
3079     * @internal
3080     * @deprecated This API is ICU internal only.
3081     */

3082    public static class FormatConfiguration {
3083        private String JavaDoc pattern;
3084        private DateFormatSymbols formatData;
3085        private Calendar cal;
3086        private ULocale loc;
3087
3088        // Only Calendar can instantiate
3089
private FormatConfiguration() {
3090        }
3091
3092        public String JavaDoc getPatternString() {
3093            return pattern;
3094        }
3095
3096        public Calendar getCalendar() {
3097            return cal;
3098        }
3099
3100        public ULocale getLocale() {
3101            return loc;
3102        }
3103
3104        public DateFormatSymbols getDateFormatSymbols() {
3105            return formatData;
3106        }
3107    }
3108
3109    //-------------------------------------------------------------------------
3110
// Protected utility methods for use by subclasses. These are very handy
3111
// for implementing add, roll, and computeFields.
3112
//-------------------------------------------------------------------------
3113

3114    /**
3115     * Adjust the specified field so that it is within
3116     * the allowable range for the date to which this calendar is set.
3117     * For example, in a Gregorian calendar pinning the {@link #DAY_OF_MONTH DAY_OF_MONTH}
3118     * field for a calendar set to April 31 would cause it to be set
3119     * to April 30.
3120     * <p>
3121     * <b>Subclassing:</b>
3122     * <br>
3123     * This utility method is intended for use by subclasses that need to implement
3124     * their own overrides of {@link #roll roll} and {@link #add add}.
3125     * <p>
3126     * <b>Note:</b>
3127     * <code>pinField</code> is implemented in terms of
3128     * {@link #getActualMinimum getActualMinimum}
3129     * and {@link #getActualMaximum getActualMaximum}. If either of those methods uses
3130     * a slow, iterative algorithm for a particular field, it would be
3131     * unwise to attempt to call <code>pinField</code> for that field. If you
3132     * really do need to do so, you should override this method to do
3133     * something more efficient for that field.
3134     * <p>
3135     * @param field The calendar field whose value should be pinned.
3136     *
3137     * @see #getActualMinimum
3138     * @see #getActualMaximum
3139     * @stable ICU 2.0
3140     */

3141    protected void pinField(int field) {
3142        int max = getActualMaximum(field);
3143        int min = getActualMinimum(field);
3144
3145        if (fields[field] > max) {
3146            set(field, max);
3147        } else if (fields[field] < min) {
3148            set(field, min);
3149        }
3150    }
3151
3152    /**
3153     * Return the week number of a day, within a period. This may be the week number in
3154     * a year or the week number in a month. Usually this will be a value >= 1, but if
3155     * some initial days of the period are excluded from week 1, because
3156     * {@link #getMinimalDaysInFirstWeek getMinimalDaysInFirstWeek} is > 1, then
3157     * the week number will be zero for those
3158     * initial days. This method requires the day number and day of week for some
3159     * known date in the period in order to determine the day of week
3160     * on the desired day.
3161     * <p>
3162     * <b>Subclassing:</b>
3163     * <br>
3164     * This method is intended for use by subclasses in implementing their
3165     * {@link #computeTime computeTime} and/or {@link #computeFields computeFields} methods.
3166     * It is often useful in {@link #getActualMinimum getActualMinimum} and
3167     * {@link #getActualMaximum getActualMaximum} as well.
3168     * <p>
3169     * This variant is handy for computing the week number of some other
3170     * day of a period (often the first or last day of the period) when its day
3171     * of the week is not known but the day number and day of week for some other
3172     * day in the period (e.g. the current date) <em>is</em> known.
3173     * <p>
3174     * @param desiredDay The {@link #DAY_OF_YEAR DAY_OF_YEAR} or
3175     * {@link #DAY_OF_MONTH DAY_OF_MONTH} whose week number is desired.
3176     * Should be 1 for the first day of the period.
3177     *
3178     * @param dayOfPeriod The {@link #DAY_OF_YEAR DAY_OF_YEAR}
3179     * or {@link #DAY_OF_MONTH DAY_OF_MONTH} for a day in the period whose
3180     * {@link #DAY_OF_WEEK DAY_OF_WEEK} is specified by the
3181     * <code>dayOfWeek</code> parameter.
3182     * Should be 1 for first day of period.
3183     *
3184     * @param dayOfWeek The {@link #DAY_OF_WEEK DAY_OF_WEEK} for the day
3185     * corresponding to the <code>dayOfPeriod</code> parameter.
3186     * 1-based with 1=Sunday.
3187     *
3188     * @return The week number (one-based), or zero if the day falls before
3189     * the first week because
3190     * {@link #getMinimalDaysInFirstWeek getMinimalDaysInFirstWeek}
3191     * is more than one.
3192     * @stable ICU 2.0
3193     */

3194    protected int weekNumber(int desiredDay, int dayOfPeriod, int dayOfWeek)
3195    {
3196        // Determine the day of the week of the first day of the period
3197
// in question (either a year or a month). Zero represents the
3198
// first day of the week on this calendar.
3199
int periodStartDayOfWeek = (dayOfWeek - getFirstDayOfWeek() - dayOfPeriod + 1) % 7;
3200        if (periodStartDayOfWeek < 0) periodStartDayOfWeek += 7;
3201
3202        // Compute the week number. Initially, ignore the first week, which
3203
// may be fractional (or may not be). We add periodStartDayOfWeek in
3204
// order to fill out the first week, if it is fractional.
3205
int weekNo = (desiredDay + periodStartDayOfWeek - 1)/7;
3206
3207        // If the first week is long enough, then count it. If
3208
// the minimal days in the first week is one, or if the period start
3209
// is zero, we always increment weekNo.
3210
if ((7 - periodStartDayOfWeek) >= getMinimalDaysInFirstWeek()) ++weekNo;
3211
3212        return weekNo;
3213    }
3214
3215    /**
3216     * Return the week number of a day, within a period. This may be the week number in
3217     * a year, or the week number in a month. Usually this will be a value >= 1, but if
3218     * some initial days of the period are excluded from week 1, because
3219     * {@link #getMinimalDaysInFirstWeek getMinimalDaysInFirstWeek} is > 1,
3220     * then the week number will be zero for those
3221     * initial days. This method requires the day of week for the given date in order to
3222     * determine the result.
3223     * <p>
3224     * <b>Subclassing:</b>
3225     * <br>
3226     * This method is intended for use by subclasses in implementing their
3227     * {@link #computeTime computeTime} and/or {@link #computeFields computeFields} methods.
3228     * It is often useful in {@link #getActualMinimum getActualMinimum} and
3229     * {@link #getActualMaximum getActualMaximum} as well.
3230     * <p>
3231     * @param dayOfPeriod The {@link #DAY_OF_YEAR DAY_OF_YEAR} or
3232     * {@link #DAY_OF_MONTH DAY_OF_MONTH} whose week number is desired.
3233     * Should be 1 for the first day of the period.
3234     *
3235     * @param dayOfWeek The {@link #DAY_OF_WEEK DAY_OF_WEEK} for the day
3236     * corresponding to the <code>dayOfPeriod</code> parameter.
3237     * 1-based with 1=Sunday.
3238     *
3239     * @return The week number (one-based), or zero if the day falls before
3240     * the first week because
3241     * {@link #getMinimalDaysInFirstWeek getMinimalDaysInFirstWeek}
3242     * is more than one.
3243     * @stable ICU 2.0
3244     */

3245    protected final int weekNumber(int dayOfPeriod, int dayOfWeek)
3246    {
3247        return weekNumber(dayOfPeriod, dayOfPeriod, dayOfWeek);
3248    }
3249
3250    //-------------------------------------------------------------------------
3251
// Constants
3252
//-------------------------------------------------------------------------
3253

3254    /**
3255     * [NEW]
3256     * Return the difference between the given time and the time this
3257     * calendar object is set to. If this calendar is set
3258     * <em>before</em> the given time, the returned value will be
3259     * positive. If this calendar is set <em>after</em> the given
3260     * time, the returned value will be negative. The
3261     * <code>field</code> parameter specifies the units of the return
3262     * value. For example, if <code>fieldDifference(when,
3263     * Calendar.MONTH)</code> returns 3, then this calendar is set to
3264     * 3 months before <code>when</code>, and possibly some additional
3265     * time less than one month.
3266     *
3267     * <p>As a side effect of this call, this calendar is advanced
3268     * toward <code>when</code> by the given amount. That is, calling
3269     * this method has the side effect of calling <code>add(field,
3270     * n)</code>, where <code>n</code> is the return value.
3271     *
3272     * <p>Usage: To use this method, call it first with the largest
3273     * field of interest, then with progressively smaller fields. For
3274     * example:
3275     *
3276     * <pre>
3277     * int y = cal.fieldDifference(when, Calendar.YEAR);
3278     * int m = cal.fieldDifference(when, Calendar.MONTH);
3279     * int d = cal.fieldDifference(when, Calendar.DATE);</pre>
3280     *
3281     * computes the difference between <code>cal</code> and
3282     * <code>when</code> in years, months, and days.
3283     *
3284     * <p>Note: <code>fieldDifference()</code> is
3285     * <em>asymmetrical</em>. That is, in the following code:
3286     *
3287     * <pre>
3288     * cal.setTime(date1);
3289     * int m1 = cal.fieldDifference(date2, Calendar.MONTH);
3290     * int d1 = cal.fieldDifference(date2, Calendar.DATE);
3291     * cal.setTime(date2);
3292     * int m2 = cal.fieldDifference(date1, Calendar.MONTH);
3293     * int d2 = cal.fieldDifference(date1, Calendar.DATE);</pre>
3294     *
3295     * one might expect that <code>m1 == -m2 && d1 == -d2</code>.
3296     * However, this is not generally the case, because of
3297     * irregularities in the underlying calendar system (e.g., the
3298     * Gregorian calendar has a varying number of days per month).
3299     *
3300     * @param when the date to compare this calendar's time to
3301     * @param field the field in which to compute the result
3302     * @return the difference, either positive or negative, between
3303     * this calendar's time and <code>when</code>, in terms of
3304     * <code>field</code>.
3305     * @stable ICU 2.0
3306     */

3307    public int fieldDifference(Date JavaDoc when, int field) {
3308        int min = 0;
3309        long startMs = getTimeInMillis();
3310        long targetMs = when.getTime();
3311        // Always add from the start millis. This accomodates
3312
// operations like adding years from February 29, 2000 up to
3313
// February 29, 2004. If 1, 1, 1, 1 is added to the year
3314
// field, the DOM gets pinned to 28 and stays there, giving an
3315
// incorrect DOM difference of 1. We have to add 1, reset, 2,
3316
// reset, 3, reset, 4.
3317
if (startMs < targetMs) {
3318            int max = 1;
3319            // Find a value that is too large
3320
for (;;) {
3321                setTimeInMillis(startMs);
3322                add(field, max);
3323                long ms = getTimeInMillis();
3324                if (ms == targetMs) {
3325                    return max;
3326                } else if (ms > targetMs) {
3327                    break;
3328                } else {
3329                    max <<= 1;
3330                    if (max < 0) {
3331                        // Field difference too large to fit into int
3332
throw new RuntimeException JavaDoc();
3333                    }
3334                }
3335            }
3336            // Do a binary search
3337
while ((max - min) > 1) {
3338                int t = (min + max) / 2;
3339                setTimeInMillis(startMs);
3340                add(field, t);
3341                long ms = getTimeInMillis();
3342                if (ms == targetMs) {
3343                    return t;
3344                } else if (ms > targetMs) {
3345                    max = t;
3346                } else {
3347                    min = t;
3348                }
3349            }
3350        } else if (startMs > targetMs) {
3351            if (false) {
3352                // This works, and makes the code smaller, but costs
3353
// an extra object creation and an extra couple cycles
3354
// of calendar computation.
3355
setTimeInMillis(targetMs);
3356                min = -fieldDifference(new Date JavaDoc(startMs), field);
3357            }
3358            int max = -1;
3359            // Find a value that is too small
3360
for (;;) {
3361                setTimeInMillis(startMs);
3362                add(field, max);
3363                long ms = getTimeInMillis();
3364                if (ms == targetMs) {
3365                    return max;
3366                } else if (ms < targetMs) {
3367                    break;
3368                } else {
3369                    max <<= 1;
3370                    if (max == 0) {
3371                        // Field difference too large to fit into int
3372
throw new RuntimeException JavaDoc();
3373                    }
3374                }
3375            }
3376            // Do a binary search
3377
while ((min - max) > 1) {
3378                int t = (min + max) / 2;
3379                setTimeInMillis(startMs);
3380                add(field, t);
3381                long ms = getTimeInMillis();
3382                if (ms == targetMs) {
3383                    return t;
3384                } else if (ms < targetMs) {
3385                    max = t;
3386                } else {
3387                    min = t;
3388                }
3389            }
3390        }
3391        // Set calendar to end point
3392
setTimeInMillis(startMs);
3393        add(field, min);
3394        return min;
3395    }
3396
3397    /**
3398     * Sets the time zone with the given time zone value.
3399     * @param value the given time zone.
3400     * @stable ICU 2.0
3401     */

3402    public void setTimeZone(TimeZone value)
3403    {
3404        zone = value;
3405        /* Recompute the fields from the time using the new zone. This also
3406         * works if isTimeSet is false (after a call to set()). In that case
3407         * the time will be computed from the fields using the new zone, then
3408         * the fields will get recomputed from that. Consider the sequence of
3409         * calls: cal.setTimeZone(EST); cal.set(HOUR, 1); cal.setTimeZone(PST).
3410         * Is cal set to 1 o'clock EST or 1 o'clock PST? Answer: PST. More
3411         * generally, a call to setTimeZone() affects calls to set() BEFORE AND
3412         * AFTER it up to the next call to complete().
3413         */

3414        areFieldsSet = false;
3415    }
3416
3417    /**
3418     * Gets the time zone.
3419     * @return the time zone object associated with this calendar.
3420     * @stable ICU 2.0
3421     */

3422    public TimeZone getTimeZone()
3423    {
3424        return zone;
3425    }
3426
3427    /**
3428     * Specify whether or not date/time interpretation is to be lenient. With
3429     * lenient interpretation, a date such as "February 942, 1996" will be
3430     * treated as being equivalent to the 941st day after February 1, 1996.
3431     * With strict interpretation, such dates will cause an exception to be
3432     * thrown.
3433     *
3434     * @see DateFormat#setLenient
3435     * @stable ICU 2.0
3436     */

3437    public void setLenient(boolean lenient)
3438    {
3439        this.lenient = lenient;
3440    }
3441
3442    /**
3443     * Tell whether date/time interpretation is to be lenient.
3444     * @stable ICU 2.0
3445     */

3446    public boolean isLenient()
3447    {
3448        return lenient;
3449    }
3450
3451    /**
3452     * Sets what the first day of the week is; e.g., Sunday in US,
3453     * Monday in France.
3454     * @param value the given first day of the week.
3455     * @stable ICU 2.0
3456     */

3457    public void setFirstDayOfWeek(int value)
3458    {
3459        if (firstDayOfWeek != value) {
3460            if (value < SUNDAY || value > SATURDAY) {
3461                throw new IllegalArgumentException JavaDoc("Invalid day of week");
3462            }
3463            firstDayOfWeek = value;
3464            areFieldsSet = false;
3465        }
3466    }
3467
3468    /**
3469     * Gets what the first day of the week is; e.g., Sunday in US,
3470     * Monday in France.
3471     * @return the first day of the week.
3472     * @stable ICU 2.0
3473     */

3474    public int getFirstDayOfWeek()
3475    {
3476        return firstDayOfWeek;
3477    }
3478
3479    /**
3480     * Sets what the minimal days required in the first week of the year are.
3481     * For example, if the first week is defined as one that contains the first
3482     * day of the first month of a year, call the method with value 1. If it
3483     * must be a full week, use value 7.
3484     * @param value the given minimal days required in the first week
3485     * of the year.
3486     * @stable ICU 2.0
3487     */

3488    public void setMinimalDaysInFirstWeek(int value)
3489    {
3490        // Values less than 1 have the same effect as 1; values greater
3491
// than 7 have the same effect as 7. However, we normalize values
3492
// so operator== and so forth work.
3493
if (value < 1) {
3494            value = 1;
3495        } else if (value > 7) {
3496            value = 7;
3497        }
3498        if (minimalDaysInFirstWeek != value) {
3499            minimalDaysInFirstWeek = value;
3500            areFieldsSet = false;
3501        }
3502    }
3503
3504    /**
3505     * Gets what the minimal days required in the first week of the year are;
3506     * e.g., if the first week is defined as one that contains the first day
3507     * of the first month of a year, getMinimalDaysInFirstWeek returns 1. If
3508     * the minimal days required must be a full week, getMinimalDaysInFirstWeek
3509     * returns 7.
3510     * @return the minimal days required in the first week of the year.
3511     * @stable ICU 2.0
3512     */

3513    public int getMinimalDaysInFirstWeek()
3514    {
3515        return minimalDaysInFirstWeek;
3516    }
3517
3518    private static final int LIMITS[][] = {
3519        // Minimum Greatest min Least max Greatest max
3520
{/* */}, // ERA
3521
{/* */}, // YEAR
3522
{/* */}, // MONTH
3523
{/* */}, // WEEK_OF_YEAR
3524
{/* */}, // WEEK_OF_MONTH
3525
{/* */}, // DAY_OF_MONTH
3526
{/* */}, // DAY_OF_YEAR
3527
{ 1, 1, 7, 7 }, // DAY_OF_WEEK
3528
{/* */}, // DAY_OF_WEEK_IN_MONTH
3529
{ 0, 0, 1, 1 }, // AM_PM
3530
{ 0, 0, 11, 11 }, // HOUR
3531
{ 0, 0, 23, 23 }, // HOUR_OF_DAY
3532
{ 0, 0, 59, 59 }, // MINUTE
3533
{ 0, 0, 59, 59 }, // SECOND
3534
{ 0, 0, 999, 999 }, // MILLISECOND
3535
{-12*ONE_HOUR, -12*ONE_HOUR, 12*ONE_HOUR, 12*ONE_HOUR }, // ZONE_OFFSET
3536
{ 0, 0, 1*ONE_HOUR, 1*ONE_HOUR }, // DST_OFFSET
3537
{/* */}, // YEAR_WOY
3538
{ 1, 1, 7, 7 }, // DOW_LOCAL
3539
{/* */}, // EXTENDED_YEAR
3540
{ -0x7F000000, -0x7F000000, 0x7F000000, 0x7F000000 }, // JULIAN_DAY
3541
{ 0, 0, 24*ONE_HOUR-1, 24*ONE_HOUR-1 }, // MILLISECONDS_IN_DAY
3542
};
3543
3544    /**
3545     * Subclass API for defining limits of different types.
3546     * Subclasses must implement this method to return limits for the
3547     * following fields:
3548     *
3549     * <pre>ERA
3550     * YEAR
3551     * MONTH
3552     * WEEK_OF_YEAR
3553     * WEEK_OF_MONTH
3554     * DAY_OF_MONTH
3555     * DAY_OF_YEAR
3556     * DAY_OF_WEEK_IN_MONTH
3557     * YEAR_WOY
3558     * EXTENDED_YEAR</pre>
3559     *
3560     * @param field one of the above field numbers
3561     * @param limitType one of <code>MINIMUM</code>, <code>GREATEST_MINIMUM</code>,
3562     * <code>LEAST_MAXIMUM</code>, or <code>MAXIMUM</code>
3563     * @stable ICU 2.0
3564     */

3565    abstract protected int handleGetLimit(int field, int limitType);
3566
3567    /**
3568     * Return a limit for a field.
3569     * @param field the field, from 0..</code>getFieldCount()-1</code>
3570     * @param limitType the type specifier for the limit
3571     * @see #MINIMUM
3572     * @see #GREATEST_MINIMUM
3573     * @see #LEAST_MAXIMUM
3574     * @see #MAXIMUM
3575     * @stable ICU 2.0
3576     */

3577    protected int getLimit(int field, int limitType) {
3578        switch (field) {
3579        case DAY_OF_WEEK:
3580        case AM_PM:
3581        case HOUR:
3582        case HOUR_OF_DAY:
3583        case MINUTE:
3584        case SECOND:
3585        case MILLISECOND:
3586        case ZONE_OFFSET:
3587        case DST_OFFSET:
3588        case DOW_LOCAL:
3589        case JULIAN_DAY:
3590        case MILLISECONDS_IN_DAY:
3591            return LIMITS[field][limitType];
3592        }
3593        return handleGetLimit(field, limitType);
3594    }
3595
3596    /**
3597     * Limit type for <code>getLimit()</code> and <code>handleGetLimit()</code>
3598     * indicating the minimum value that a field can take (least minimum).
3599     * @see #getLimit
3600     * @see #handleGetLimit
3601     * @stable ICU 2.0
3602     */

3603    protected static final int MINIMUM = 0;
3604
3605    /**
3606     * Limit type for <code>getLimit()</code> and <code>handleGetLimit()</code>
3607     * indicating the greatest minimum value that a field can take.
3608     * @see #getLimit
3609     * @see #handleGetLimit
3610     * @stable ICU 2.0
3611     */

3612    protected static final int GREATEST_MINIMUM = 1;
3613
3614    /**
3615     * Limit type for <code>getLimit()</code> and <code>handleGetLimit()</code>
3616     * indicating the least maximum value that a field can take.
3617     * @see #getLimit
3618     * @see #handleGetLimit
3619     * @stable ICU 2.0
3620     */

3621    protected static final int LEAST_MAXIMUM = 2;
3622
3623    /**
3624     * Limit type for <code>getLimit()</code> and <code>handleGetLimit()</code>
3625     * indicating the maximum value that a field can take (greatest maximum).
3626     * @see #getLimit
3627     * @see #handleGetLimit
3628     * @stable ICU 2.0
3629     */

3630    protected static final int MAXIMUM = 3;
3631
3632    /**
3633     * Gets the minimum value for the given time field.
3634     * e.g., for Gregorian DAY_OF_MONTH, 1.
3635     * @param field the given time field.
3636     * @return the minimum value for the given time field.
3637     * @stable ICU 2.0
3638     */

3639    public final int getMinimum(int field) {
3640        return getLimit(field, MINIMUM);
3641    }
3642
3643    /**
3644     * Gets the maximum value for the given time field.
3645     * e.g. for Gregorian DAY_OF_MONTH, 31.
3646     * @param field the given time field.
3647     * @return the maximum value for the given time field.
3648     * @stable ICU 2.0
3649     */

3650    public final int getMaximum(int field) {
3651        return getLimit(field, MAXIMUM);
3652    }
3653
3654    /**
3655     * Gets the highest minimum value for the given field if varies.
3656     * Otherwise same as getMinimum(). For Gregorian, no difference.
3657     * @param field the given time field.
3658     * @return the highest minimum value for the given time field.
3659     * @stable ICU 2.0
3660     */

3661    public final int getGreatestMinimum(int field) {
3662        return getLimit(field, GREATEST_MINIMUM);
3663    }
3664
3665    /**
3666     * Gets the lowest maximum value for the given field if varies.
3667     * Otherwise same as getMaximum(). e.g., for Gregorian DAY_OF_MONTH, 28.
3668     * @param field the given time field.
3669     * @return the lowest maximum value for the given time field.
3670     * @stable ICU 2.0
3671     */

3672    public final int getLeastMaximum(int field) {
3673        return getLimit(field, LEAST_MAXIMUM);
3674    }
3675
3676    //-------------------------------------------------------------------------
3677
// Weekend support -- determining which days of the week are the weekend
3678
// in a given locale
3679
//-------------------------------------------------------------------------
3680

3681    /**
3682     * Return whether the given day of the week is a weekday, a
3683     * weekend day, or a day that transitions from one to the other,
3684     * in this calendar system. If a transition occurs at midnight,
3685     * then the days before and after the transition will have the
3686     * type WEEKDAY or WEEKEND. If a transition occurs at a time
3687     * other than midnight, then the day of the transition will have
3688     * the type WEEKEND_ONSET or WEEKEND_CEASE. In this case, the
3689     * method getWeekendTransition() will return the point of
3690     * transition.
3691     * @param dayOfWeek either SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
3692     * THURSDAY, FRIDAY, or SATURDAY
3693     * @return either WEEKDAY, WEEKEND, WEEKEND_ONSET, or
3694     * WEEKEND_CEASE
3695     * @exception IllegalArgumentException if dayOfWeek is not
3696     * between SUNDAY and SATURDAY, inclusive
3697     * @see #WEEKDAY
3698     * @see #WEEKEND
3699     * @see #WEEKEND_ONSET
3700     * @see #WEEKEND_CEASE
3701     * @see #getWeekendTransition
3702     * @see #isWeekend(Date)
3703     * @see #isWeekend()
3704     * @stable ICU 2.0
3705     */

3706    public int getDayOfWeekType(int dayOfWeek) {
3707        if (dayOfWeek < SUNDAY || dayOfWeek > SATURDAY) {
3708            throw new IllegalArgumentException JavaDoc("Invalid day of week");
3709        }
3710        if (weekendOnset < weekendCease) {
3711            if (dayOfWeek < weekendOnset || dayOfWeek > weekendCease) {
3712                return WEEKDAY;
3713            }
3714        } else {
3715            if (dayOfWeek > weekendCease && dayOfWeek < weekendOnset) {
3716                return WEEKDAY;
3717            }
3718        }
3719        if (dayOfWeek == weekendOnset) {
3720            return (weekendOnsetMillis == 0) ? WEEKEND : WEEKEND_ONSET;
3721        }
3722        if (dayOfWeek == weekendCease) {
3723            return (weekendCeaseMillis == 0) ? WEEKDAY : WEEKEND_CEASE;
3724        }
3725        return WEEKEND;
3726    }
3727
3728    /**
3729     * Return the time during the day at which the weekend begins or end in
3730     * this calendar system. If getDayOfWeekType(dayOfWeek) ==
3731     * WEEKEND_ONSET return the time at which the weekend begins. If
3732     * getDayOfWeekType(dayOfWeek) == WEEKEND_CEASE return the time at
3733     * which the weekend ends. If getDayOfWeekType(dayOfWeek) has some
3734     * other value, then throw an exception.
3735     * @param dayOfWeek either SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
3736     * THURSDAY, FRIDAY, or SATURDAY
3737     * @return the milliseconds after midnight at which the
3738     * weekend begins or ends
3739     * @exception IllegalArgumentException if dayOfWeek is not
3740     * WEEKEND_ONSET or WEEKEND_CEASE
3741     * @see #getDayOfWeekType
3742     * @see #isWeekend(Date)
3743     * @see #isWeekend()
3744     * @stable ICU 2.0
3745     */

3746    public int getWeekendTransition(int dayOfWeek) {
3747        if (dayOfWeek == weekendOnset) {
3748            return weekendOnsetMillis;
3749        } else if (dayOfWeek == weekendCease) {
3750            return weekendCeaseMillis;
3751        }
3752        throw new IllegalArgumentException JavaDoc("Not weekend transition day");
3753    }
3754
3755    /**
3756     * Return true if the given date and time is in the weekend in
3757     * this calendar system. Equivalent to calling setTime() followed
3758     * by isWeekend(). Note: This method changes the time this
3759     * calendar is set to.
3760     * @param date the date and time
3761     * @return true if the given date and time is part of the
3762     * weekend
3763     * @see #getDayOfWeekType
3764     * @see #getWeekendTransition
3765     * @see #isWeekend()
3766     * @stable ICU 2.0
3767     */

3768    public boolean isWeekend(Date JavaDoc date) {
3769        setTime(date);
3770        return isWeekend();
3771    }
3772
3773    /**
3774     * Return true if this Calendar's current date and time is in the
3775     * weekend in this calendar system.
3776     * @return true if the given date and time is part of the
3777     * weekend
3778     * @see #getDayOfWeekType
3779     * @see #getWeekendTransition
3780     * @see #isWeekend(Date)
3781     * @stable ICU 2.0
3782     */

3783    public boolean isWeekend() {
3784        int dow = get(DAY_OF_WEEK);
3785        int dowt = getDayOfWeekType(dow);
3786        switch (dowt) {
3787        case WEEKDAY:
3788            return false;
3789        case WEEKEND:
3790            return true;
3791        default: // That is, WEEKEND_ONSET or WEEKEND_CEASE
3792
// Use internalGet() because the above call to get() populated
3793
// all fields.
3794
// [Note: There should be a better way to get millis in day.
3795
// For ICU4J, submit request for a MILLIS_IN_DAY field
3796
// and a DAY_NUMBER field (could be Julian day #). - aliu]
3797
int millisInDay = internalGet(MILLISECOND) + 1000 * (internalGet(SECOND) +
3798                60 * (internalGet(MINUTE) + 60 * internalGet(HOUR_OF_DAY)));
3799            int transition = getWeekendTransition(dow);
3800            return (dowt == WEEKEND_ONSET)
3801                ? (millisInDay >= transition)
3802                : (millisInDay < transition);
3803        }
3804        // (We can never reach this point.)
3805
}
3806
3807    //-------------------------------------------------------------------------
3808
// End of weekend support
3809
//-------------------------------------------------------------------------
3810

3811    /**
3812     * Overrides Cloneable
3813     * @stable ICU 2.0
3814     */

3815    public Object JavaDoc clone()
3816    {
3817        try {
3818            Calendar other = (Calendar) super.clone();
3819
3820            other.fields = new int[fields.length];
3821            other.stamp = new int[fields.length];
3822            System.arraycopy(this.fields, 0, other.fields, 0, fields.length);
3823            System.arraycopy(this.stamp, 0, other.stamp, 0, fields.length);
3824
3825            other.zone = (TimeZone) zone.clone();
3826            return other;
3827        }
3828        catch (CloneNotSupportedException JavaDoc e) {
3829            // this shouldn't happen, since we are Cloneable
3830
throw new IllegalStateException JavaDoc();
3831        }
3832    }
3833
3834    /**
3835     * Return a string representation of this calendar. This method
3836     * is intended to be used only for debugging purposes, and the
3837     * format of the returned string may vary between implementations.
3838     * The returned string may be empty but may not be <code>null</code>.
3839     *
3840     * @return a string representation of this calendar.
3841     * @stable ICU 2.0
3842     */

3843    public String JavaDoc toString() {
3844        StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
3845        buffer.append(getClass().getName());
3846        buffer.append("[time=");
3847        buffer.append(isTimeSet ? String.valueOf(time) : "?");
3848        buffer.append(",areFieldsSet=");
3849        buffer.append(areFieldsSet);
3850        buffer.append(",areAllFieldsSet=");
3851        buffer.append(areAllFieldsSet);
3852        buffer.append(",lenient=");
3853        buffer.append(lenient);
3854        buffer.append(",zone=");
3855        buffer.append(zone);
3856        buffer.append(",firstDayOfWeek=");
3857        buffer.append(firstDayOfWeek);
3858        buffer.append(",minimalDaysInFirstWeek=");
3859        buffer.append(minimalDaysInFirstWeek);
3860        for (int i=0; i<fields.length; ++i) {
3861            buffer.append(',').append(FIELD_NAME[i]).append('=');
3862            buffer.append(isSet(i) ? String.valueOf(fields[i]) : "?");
3863        }
3864        buffer.append(']');
3865        return buffer.toString();
3866    }
3867
3868    // =======================privates===============================
3869

3870    /**
3871     * Internal class that holds cached locale data.
3872     */

3873    private static class WeekData {
3874        public int firstDayOfWeek;
3875        public int minimalDaysInFirstWeek;
3876        public int weekendOnset;
3877        public int weekendOnsetMillis;
3878        public int weekendCease;
3879        public int weekendCeaseMillis;
3880        public ULocale actualLocale;
3881        public WeekData(int fdow, int mdifw,
3882                        int weekendOnset, int weekendOnsetMillis,
3883                        int weekendCease, int weekendCeaseMillis,
3884                        ULocale actualLoc) {
3885            this.firstDayOfWeek = fdow;
3886            this.minimalDaysInFirstWeek = mdifw;
3887            this.actualLocale = actualLoc;
3888            this.weekendOnset = weekendOnset;
3889            this.weekendOnsetMillis = weekendOnsetMillis;
3890            this.weekendCease = weekendCease;
3891            this.weekendCeaseMillis = weekendCeaseMillis;
3892        }
3893    }
3894    
3895    /**
3896     * Set this calendar to contain week and weekend data for the given
3897     * locale.
3898     * @param locale the locale
3899     */

3900    private void setWeekData(ULocale locale)
3901    {
3902        /* try to get the Locale data from the cache */
3903        WeekData data = (WeekData) cachedLocaleData.get(locale);
3904        
3905        if (data == null) { /* cache miss */
3906
3907            CalendarData calData = new CalendarData(locale, getType());
3908            int[] dateTimeElements = calData.get("DateTimeElements").getIntVector();
3909            int[] weekend = calData.get("weekend").getIntVector();
3910            data = new WeekData(dateTimeElements[0],dateTimeElements[1],
3911                                weekend[0],
3912                                weekend[1],
3913                                weekend[2],
3914                                weekend[3],
3915                                calData.getULocale());
3916            /* cache update */
3917            cachedLocaleData.put(locale, data);
3918        }
3919        setFirstDayOfWeek(data.firstDayOfWeek);
3920        setMinimalDaysInFirstWeek(data.minimalDaysInFirstWeek);
3921        weekendOnset = data.weekendOnset;
3922        weekendOnsetMillis = data.weekendOnsetMillis;
3923        weekendCease = data.weekendCease;
3924        weekendCeaseMillis = data.weekendCeaseMillis;
3925
3926        // TODO: determine the actual/valid locale
3927
ULocale uloc = data.actualLocale;
3928        setLocale(uloc, uloc);
3929    }
3930
3931    /**
3932     * Recompute the time and update the status fields isTimeSet
3933     * and areFieldsSet. Callers should check isTimeSet and only
3934     * call this method if isTimeSet is false.
3935     */

3936    private void updateTime() {
3937        computeTime();
3938        // If we are lenient, we need to recompute the fields to normalize
3939
// the values. Also, if we haven't set all the fields yet (i.e.,
3940
// in a newly-created object), we need to fill in the fields. [LIU]
3941
if (isLenient() || !areAllFieldsSet) areFieldsSet = false;
3942        isTimeSet = true;
3943        areFieldsVirtuallySet = false;
3944    }
3945
3946    /**
3947     * Save the state of this object to a stream (i.e., serialize it).
3948     *
3949     * Ideally, <code>Calendar</code> would only write out its state data and
3950     * the current time, and not write any field data out, such as
3951     * <code>fields[]</code>, <code>isTimeSet</code>, <code>areFieldsSet</code>,
3952     * and <code>isSet[]</code>. <code>nextStamp</code> also should not be part
3953     * of the persistent state. Unfortunately, this didn't happen before JDK 1.1
3954     * shipped. To be compatible with JDK 1.1, we will always have to write out
3955     * the field values and state flags. However, <code>nextStamp</code> can be
3956     * removed from the serialization stream; this will probably happen in the
3957     * near future.
3958     */

3959    private void writeObject(ObjectOutputStream JavaDoc stream)
3960         throws IOException JavaDoc
3961    {
3962        // Try to compute the time correctly, for the future (stream
3963
// version 2) in which we don't write out fields[] or isSet[].
3964
if (!isTimeSet) {
3965            try {
3966                updateTime();
3967            }
3968            catch (IllegalArgumentException JavaDoc e) {}
3969        }
3970
3971        // Write out the 1.1 FCS object.
3972
stream.defaultWriteObject();
3973    }
3974
3975    /**
3976     * Reconstitute this object from a stream (i.e., deserialize it).
3977     */

3978    private void readObject(ObjectInputStream JavaDoc stream)
3979        throws IOException JavaDoc, ClassNotFoundException JavaDoc {
3980
3981        stream.defaultReadObject();
3982
3983        initInternal();
3984
3985        isTimeSet = true;
3986        areFieldsSet = areAllFieldsSet = false;
3987        nextStamp = MINIMUM_USER_STAMP;
3988    }
3989
3990
3991    //----------------------------------------------------------------------
3992
// Time -> Fields
3993
//----------------------------------------------------------------------
3994

3995    /**
3996     * Converts the current millisecond time value <code>time</code> to
3997     * field values in <code>fields[]</code>. This synchronizes the time
3998     * field values with a new time that is set for the calendar. The time
3999     * is <em>not</em> recomputed first; to recompute the time, then the
4000     * fields, call the <code>complete</code> method.
4001     * @see #complete
4002     * @stable ICU 2.0
4003     */

4004    protected void computeFields() {
4005        int offsets[] = new int[2];
4006        getTimeZone().getOffset(time, false, offsets);
4007        long localMillis = time + offsets[0] + offsets[1];
4008
4009        // Mark fields as set. Do this before calling handleComputeFields().
4010
int mask = internalSetMask;
4011        for (int i=0; i<fields.length; ++i) {
4012            if ((mask & 1) == 0) {
4013                stamp[i] = INTERNALLY_SET;
4014            } else {
4015                stamp[i] = UNSET;
4016            }
4017            mask >>= 1;
4018        }
4019
4020        // We used to check for and correct extreme millis values (near
4021
// Long.MIN_VALUE or Long.MAX_VALUE) here. Such values would cause
4022
// overflows from positive to negative (or vice versa) and had to
4023
// be manually tweaked. We no longer need to do this because we
4024
// have limited the range of supported dates to those that have a
4025
// Julian day that fits into an int. This allows us to implement a
4026
// JULIAN_DAY field and also removes some inelegant code. - Liu
4027
// 11/6/00
4028

4029        long days = floorDivide(localMillis, ONE_DAY);
4030
4031        fields[JULIAN_DAY] = (int) days + EPOCH_JULIAN_DAY;
4032
4033        // In some cases we will have to call this method again below to
4034
// adjust for DST pushing us into the next Julian day.
4035
computeGregorianAndDOWFields(fields[JULIAN_DAY]);
4036
4037        // Call framework method to have subclass compute its fields.
4038
// These must include, at a minimum, MONTH, DAY_OF_MONTH,
4039
// EXTENDED_YEAR, YEAR, DAY_OF_YEAR. This method will call internalSet(),
4040
// which will update stamp[].
4041
handleComputeFields(fields[JULIAN_DAY]);
4042
4043        // Compute week-related fields, based on the subclass-computed
4044
// fields computed by handleComputeFields().
4045
computeWeekFields();
4046
4047        // Compute time-related fields. These are indepent of the date and
4048
// of the subclass algorithm. They depend only on the local zone
4049
// wall milliseconds in day.
4050
int millisInDay = (int) (localMillis - (days * ONE_DAY));
4051        fields[MILLISECONDS_IN_DAY] = millisInDay;
4052        fields[MILLISECOND] = millisInDay % 1000;
4053        millisInDay /= 1000;
4054        fields[SECOND] = millisInDay % 60;
4055        millisInDay /= 60;
4056        fields[MINUTE] = millisInDay % 60;
4057        millisInDay /= 60;
4058        fields[HOUR_OF_DAY] = millisInDay;
4059        fields[AM_PM] = millisInDay / 12; // Assume AM == 0
4060
fields[HOUR] = millisInDay % 12;
4061        fields[ZONE_OFFSET] = offsets[0];
4062        fields[DST_OFFSET] = offsets[1];
4063    }
4064
4065    /**
4066     * Compute the Gregorian calendar year, month, and day of month from
4067     * the given Julian day. These values are not stored in fields, but in
4068     * member variables gregorianXxx. Also compute the DAY_OF_WEEK and
4069     * DOW_LOCAL fields.
4070     */

4071    private final void computeGregorianAndDOWFields(int julianDay) {
4072        computeGregorianFields(julianDay);
4073
4074        // Compute day of week: JD 0 = Monday
4075
int dow = fields[DAY_OF_WEEK] = julianDayToDayOfWeek(julianDay);
4076
4077        // Calculate 1-based localized day of week
4078
int dowLocal = dow - getFirstDayOfWeek() + 1;
4079        if (dowLocal < 1) {
4080            dowLocal += 7;
4081        }
4082        fields[DOW_LOCAL] = dowLocal;
4083    }
4084
4085    /**
4086     * Compute the Gregorian calendar year, month, and day of month from the
4087     * Julian day. These values are not stored in fields, but in member
4088     * variables gregorianXxx. They are used for time zone computations and by
4089     * subclasses that are Gregorian derivatives. Subclasses may call this
4090     * method to perform a Gregorian calendar millis->fields computation.
4091     * To perform a Gregorian calendar fields->millis computation, call
4092     * computeGregorianMonthStart().
4093     * @see #computeGregorianMonthStart
4094     * @stable ICU 2.0
4095     */

4096    protected final void computeGregorianFields(int julianDay) {
4097        int year, month, dayOfMonth, dayOfYear;
4098
4099        // The Gregorian epoch day is zero for Monday January 1, year 1.
4100
long gregorianEpochDay = julianDay - JAN_1_1_JULIAN_DAY;
4101
4102        // Here we convert from the day number to the multiple radix
4103
// representation. We use 400-year, 100-year, and 4-year cycles.
4104
// For example, the 4-year cycle has 4 years + 1 leap day; giving
4105
// 1461 == 365*4 + 1 days.
4106
int[] rem = new int[1];
4107        int n400 = floorDivide(gregorianEpochDay, 146097, rem); // 400-year cycle length
4108
int n100 = floorDivide(rem[0], 36524, rem); // 100-year cycle length
4109
int n4 = floorDivide(rem[0], 1461, rem); // 4-year cycle length
4110
int n1 = floorDivide(rem[0], 365, rem);
4111        year = 400*n400 + 100*n100 + 4*n4 + n1;
4112        dayOfYear = rem[0]; // zero-based day of year
4113
if (n100 == 4 || n1 == 4) {
4114            dayOfYear = 365; // Dec 31 at end of 4- or 400-yr cycle
4115
} else {
4116            ++year;
4117        }
4118
4119        boolean isLeap = ((year&0x3) == 0) && // equiv. to (year%4 == 0)
4120
(year%100 != 0 || year%400 == 0);
4121
4122        int correction = 0;
4123        int march1 = isLeap ? 60 : 59; // zero-based DOY for March 1
4124
if (dayOfYear >= march1) correction = isLeap ? 1 : 2;
4125        month = (12 * (dayOfYear + correction) + 6) / 367; // zero-based month
4126
dayOfMonth = dayOfYear -
4127            GREGORIAN_MONTH_COUNT[month][isLeap?3:2] + 1; // one-based DOM
4128

4129        gregorianYear = year;
4130        gregorianMonth = month; // 0-based already
4131
gregorianDayOfMonth = dayOfMonth; // 1-based already
4132
gregorianDayOfYear = dayOfYear + 1; // Convert from 0-based to 1-based
4133
}
4134
4135    /**
4136     * Compute the fields WEEK_OF_YEAR, YEAR_WOY, WEEK_OF_MONTH,
4137     * DAY_OF_WEEK_IN_MONTH, and DOW_LOCAL from EXTENDED_YEAR, YEAR,
4138     * DAY_OF_WEEK, and DAY_OF_YEAR. The latter fields are computed by the
4139     * subclass based on the calendar system.
4140     *
4141     * <p>The YEAR_WOY field is computed simplistically. It is equal to YEAR
4142     * most of the time, but at the year boundary it may be adjusted to YEAR-1
4143     * or YEAR+1 to reflect the overlap of a week into an adjacent year. In
4144     * this case, a simple increment or decrement is performed on YEAR, even
4145     * though this may yield an invalid YEAR value. For instance, if the YEAR
4146     * is part of a calendar system with an N-year cycle field CYCLE, then
4147     * incrementing the YEAR may involve incrementing CYCLE and setting YEAR
4148     * back to 0 or 1. This is not handled by this code, and in fact cannot be
4149     * simply handled without having subclasses define an entire parallel set of
4150     * fields for fields larger than or equal to a year. This additional
4151     * complexity is not warranted, since the intention of the YEAR_WOY field is
4152     * to support ISO 8601 notation, so it will typically be used with a
4153     * proleptic Gregorian calendar, which has no field larger than a year.
4154     */

4155    private final void computeWeekFields() {
4156        int eyear = fields[EXTENDED_YEAR];
4157        int year = fields[YEAR];
4158        int dayOfWeek = fields[DAY_OF_WEEK];
4159        int dayOfYear = fields[DAY_OF_YEAR];
4160
4161        // WEEK_OF_YEAR start
4162
// Compute the week of the year. For the Gregorian calendar, valid week
4163
// numbers run from 1 to 52 or 53, depending on the year, the first day
4164
// of the week, and the minimal days in the first week. For other
4165
// calendars, the valid range may be different -- it depends on the year
4166
// length. Days at the start of the year may fall into the last week of
4167
// the previous year; days at the end of the year may fall into the
4168
// first week of the next year. ASSUME that the year length is less than
4169
// 7000 days.
4170
int yearOfWeekOfYear = year;
4171        int relDow = (dayOfWeek + 7 - getFirstDayOfWeek()) % 7; // 0..6
4172
int relDowJan1 = (dayOfWeek - dayOfYear + 7001 - getFirstDayOfWeek()) % 7; // 0..6
4173
int woy = (dayOfYear - 1 + relDowJan1) / 7; // 0..53
4174
if ((7 - relDowJan1) >= getMinimalDaysInFirstWeek()) {
4175            ++woy;
4176        }
4177
4178        // Adjust for weeks at the year end that overlap into the previous or
4179
// next calendar year.
4180
if (woy == 0) {
4181            // We are the last week of the previous year.
4182
// Check to see if we are in the last week; if so, we need
4183
// to handle the case in which we are the first week of the
4184
// next year.
4185

4186            int prevDoy = dayOfYear + handleGetYearLength(eyear - 1);
4187            woy = weekNumber(prevDoy, dayOfWeek);
4188            yearOfWeekOfYear--;
4189        } else {
4190            int lastDoy = handleGetYearLength(eyear);
4191            // Fast check: For it to be week 1 of the next year, the DOY
4192
// must be on or after L-5, where L is yearLength(), then it
4193
// cannot possibly be week 1 of the next year:
4194
// L-5 L
4195
// doy: 359 360 361 362 363 364 365 001
4196
// dow: 1 2 3 4 5 6 7
4197
if (dayOfYear >= (lastDoy - 5)) {
4198                int lastRelDow = (relDow + lastDoy - dayOfYear) % 7;
4199                if (lastRelDow < 0) {
4200                    lastRelDow += 7;
4201                }
4202                if (((6 - lastRelDow) >= getMinimalDaysInFirstWeek()) &&
4203                    ((dayOfYear + 7 - relDow) > lastDoy)) {
4204                    woy = 1;
4205                    yearOfWeekOfYear++;
4206                }
4207            }
4208        }
4209        fields[WEEK_OF_YEAR] = woy;
4210        fields[YEAR_WOY] = yearOfWeekOfYear;
4211        // WEEK_OF_YEAR end
4212

4213        int dayOfMonth = fields[DAY_OF_MONTH];
4214        fields[WEEK_OF_MONTH] = weekNumber(dayOfMonth, dayOfWeek);
4215        fields[DAY_OF_WEEK_IN_MONTH] = (dayOfMonth-1) / 7 + 1;
4216    }
4217
4218    //----------------------------------------------------------------------
4219
// Fields -> Time
4220
//----------------------------------------------------------------------
4221

4222    /**
4223     * Value to OR against resolve table field values for remapping.
4224     * @see #resolveFields
4225     * @stable ICU 2.0
4226     */

4227    protected static final int RESOLVE_REMAP = 32;
4228    // A power of 2 greater than or equal to MAX_FIELD_COUNT
4229

4230    // Default table for day in year
4231
static final int[][][] DATE_PRECEDENCE = {
4232        {
4233            { DAY_OF_MONTH },
4234            { WEEK_OF_YEAR, DAY_OF_WEEK },
4235            { WEEK_OF_MONTH, DAY_OF_WEEK },
4236            { DAY_OF_WEEK_IN_MONTH, DAY_OF_WEEK },
4237            { WEEK_OF_YEAR, DOW_LOCAL },
4238            { WEEK_OF_MONTH, DOW_LOCAL },
4239            { DAY_OF_WEEK_IN_MONTH, DOW_LOCAL },
4240            { DAY_OF_YEAR },
4241        },
4242        {
4243            { WEEK_OF_YEAR },
4244            { WEEK_OF_MONTH },
4245            { DAY_OF_WEEK_IN_MONTH },
4246            { RESOLVE_REMAP | DAY_OF_WEEK_IN_MONTH, DAY_OF_WEEK },
4247            { RESOLVE_REMAP | DAY_OF_WEEK_IN_MONTH, DOW_LOCAL },
4248        },
4249    };
4250
4251    static final int[][][] DOW_PRECEDENCE = {
4252        {
4253            { DAY_OF_WEEK },
4254            { DOW_LOCAL },
4255        },
4256    };
4257
4258    /**
4259     * Given a precedence table, return the newest field combination in
4260     * the table, or -1 if none is found.
4261     *
4262     * <p>The precedence table is a 3-dimensional array of integers. It
4263     * may be thought of as an array of groups. Each group is an array of
4264     * lines. Each line is an array of field numbers. Within a line, if
4265     * all fields are set, then the time stamp of the line is taken to be
4266     * the stamp of the most recently set field. If any field of a line is
4267     * unset, then the line fails to match. Within a group, the line with
4268     * the newest time stamp is selected. The first field of the line is
4269     * returned to indicate which line matched.
4270     *
4271     * <p>In some cases, it may be desirable to map a line to field that
4272     * whose stamp is NOT examined. For example, if the best field is
4273     * DAY_OF_WEEK then the DAY_OF_WEEK_IN_MONTH algorithm may be used. In
4274     * order to do this, insert the value <code>REMAP_RESOLVE | F</code> at
4275     * the start of the line, where <code>F</code> is the desired return
4276     * field value. This field will NOT be examined; it only determines
4277     * the return value if the other fields in the line are the newest.
4278     *
4279     * <p>If all lines of a group contain at least one unset field, then no
4280     * line will match, and the group as a whole will fail to match. In
4281     * that case, the next group will be processed. If all groups fail to
4282     * match, then -1 is returned.
4283     * @stable ICU 2.0
4284     */

4285    protected int resolveFields(int[][][] precedenceTable) {
4286        int bestField = -1;
4287        for (int g=0; g<precedenceTable.length && bestField < 0; ++g) {
4288            int[][] group = precedenceTable[g];
4289            int bestStamp = UNSET;
4290        linesInGroup:
4291            for (int l=0; l<group.length; ++l) {
4292                int[] line= group[l];
4293                int lineStamp = UNSET;
4294                // Skip over first entry if it is negative
4295
for (int i=(line[0]>=RESOLVE_REMAP)?1:0; i<line.length; ++i) {
4296                    int s = stamp[line[i]];
4297                    // If any field is unset then don't use this line
4298
if (s == UNSET) {
4299                        continue linesInGroup;
4300                    } else {
4301                        lineStamp = Math.max(lineStamp, s);
4302                    }
4303                }
4304                // Record new maximum stamp & field no.
4305
if (lineStamp > bestStamp) {
4306                    bestStamp = lineStamp;
4307                    bestField = line[0]; // First field refers to entire line
4308
}
4309            }
4310        }
4311        return (bestField>=RESOLVE_REMAP)?(bestField&(RESOLVE_REMAP-1)):bestField;
4312    }
4313
4314    /**
4315     * Return the newest stamp of a given range of fields.
4316     * @stable ICU 2.0
4317     */

4318    protected int newestStamp(int first, int last, int bestStampSoFar) {
4319        int bestStamp = bestStampSoFar;
4320        for (int i=first; i<=last; ++i) {
4321            if (stamp[i] > bestStamp) {
4322                bestStamp = stamp[i];
4323            }
4324        }
4325        return bestStamp;
4326    }
4327
4328    /**
4329     * Return the timestamp of a field.
4330     * @stable ICU 2.0
4331     */

4332    protected final int getStamp(int field) {
4333        return stamp[field];
4334    }
4335
4336    /**
4337     * Return the field that is newer, either defaultField, or
4338     * alternateField. If neither is newer or neither is set, return defaultField.
4339     * @stable ICU 2.0
4340     */

4341    protected int newerField(int defaultField, int alternateField) {
4342        if (stamp[alternateField] > stamp[defaultField]) {
4343            return alternateField;
4344        }
4345        return defaultField;
4346    }
4347
4348    /**
4349     * Ensure that each field is within its valid range by calling {@link
4350     * #validateField(int)} on each field that has been set. This method
4351     * should only be called if this calendar is not lenient.
4352     * @see #isLenient
4353     * @see #validateField(int)
4354     * @stable ICU 2.0
4355     */

4356    protected void validateFields() {
4357        for (int field = 0; field < fields.length; field++) {
4358            if (isSet(field)) {
4359                validateField(field);
4360            }
4361        }
4362    }
4363
4364    /**
4365     * Validate a single field of this calendar. Subclasses should
4366     * override this method to validate any calendar-specific fields.
4367     * Generic fields can be handled by
4368     * <code>Calendar.validateField()</code>.
4369     * @see #validateField(int, int, int)
4370     * @stable ICU 2.0
4371     */

4372    protected void validateField(int field) {
4373        int y;
4374        switch (field) {
4375        case DAY_OF_MONTH:
4376            y = handleGetExtendedYear();
4377            validateField(field, 1, handleGetMonthLength(y, internalGet(MONTH)));
4378            break;
4379        case DAY_OF_YEAR:
4380            y = handleGetExtendedYear();
4381            validateField(field, 1, handleGetYearLength(y));
4382            break;
4383        case DAY_OF_WEEK_IN_MONTH:
4384            if (internalGet(field) == 0) {
4385                throw new IllegalArgumentException JavaDoc("DAY_OF_WEEK_IN_MONTH cannot be zero");
4386            }
4387            validateField(field, getMinimum(field), getMaximum(field));
4388            break;
4389        default:
4390            validateField(field, getMinimum(field), getMaximum(field));
4391            break;
4392        }
4393    }
4394
4395    /**
4396     * Validate a single field of this calendar given its minimum and
4397     * maximum allowed value. If the field is out of range, throw a
4398     * descriptive <code>IllegalArgumentException</code>. Subclasses may
4399     * use this method in their implementation of {@link
4400     * #validateField(int)}.
4401     * @stable ICU 2.0
4402     */

4403    protected final void validateField(int field, int min, int max) {
4404        int value = fields[field];
4405        if (value < min || value > max) {
4406            throw new IllegalArgumentException JavaDoc(fieldName(field) +
4407                                               '=' + value + ", valid range=" +
4408                                               min + ".." + max);
4409        }
4410    }
4411
4412    /**
4413     * Converts the current field values in <code>fields[]</code> to the
4414     * millisecond time value <code>time</code>.
4415     * @stable ICU 2.0
4416     */

4417   protected void computeTime() {
4418        if (!isLenient()) {
4419            validateFields();
4420        }
4421
4422        // Compute the Julian day
4423
int julianDay = computeJulianDay();
4424
4425        long millis = julianDayToMillis(julianDay);
4426
4427        int millisInDay;
4428
4429        // We only use MILLISECONDS_IN_DAY if it has been set by the user.
4430
// This makes it possible for the caller to set the calendar to a
4431
// time and call clear(MONTH) to reset the MONTH to January. This
4432
// is legacy behavior. Without this, clear(MONTH) has no effect,
4433
// since the internally set JULIAN_DAY is used.
4434
if (stamp[MILLISECONDS_IN_DAY] >= MINIMUM_USER_STAMP &&
4435            newestStamp(AM_PM, MILLISECOND, UNSET) <= stamp[MILLISECONDS_IN_DAY]) {
4436            millisInDay = internalGet(MILLISECONDS_IN_DAY);
4437        } else {
4438            millisInDay = computeMillisInDay();
4439        }
4440
4441        // Compute the time zone offset and DST offset. There are two potential
4442
// ambiguities here. We'll assume a 2:00 am (wall time) switchover time
4443
// for discussion purposes here.
4444
// 1. The transition into DST. Here, a designated time of 2:00 am - 2:59 am
4445
// can be in standard or in DST depending. However, 2:00 am is an invalid
4446
// representation (the representation jumps from 1:59:59 am Std to 3:00:00 am DST).
4447
// We assume standard time.
4448
// 2. The transition out of DST. Here, a designated time of 1:00 am - 1:59 am
4449
// can be in standard or DST. Both are valid representations (the rep
4450
// jumps from 1:59:59 DST to 1:00:00 Std).
4451
// Again, we assume standard time.
4452
// We use the TimeZone object, unless the user has explicitly set the ZONE_OFFSET
4453
// or DST_OFFSET fields; then we use those fields.
4454
if (stamp[ZONE_OFFSET] >= MINIMUM_USER_STAMP ||
4455            stamp[DST_OFFSET] >= MINIMUM_USER_STAMP) {
4456            millisInDay -= internalGet(ZONE_OFFSET) + internalGet(DST_OFFSET);
4457        } else {
4458            millisInDay -= computeZoneOffset(millis, millisInDay);
4459        }
4460
4461        time = millis + millisInDay;
4462    }
4463
4464    /**
4465     * Compute the milliseconds in the day from the fields. This is a
4466     * value from 0 to 23:59:59.999 inclusive, unless fields are out of
4467     * range, in which case it can be an arbitrary value. This value
4468     * reflects local zone wall time.
4469     * @stable ICU 2.0
4470     */

4471    protected int computeMillisInDay() {
4472        // Do the time portion of the conversion.
4473

4474        int millisInDay = 0;
4475
4476        // Find the best set of fields specifying the time of day. There
4477
// are only two possibilities here; the HOUR_OF_DAY or the
4478
// AM_PM and the HOUR.
4479
int hourOfDayStamp = stamp[HOUR_OF_DAY];
4480        int hourStamp = Math.max(stamp[HOUR], stamp[AM_PM]);
4481        int bestStamp = (hourStamp > hourOfDayStamp) ? hourStamp : hourOfDayStamp;
4482
4483        // Hours
4484
if (bestStamp != UNSET) {
4485            if (bestStamp == hourOfDayStamp) {
4486                // Don't normalize here; let overflow bump into the next period.
4487
// This is consistent with how we handle other fields.
4488
millisInDay += internalGet(HOUR_OF_DAY);
4489            } else {
4490                // Don't normalize here; let overflow bump into the next period.
4491
// This is consistent with how we handle other fields.
4492
millisInDay += internalGet(HOUR);
4493                millisInDay += 12 * internalGet(AM_PM); // Default works for unset AM_PM
4494
}
4495        }
4496
4497        // We use the fact that unset == 0; we start with millisInDay
4498
// == HOUR_OF_DAY.
4499
millisInDay *= 60;
4500        millisInDay += internalGet(MINUTE); // now have minutes
4501
millisInDay *= 60;
4502        millisInDay += internalGet(SECOND); // now have seconds
4503
millisInDay *= 1000;
4504        millisInDay += internalGet(MILLISECOND); // now have millis
4505

4506        return millisInDay;
4507    }
4508
4509    /**
4510     * This method can assume EXTENDED_YEAR has been set.
4511     * @param millis milliseconds of the date fields (local midnight millis)
4512     * @param millisInDay milliseconds of the time fields; may be out
4513     * or range.
4514     * @return total zone offset (raw + DST) for the given moment
4515     * @stable ICU 2.0
4516     */

4517    protected int computeZoneOffset(long millis, int millisInDay) {
4518        int offsets[] = new int[2];
4519        zone.getOffset(millis + millisInDay, true, offsets);
4520        return offsets[0] + offsets[1];
4521
4522        // Note: Because we pass in wall millisInDay, rather than
4523
// standard millisInDay, we interpret "1:00 am" on the day
4524
// of cessation of DST as "1:00 am Std" (assuming the time
4525
// of cessation is 2:00 am).
4526
}
4527
4528    /**
4529     * Compute the Julian day number as specified by this calendar's fields.
4530     * @stable ICU 2.0
4531     */

4532    protected int computeJulianDay() {
4533
4534        // We want to see if any of the date fields is newer than the
4535
// JULIAN_DAY. If not, then we use JULIAN_DAY. If so, then we do
4536
// the normal resolution. We only use JULIAN_DAY if it has been
4537
// set by the user. This makes it possible for the caller to set
4538
// the calendar to a time and call clear(MONTH) to reset the MONTH
4539
// to January. This is legacy behavior. Without this,
4540
// clear(MONTH) has no effect, since the internally set JULIAN_DAY
4541
// is used.
4542
if (stamp[JULIAN_DAY] >= MINIMUM_USER_STAMP) {
4543            int bestStamp = newestStamp(ERA, DAY_OF_WEEK_IN_MONTH, UNSET);
4544            bestStamp = newestStamp(YEAR_WOY, EXTENDED_YEAR, bestStamp);
4545            if (bestStamp <= stamp[JULIAN_DAY]) {
4546                return internalGet(JULIAN_DAY);
4547            }
4548        }
4549
4550        int bestField = resolveFields(getFieldResolutionTable());
4551        if (bestField < 0) {
4552            bestField = DAY_OF_MONTH;
4553        }
4554
4555        return handleComputeJulianDay(bestField);
4556    }
4557
4558    /**
4559     * Return the field resolution array for this calendar. Calendars that
4560     * define additional fields or change the semantics of existing fields
4561     * should override this method to adjust the field resolution semantics
4562     * accordingly. Other subclasses should not override this method.
4563     * @see #resolveFields
4564     * @stable ICU 2.0
4565     */

4566    protected int[][][] getFieldResolutionTable() {
4567        return DATE_PRECEDENCE;
4568    }
4569
4570    /**
4571     * Return the Julian day number of day before the first day of the
4572     * given month in the given extended year. Subclasses should override
4573     * this method to implement their calendar system.
4574     * @param eyear the extended year
4575     * @param month the zero-based month, or 0 if useMonth is false
4576     * @param useMonth if false, compute the day before the first day of
4577     * the given year, otherwise, compute the day before the first day of
4578     * the given month
4579     * @return the Julian day number of the day before the first
4580     * day of the given month and year
4581     * @stable ICU 2.0
4582     */

4583    abstract protected int handleComputeMonthStart(int eyear, int month,
4584                                                   boolean useMonth);
4585
4586    /**
4587     * Return the extended year defined by the current fields. This will
4588     * use the EXTENDED_YEAR field or the YEAR and supra-year fields (such
4589     * as ERA) specific to the calendar system, depending on which set of
4590     * fields is newer.
4591     * @return the extended year
4592     * @stable ICU 2.0
4593     */

4594    abstract protected int handleGetExtendedYear();
4595
4596    // (The following method is not called because all existing subclasses
4597
// override it. 2003-06-11 ICU 2.6 Alan)
4598
///CLOVER:OFF
4599
/**
4600     * Return the number of days in the given month of the given extended
4601     * year of this calendar system. Subclasses should override this
4602     * method if they can provide a more correct or more efficient
4603     * implementation than the default implementation in Calendar.
4604     * @stable ICU 2.0
4605     */

4606    protected int handleGetMonthLength(int extendedYear, int month) {
4607        return handleComputeMonthStart(extendedYear, month+1, true) -
4608               handleComputeMonthStart(extendedYear, month, true);
4609    }
4610    ///CLOVER:ON
4611

4612    /**
4613     * Return the number of days in the given extended year of this
4614     * calendar system. Subclasses should override this method if they can
4615     * provide a more correct or more efficient implementation than the
4616     * default implementation in Calendar.
4617     * @stable ICU 2.0
4618     */

4619    protected int handleGetYearLength(int eyear) {
4620        return handleComputeMonthStart(eyear+1, 0, false) -
4621               handleComputeMonthStart(eyear, 0, false);
4622    }
4623
4624    /**
4625     * Subclasses that use additional fields beyond those defined in
4626     * <code>Calendar</code> should override this method to return an
4627     * <code>int[]</code> array of the appropriate length. The length
4628     * must be at least <code>BASE_FIELD_COUNT</code> and no more than
4629     * <code>MAX_FIELD_COUNT</code>.
4630     * @stable ICU 2.0
4631     */

4632    protected int[] handleCreateFields() {
4633        return new int[BASE_FIELD_COUNT];
4634    }
4635    
4636    /**
4637     * Subclasses may override this.
4638     * Called by handleComputeJulianDay. Returns the default month (0-based) for the year,
4639     * taking year and era into account. Defaults to 0 (JANUARY) for Gregorian.
4640     * @param extendedYear the extendedYear, as returned by handleGetExtendedYear
4641     * @return the default month
4642     * @provisional ICU 3.6
4643     * @draft ICU 3.6
4644     * @see #MONTH
4645     */

4646    protected int getDefaultMonthInYear(int extendedYear) {
4647        return Calendar.JANUARY;
4648    }
4649
4650    /**
4651     * Subclasses may override this.
4652     * Called by handleComputeJulianDay. Returns the default day (1-based) for the month,
4653     * taking currently-set year and era into account. Defaults to 1 for Gregorian.
4654     * @param extendedYear the extendedYear, as returned by handleGetExtendedYear
4655     * @param month the month, as returned by getDefaultMonthInYear
4656     * @return the default day of the month
4657     * @draft ICU 3.6
4658     * @provisional ICU 3.6
4659     * @see #DAY_OF_MONTH
4660     */

4661    protected int getDefaultDayInMonth(int extendedYear, int month) {
4662        return 1;
4663    }
4664
4665
4666    /**
4667     * Subclasses may override this. This method calls
4668     * handleGetMonthLength() to obtain the calendar-specific month
4669     * length.
4670     * @stable ICU 2.0
4671     */

4672    protected int handleComputeJulianDay(int bestField) {
4673
4674        boolean useMonth = (bestField == DAY_OF_MONTH ||
4675                            bestField == WEEK_OF_MONTH ||
4676                            bestField == DAY_OF_WEEK_IN_MONTH);
4677
4678        int year = handleGetExtendedYear();
4679        internalSet(EXTENDED_YEAR, year);
4680
4681        int month = useMonth ? internalGet(MONTH, getDefaultMonthInYear(year)) : 0;
4682        
4683        int dom = internalGet(DAY_OF_MONTH, getDefaultDayInMonth(year, month));
4684        
4685        // Get the Julian day of the day BEFORE the start of this year.
4686
// If useMonth is true, get the day before the start of the month.
4687
int julianDay = handleComputeMonthStart(year, month, useMonth);
4688
4689        if (bestField == DAY_OF_MONTH) {
4690            if(isSet(DAY_OF_MONTH)) {
4691                return julianDay + internalGet(DAY_OF_MONTH, getDefaultDayInMonth(year, month));
4692            } else {
4693                return julianDay + getDefaultDayInMonth(year, month);
4694            }
4695        }
4696
4697        if (bestField == DAY_OF_YEAR) {
4698            return julianDay + internalGet(DAY_OF_YEAR);
4699        }
4700
4701        int firstDayOfWeek = getFirstDayOfWeek(); // Localized fdw
4702

4703        // At this point julianDay is the 0-based day BEFORE the first day of
4704
// January 1, year 1 of the given calendar. If julianDay == 0, it
4705
// specifies (Jan. 1, 1) - 1, in whatever calendar we are using (Julian
4706
// or Gregorian).
4707

4708        // At this point we need to process the WEEK_OF_MONTH or
4709
// WEEK_OF_YEAR, which are similar, or the DAY_OF_WEEK_IN_MONTH.
4710
// First, perform initial shared computations. These locate the
4711
// first week of the period.
4712

4713        // Get the 0-based localized DOW of day one of the month or year.
4714
// Valid range 0..6.
4715
int first = julianDayToDayOfWeek(julianDay + 1) - firstDayOfWeek;
4716        if (first < 0) {
4717            first += 7;
4718        }
4719
4720        // Get zero-based localized DOW, valid range 0..6. This is the DOW
4721
// we are looking for.
4722
int dowLocal = 0;
4723        switch (resolveFields(DOW_PRECEDENCE)) {
4724        case DAY_OF_WEEK:
4725            dowLocal = internalGet(DAY_OF_WEEK) - firstDayOfWeek;
4726            break;
4727        case DOW_LOCAL:
4728            dowLocal = internalGet(DOW_LOCAL) - 1;
4729            break;
4730        }
4731        dowLocal = dowLocal % 7;
4732        if (dowLocal < 0) {
4733            dowLocal += 7;
4734        }
4735
4736        // Find the first target DOW (dowLocal) in the month or year.
4737
// Actually, it may be just before the first of the month or year.
4738
// It will be an integer from -5..7.
4739
int date = 1 - first + dowLocal;
4740
4741        if (bestField == DAY_OF_WEEK_IN_MONTH) {
4742
4743            // Adjust the target DOW to be in the month or year.
4744
if (date < 1) {
4745                date += 7;
4746            }
4747
4748            // The only trickiness occurs if the day-of-week-in-month is
4749
// negative.
4750
int dim = internalGet(DAY_OF_WEEK_IN_MONTH, 1);
4751            if (dim >= 0) {
4752                date += 7*(dim - 1);
4753
4754            } else {
4755                // Move date to the last of this day-of-week in this month,
4756
// then back up as needed. If dim==-1, we don't back up at
4757
// all. If dim==-2, we back up once, etc. Don't back up
4758
// past the first of the given day-of-week in this month.
4759
// Note that we handle -2, -3, etc. correctly, even though
4760
// values < -1 are technically disallowed.
4761
int m = internalGet(MONTH, JANUARY);
4762                int monthLength = handleGetMonthLength(year, m);
4763                date += ((monthLength - date) / 7 + dim + 1) * 7;
4764            }
4765        } else {
4766            // assert(bestField == WEEK_OF_MONTH || bestField == WEEK_OF_YEAR)
4767

4768            // Adjust for minimal days in first week
4769
if ((7 - first) < getMinimalDaysInFirstWeek()) {
4770                date += 7;
4771            }
4772
4773            // Now adjust for the week number.
4774
date += 7 * (internalGet(bestField) - 1);
4775        }
4776
4777        return julianDay + date;
4778    }
4779
4780    /**
4781     * Compute the Julian day of a month of the Gregorian calendar.
4782     * Subclasses may call this method to perform a Gregorian calendar
4783     * fields->millis computation. To perform a Gregorian calendar
4784     * millis->fields computation, call computeGregorianFields().
4785     * @param year extended Gregorian year
4786     * @param month zero-based Gregorian month
4787     * @return the Julian day number of the day before the first
4788     * day of the given month in the given extended year
4789     * @see #computeGregorianFields
4790     * @stable ICU 2.0
4791     */

4792    protected int computeGregorianMonthStart(int year, int month) {
4793
4794        // If the month is out of range, adjust it into range, and
4795
// modify the extended year value accordingly.
4796
if (month < 0 || month > 11) {
4797            int[] rem = new int[1];
4798            year += floorDivide(month, 12, rem);
4799            month = rem[0];
4800        }
4801
4802        boolean isLeap = (year%4 == 0) && ((year%100 != 0) || (year%400 == 0));
4803        int y = year - 1;
4804        // This computation is actually ... + (JAN_1_1_JULIAN_DAY - 3) + 2.
4805
// Add 2 because Gregorian calendar starts 2 days after Julian
4806
// calendar.
4807
int julianDay = 365*y + floorDivide(y, 4) - floorDivide(y, 100) +
4808            floorDivide(y, 400) + JAN_1_1_JULIAN_DAY - 1;
4809
4810        // At this point julianDay indicates the day BEFORE the first day
4811
// of January 1, <eyear> of the Gregorian calendar.
4812
if (month != 0) {
4813            julianDay += GREGORIAN_MONTH_COUNT[month][isLeap?3:2];
4814        }
4815
4816        return julianDay;
4817    }
4818
4819    //----------------------------------------------------------------------
4820
// Subclass API
4821
// For subclasses to override
4822
//----------------------------------------------------------------------
4823

4824    // (The following method is not called because all existing subclasses
4825
// override it. 2003-06-11 ICU 2.6 Alan)
4826
///CLOVER:OFF
4827
/**
4828     * Subclasses may override this method to compute several fields
4829     * specific to each calendar system. These are:
4830     *
4831     * <ul><li>ERA
4832     * <li>YEAR
4833     * <li>MONTH
4834     * <li>DAY_OF_MONTH
4835     * <li>DAY_OF_YEAR
4836     * <li>EXTENDED_YEAR</ul>
4837     *
4838     * Subclasses can refer to the DAY_OF_WEEK and DOW_LOCAL fields, which
4839     * will be set when this method is called. Subclasses can also call
4840     * the getGregorianXxx() methods to obtain Gregorian calendar
4841     * equivalents for the given Julian day.
4842     *
4843     * <p>In addition, subclasses should compute any subclass-specific
4844     * fields, that is, fields from BASE_FIELD_COUNT to
4845     * getFieldCount() - 1.
4846     *
4847     * <p>The default implementation in <code>Calendar</code> implements
4848     * a pure proleptic Gregorian calendar.
4849     * @stable ICU 2.0
4850     */

4851    protected void handleComputeFields(int julianDay) {
4852        internalSet(MONTH, getGregorianMonth());
4853        internalSet(DAY_OF_MONTH, getGregorianDayOfMonth());
4854        internalSet(DAY_OF_YEAR, getGregorianDayOfYear());
4855        int eyear = getGregorianYear();
4856        internalSet(EXTENDED_YEAR, eyear);
4857        int era = GregorianCalendar.AD;
4858        if (eyear < 1) {
4859            era = GregorianCalendar.BC;
4860            eyear = 1 - eyear;
4861        }
4862        internalSet(ERA, era);
4863        internalSet(YEAR, eyear);
4864    }
4865    ///CLOVER:ON
4866

4867    //----------------------------------------------------------------------
4868
// Subclass API
4869
// For subclasses to call
4870
//----------------------------------------------------------------------
4871

4872    /**
4873     * Return the extended year on the Gregorian calendar as computed by
4874     * <code>computeGregorianFields()</code>.
4875     * @see #computeGregorianFields
4876     * @stable ICU 2.0
4877     */

4878    protected final int getGregorianYear() {
4879        return gregorianYear;
4880    }
4881
4882    /**
4883     * Return the month (0-based) on the Gregorian calendar as computed by
4884     * <code>computeGregorianFields()</code>.
4885     * @see #computeGregorianFields
4886     * @stable ICU 2.0
4887     */

4888    protected final int getGregorianMonth() {
4889        return gregorianMonth;
4890    }
4891
4892    /**
4893     * Return the day of year (1-based) on the Gregorian calendar as
4894     * computed by <code>computeGregorianFields()</code>.
4895     * @see #computeGregorianFields
4896     * @stable ICU 2.0
4897     */

4898    protected final int getGregorianDayOfYear() {
4899        return gregorianDayOfYear;
4900    }
4901
4902    /**
4903     * Return the day of month (1-based) on the Gregorian calendar as
4904     * computed by <code>computeGregorianFields()</code>.
4905     * @see #computeGregorianFields
4906     * @stable ICU 2.0
4907     */

4908    protected final int getGregorianDayOfMonth() {
4909        return gregorianDayOfMonth;
4910    }
4911
4912    /**
4913     * Return the number of fields defined by this calendar. Valid field
4914     * arguments to <code>set()</code> and <code>get()</code> are
4915     * <code>0..getFieldCount()-1</code>.
4916     * @stable ICU 2.0
4917     */

4918    public final int getFieldCount() {
4919        return fields.length;
4920    }
4921
4922    /**
4923     * Set a field to a value. Subclasses should use this method when
4924     * computing fields. It sets the time stamp in the
4925     * <code>stamp[]</code> array to <code>INTERNALLY_SET</code>. If a
4926     * field that may not be set by subclasses is passed in, an
4927     * <code>IllegalArgumentException</code> is thrown. This prevents
4928     * subclasses from modifying fields that are intended to be
4929     * calendar-system invariant.
4930     * @stable ICU 2.0
4931     */

4932    protected final void internalSet(int field, int value) {
4933        if (((1 << field) & internalSetMask) == 0) {
4934            throw new IllegalStateException JavaDoc("Subclass cannot set " +
4935                                            fieldName(field));
4936        }
4937        fields[field] = value;
4938        stamp[field] = INTERNALLY_SET;
4939    }
4940
4941    private static final int[][] GREGORIAN_MONTH_COUNT = {
4942        //len len2 st st2
4943
{ 31, 31, 0, 0 }, // Jan
4944
{ 28, 29, 31, 31 }, // Feb
4945
{ 31, 31, 59, 60 }, // Mar
4946
{ 30, 30, 90, 91 }, // Apr
4947
{ 31, 31, 120, 121 }, // May
4948
{ 30, 30, 151, 152 }, // Jun
4949
{ 31, 31, 181, 182 }, // Jul
4950
{ 31, 31, 212, 213 }, // Aug
4951
{ 30, 30, 243, 244 }, // Sep
4952
{ 31, 31, 273, 274 }, // Oct
4953
{ 30, 30, 304, 305 }, // Nov
4954
{ 31, 31, 334, 335 } // Dec
4955
// len length of month
4956
// len2 length of month in a leap year
4957
// st days in year before start of month
4958
// st2 days in year before month in leap year
4959
};
4960
4961    /**
4962     * Determines if the given year is a leap year. Returns true if the
4963     * given year is a leap year.
4964     * @param year the given year.
4965     * @return true if the given year is a leap year; false otherwise.
4966     * @stable ICU 2.0
4967     */

4968    protected static final boolean isGregorianLeapYear(int year) {
4969        return (year%4 == 0) && ((year%100 != 0) || (year%400 == 0));
4970    }
4971
4972    /**
4973     * Return the length of a month of the Gregorian calendar.
4974     * @param y the extended year
4975     * @param m the 0-based month number
4976     * @return the number of days in the given month
4977     * @stable ICU 2.0
4978     */

4979    protected static final int gregorianMonthLength(int y, int m) {
4980        return GREGORIAN_MONTH_COUNT[m][isGregorianLeapYear(y)?1:0];
4981    }
4982
4983    /**
4984     * Return the length of a previous month of the Gregorian calendar.
4985     * @param y the extended year
4986     * @param m the 0-based month number
4987     * @return the number of days in the month previous to the given month
4988     * @stable ICU 2.0
4989     */

4990    protected static final int gregorianPreviousMonthLength(int y, int m) {
4991        return (m > 0) ? gregorianMonthLength(y, m-1) : 31;
4992    }
4993
4994    /**
4995     * Divide two long integers, returning the floor of the quotient.
4996     * <p>
4997     * Unlike the built-in division, this is mathematically well-behaved.
4998     * E.g., <code>-1/4</code> => 0
4999     * but <code>floorDivide(-1,4)</code> => -1.
5000     * @param numerator the numerator
5001     * @param denominator a divisor which must be > 0
5002     * @return the floor of the quotient.
5003     * @stable ICU 2.0
5004     */

5005    protected static final long floorDivide(long numerator, long denominator) {
5006        // We do this computation in order to handle
5007
// a numerator of Long.MIN_VALUE correctly
5008
return (numerator >= 0) ?
5009            numerator / denominator :
5010            ((numerator + 1) / denominator) - 1;
5011    }
5012
5013    /**
5014     * Divide two integers, returning the floor of the quotient.
5015     * <p>
5016     * Unlike the built-in division, this is mathematically well-behaved.
5017     * E.g., <code>-1/4</code> => 0
5018     * but <code>floorDivide(-1,4)</code> => -1.
5019     * @param numerator the numerator
5020     * @param denominator a divisor which must be > 0
5021     * @return the floor of the quotient.
5022     * @stable ICU 2.0
5023     */

5024    protected static final int floorDivide(int numerator, int denominator) {
5025        // We do this computation in order to handle
5026
// a numerator of Integer.MIN_VALUE correctly
5027
return (numerator >= 0) ?
5028            numerator / denominator :
5029            ((numerator + 1) / denominator) - 1;
5030    }
5031
5032    /**
5033     * Divide two integers, returning the floor of the quotient, and
5034     * the modulus remainder.
5035     * <p>
5036     * Unlike the built-in division, this is mathematically well-behaved.
5037     * E.g., <code>-1/4</code> => 0 and <code>-1%4</code> => -1,
5038     * but <code>floorDivide(-1,4)</code> => -1 with <code>remainder[0]</code> => 3.
5039     * @param numerator the numerator
5040     * @param denominator a divisor which must be > 0
5041     * @param remainder an array of at least one element in which the value
5042     * <code>numerator mod denominator</code> is returned. Unlike <code>numerator
5043     * % denominator</code>, this will always be non-negative.
5044     * @return the floor of the quotient.
5045     * @stable ICU 2.0
5046     */

5047    protected static final int floorDivide(int numerator, int denominator, int[] remainder) {
5048        if (numerator >= 0) {
5049            remainder[0] = numerator % denominator;
5050            return numerator / denominator;
5051        }
5052    int quotient = ((numerator + 1) / denominator) - 1;
5053        remainder[0] = numerator - (quotient * denominator);
5054        return quotient;
5055    }
5056
5057    /**
5058     * Divide two integers, returning the floor of the quotient, and
5059     * the modulus remainder.
5060     * <p>
5061     * Unlike the built-in division, this is mathematically well-behaved.
5062     * E.g., <code>-1/4</code> => 0 and <code>-1%4</code> => -1,
5063     * but <code>floorDivide(-1,4)</code> => -1 with <code>remainder[0]</code> => 3.
5064     * @param numerator the numerator
5065     * @param denominator a divisor which must be > 0
5066     * @param remainder an array of at least one element in which the value
5067     * <code>numerator mod denominator</code> is returned. Unlike <code>numerator
5068     * % denominator</code>, this will always be non-negative.
5069     * @return the floor of the quotient.
5070     * @stable ICU 2.0
5071     */

5072    protected static final int floorDivide(long numerator, int denominator, int[] remainder) {
5073        if (numerator >= 0) {
5074            remainder[0] = (int)(numerator % denominator);
5075            return (int)(numerator / denominator);
5076        }
5077        int quotient = (int)(((numerator + 1) / denominator) - 1);
5078        remainder[0] = (int)(numerator - (quotient * denominator));
5079        return quotient;
5080    }
5081
5082    private static final String JavaDoc[] FIELD_NAME = {
5083        "ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH",
5084        "DAY_OF_MONTH", "DAY_OF_YEAR", "DAY_OF_WEEK",
5085        "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR", "HOUR_OF_DAY",
5086        "MINUTE", "SECOND", "MILLISECOND", "ZONE_OFFSET",
5087        "DST_OFFSET", "YEAR_WOY", "DOW_LOCAL", "EXTENDED_YEAR",
5088        "JULIAN_DAY", "MILLISECONDS_IN_DAY",
5089    };
5090
5091    /**
5092     * Return a string name for a field, for debugging and exceptions.
5093     * @stable ICU 2.0
5094     */

5095    protected String JavaDoc fieldName(int field) {
5096        try {
5097            return FIELD_NAME[field];
5098        } catch (ArrayIndexOutOfBoundsException JavaDoc e) {
5099            return "Field " + field;
5100        }
5101    }
5102
5103    /**
5104     * Converts time as milliseconds to Julian day.
5105     * @param millis the given milliseconds.
5106     * @return the Julian day number.
5107     * @stable ICU 2.0
5108     */

5109    protected static final int millisToJulianDay(long millis) {
5110        return (int) (EPOCH_JULIAN_DAY + floorDivide(millis, ONE_DAY));
5111    }
5112
5113    /**
5114     * Converts Julian day to time as milliseconds.
5115     * @param julian the given Julian day number.
5116     * @return time as milliseconds.
5117     * @stable ICU 2.0
5118     */

5119    protected static final long julianDayToMillis(int julian) {
5120        return (julian - EPOCH_JULIAN_DAY) * ONE_DAY;
5121    }
5122
5123    /**
5124     * Return the day of week, from SUNDAY to SATURDAY, given a Julian day.
5125     * @stable ICU 2.0
5126     */

5127    protected static final int julianDayToDayOfWeek(int julian) {
5128        // If julian is negative, then julian%7 will be negative, so we adjust
5129
// accordingly. Julian day 0 is Monday.
5130
int dayOfWeek = (julian + MONDAY) % 7;
5131        if (dayOfWeek < SUNDAY) {
5132            dayOfWeek += 7;
5133        }
5134        return dayOfWeek;
5135    }
5136
5137    /**
5138     * Return the current milliseconds without recomputing.
5139     * @stable ICU 2.0
5140     */

5141    protected final long internalGetTimeInMillis() {
5142        return time;
5143    }
5144    
5145    /**
5146     * Return the current Calendar type.
5147     * Note, in 3.0 this function will return 'gregorian' in Calendar to emulate legacy behavior
5148     * @return type of calendar (gregorian, etc)
5149     * @internal ICU 3.0
5150     * @deprecated This API is ICU internal only.
5151     */

5152    public String JavaDoc getType() {
5153        return "gregorian";
5154    }
5155    
5156    // -------- BEGIN ULocale boilerplate --------
5157

5158    /**
5159     * Return the locale that was used to create this object, or null.
5160     * This may may differ from the locale requested at the time of
5161     * this object's creation. For example, if an object is created
5162     * for locale <tt>en_US_CALIFORNIA</tt>, the actual data may be
5163     * drawn from <tt>en</tt> (the <i>actual</i> locale), and
5164     * <tt>en_US</tt> may be the most specific locale that exists (the
5165     * <i>valid</i> locale).
5166     *
5167     * <p>Note: This method will be implemented in ICU 3.0; ICU 2.8
5168     * contains a partial preview implementation. The * <i>actual</i>
5169     * locale is returned correctly, but the <i>valid</i> locale is
5170     * not, in most cases.
5171     * @param type type of information requested, either {@link
5172     * com.ibm.icu.util.ULocale#VALID_LOCALE} or {@link
5173     * com.ibm.icu.util.ULocale#ACTUAL_LOCALE}.
5174     * @return the information specified by <i>type</i>, or null if
5175     * this object was not constructed from locale data.
5176     * @see com.ibm.icu.util.ULocale
5177     * @see com.ibm.icu.util.ULocale#VALID_LOCALE
5178     * @see com.ibm.icu.util.ULocale#ACTUAL_LOCALE
5179     * @draft ICU 2.8 (retain)
5180     * @provisional This API might change or be removed in a future release.
5181     */

5182    public final ULocale getLocale(ULocale.Type type) {
5183        return type == ULocale.ACTUAL_LOCALE ?
5184            this.actualLocale : this.validLocale;
5185    }
5186
5187    /**
5188     * Set information about the locales that were used to create this
5189     * object. If the object was not constructed from locale data,
5190     * both arguments should be set to null. Otherwise, neither
5191     * should be null. The actual locale must be at the same level or
5192     * less specific than the valid locale. This method is intended
5193     * for use by factories or other entities that create objects of
5194     * this class.
5195     * @param valid the most specific locale containing any resource
5196     * data, or null
5197     * @param actual the locale containing data used to construct this
5198     * object, or null
5199     * @see com.ibm.icu.util.ULocale
5200     * @see com.ibm.icu.util.ULocale#VALID_LOCALE
5201     * @see com.ibm.icu.util.ULocale#ACTUAL_LOCALE
5202     * @internal
5203     */

5204    final void setLocale(ULocale valid, ULocale actual) {
5205        // Change the following to an assertion later
5206
if ((valid == null) != (actual == null)) {
5207            ///CLOVER:OFF
5208
throw new IllegalArgumentException JavaDoc();
5209            ///CLOVER:ON
5210
}
5211        // Another check we could do is that the actual locale is at
5212
// the same level or less specific than the valid locale.
5213
this.validLocale = valid;
5214        this.actualLocale = actual;
5215    }
5216
5217    /**
5218     * The most specific locale containing any resource data, or null.
5219     * @see com.ibm.icu.util.ULocale
5220     * @internal
5221     */

5222    private ULocale validLocale;
5223
5224    /**
5225     * The locale containing data used to construct this object, or
5226     * null.
5227     * @see com.ibm.icu.util.ULocale
5228     * @internal
5229     */

5230    private ULocale actualLocale;
5231
5232    // -------- END ULocale boilerplate --------
5233
}
5234
5235
Popular Tags