1/* GENERATED SOURCE. DO NOT MODIFY. */
2// © 2016 and later: Unicode, Inc. and others.
3// License & terms of use: http://www.unicode.org/copyright.html#License
4/*
5 * Copyright (C) 1996-2016, International Business Machines
6 * Corporation and others.  All Rights Reserved.
7 */
8
9package android.icu.util;
10
11import java.util.Date;
12import java.util.Locale;
13
14import android.icu.util.ULocale.Category;
15
16/**
17 * <strong>[icu enhancement]</strong> ICU's replacement for {@link java.util.GregorianCalendar}.&nbsp;Methods, fields, and other functionality specific to ICU are labeled '<strong>[icu]</strong>'.
18 *
19 * <p><code>GregorianCalendar</code> is a concrete subclass of
20 * {@link Calendar}
21 * and provides the standard calendar used by most of the world.
22 *
23 * <p>The standard (Gregorian) calendar has 2 eras, BC and AD.
24 *
25 * <p>This implementation handles a single discontinuity, which corresponds by
26 * default to the date the Gregorian calendar was instituted (October 15, 1582
27 * in some countries, later in others).  The cutover date may be changed by the
28 * caller by calling <code>setGregorianChange()</code>.
29 *
30 * <p>Historically, in those countries which adopted the Gregorian calendar first,
31 * October 4, 1582 was thus followed by October 15, 1582. This calendar models
32 * this correctly.  Before the Gregorian cutover, <code>GregorianCalendar</code>
33 * implements the Julian calendar.  The only difference between the Gregorian
34 * and the Julian calendar is the leap year rule. The Julian calendar specifies
35 * leap years every four years, whereas the Gregorian calendar omits century
36 * years which are not divisible by 400.
37 *
38 * <p><code>GregorianCalendar</code> implements <em>proleptic</em> Gregorian and
39 * Julian calendars. That is, dates are computed by extrapolating the current
40 * rules indefinitely far backward and forward in time. As a result,
41 * <code>GregorianCalendar</code> may be used for all years to generate
42 * meaningful and consistent results. However, dates obtained using
43 * <code>GregorianCalendar</code> are historically accurate only from March 1, 4
44 * AD onward, when modern Julian calendar rules were adopted.  Before this date,
45 * leap year rules were applied irregularly, and before 45 BC the Julian
46 * calendar did not even exist.
47 *
48 * <p>Prior to the institution of the Gregorian calendar, New Year's Day was
49 * March 25. To avoid confusion, this calendar always uses January 1. A manual
50 * adjustment may be made if desired for dates that are prior to the Gregorian
51 * changeover and which fall between January 1 and March 24.
52 *
53 * <p>Values calculated for the <code>WEEK_OF_YEAR</code> field range from 1 to
54 * 53.  Week 1 for a year is the earliest seven day period starting on
55 * <code>getFirstDayOfWeek()</code> that contains at least
56 * <code>getMinimalDaysInFirstWeek()</code> days from that year.  It thus
57 * depends on the values of <code>getMinimalDaysInFirstWeek()</code>,
58 * <code>getFirstDayOfWeek()</code>, and the day of the week of January 1.
59 * Weeks between week 1 of one year and week 1 of the following year are
60 * numbered sequentially from 2 to 52 or 53 (as needed).
61
62 * <p>For example, January 1, 1998 was a Thursday.  If
63 * <code>getFirstDayOfWeek()</code> is <code>MONDAY</code> and
64 * <code>getMinimalDaysInFirstWeek()</code> is 4 (these are the values
65 * reflecting ISO 8601 and many national standards), then week 1 of 1998 starts
66 * on December 29, 1997, and ends on January 4, 1998.  If, however,
67 * <code>getFirstDayOfWeek()</code> is <code>SUNDAY</code>, then week 1 of 1998
68 * starts on January 4, 1998, and ends on January 10, 1998; the first three days
69 * of 1998 then are part of week 53 of 1997.
70 *
71 * <p>Values calculated for the <code>WEEK_OF_MONTH</code> field range from 0 or
72 * 1 to 4 or 5.  Week 1 of a month (the days with <code>WEEK_OF_MONTH =
73 * 1</code>) is the earliest set of at least
74 * <code>getMinimalDaysInFirstWeek()</code> contiguous days in that month,
75 * ending on the day before <code>getFirstDayOfWeek()</code>.  Unlike
76 * week 1 of a year, week 1 of a month may be shorter than 7 days, need
77 * not start on <code>getFirstDayOfWeek()</code>, and will not include days of
78 * the previous month.  Days of a month before week 1 have a
79 * <code>WEEK_OF_MONTH</code> of 0.
80 *
81 * <p>For example, if <code>getFirstDayOfWeek()</code> is <code>SUNDAY</code>
82 * and <code>getMinimalDaysInFirstWeek()</code> is 4, then the first week of
83 * January 1998 is Sunday, January 4 through Saturday, January 10.  These days
84 * have a <code>WEEK_OF_MONTH</code> of 1.  Thursday, January 1 through
85 * Saturday, January 3 have a <code>WEEK_OF_MONTH</code> of 0.  If
86 * <code>getMinimalDaysInFirstWeek()</code> is changed to 3, then January 1
87 * through January 3 have a <code>WEEK_OF_MONTH</code> of 1.
88 *
89 * <p>
90 * <strong>Example:</strong>
91 * <blockquote>
92 * <pre>
93 * // get the supported ids for GMT-08:00 (Pacific Standard Time)
94 * String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
95 * // if no ids were returned, something is wrong. get out.
96 * if (ids.length == 0)
97 *     System.exit(0);
98 *
99 *  // begin output
100 * System.out.println("Current Time");
101 *
102 * // create a Pacific Standard Time time zone
103 * SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
104 *
105 * // set up rules for daylight savings time
106 * pdt.setStartRule(Calendar.MARCH, 2, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
107 * pdt.setEndRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
108 *
109 * // create a GregorianCalendar with the Pacific Daylight time zone
110 * // and the current date and time
111 * Calendar calendar = new GregorianCalendar(pdt);
112 * Date trialTime = new Date();
113 * calendar.setTime(trialTime);
114 *
115 * // print out a bunch of interesting things
116 * System.out.println("ERA: " + calendar.get(Calendar.ERA));
117 * System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
118 * System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
119 * System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR));
120 * System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH));
121 * System.out.println("DATE: " + calendar.get(Calendar.DATE));
122 * System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
123 * System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR));
124 * System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));
125 * System.out.println("DAY_OF_WEEK_IN_MONTH: "
126 *                    + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
127 * System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
128 * System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
129 * System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
130 * System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
131 * System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
132 * System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
133 * System.out.println("ZONE_OFFSET: "
134 *                    + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000)));
135 * System.out.println("DST_OFFSET: "
136 *                    + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000)));
137
138 * System.out.println("Current Time, with hour reset to 3");
139 * calendar.clear(Calendar.HOUR_OF_DAY); // so doesn't override
140 * calendar.set(Calendar.HOUR, 3);
141 * System.out.println("ERA: " + calendar.get(Calendar.ERA));
142 * System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
143 * System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
144 * System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR));
145 * System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH));
146 * System.out.println("DATE: " + calendar.get(Calendar.DATE));
147 * System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
148 * System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR));
149 * System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));
150 * System.out.println("DAY_OF_WEEK_IN_MONTH: "
151 *                    + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
152 * System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
153 * System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
154 * System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
155 * System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
156 * System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
157 * System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
158 * System.out.println("ZONE_OFFSET: "
159 *        + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000))); // in hours
160 * System.out.println("DST_OFFSET: "
161 *        + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000))); // in hours</pre>
162 * </blockquote>
163 * <p>
164 * GregorianCalendar usually should be instantiated using
165 * {@link android.icu.util.Calendar#getInstance(ULocale)} passing in a <code>ULocale</code>
166 * with the tag <code>"@calendar=gregorian"</code>.</p>
167
168 * @see          Calendar
169 * @see          TimeZone
170 * @author Deborah Goldsmith, Mark Davis, Chen-Lieh Huang, Alan Liu
171 */
172public class GregorianCalendar extends Calendar {
173    // jdk1.4.2 serialver
174    private static final long serialVersionUID = 9199388694351062137L;
175
176    /*
177     * Implementation Notes
178     *
179     * The Julian day number, as used here, is a modified number which has its
180     * onset at midnight, rather than noon.
181     *
182     * The epoch is the number of days or milliseconds from some defined
183     * starting point. The epoch for java.util.Date is used here; that is,
184     * milliseconds from January 1, 1970 (Gregorian), midnight UTC.  Other
185     * epochs which are used are January 1, year 1 (Gregorian), which is day 1
186     * of the Gregorian calendar, and December 30, year 0 (Gregorian), which is
187     * day 1 of the Julian calendar.
188     *
189     * We implement the proleptic Julian and Gregorian calendars.  This means we
190     * implement the modern definition of the calendar even though the
191     * historical usage differs.  For example, if the Gregorian change is set
192     * to new Date(Long.MIN_VALUE), we have a pure Gregorian calendar which
193     * labels dates preceding the invention of the Gregorian calendar in 1582 as
194     * if the calendar existed then.
195     *
196     * Likewise, with the Julian calendar, we assume a consistent 4-year leap
197     * rule, even though the historical pattern of leap years is irregular,
198     * being every 3 years from 45 BC through 9 BC, then every 4 years from 8 AD
199     * onwards, with no leap years in-between.  Thus date computations and
200     * functions such as isLeapYear() are not intended to be historically
201     * accurate.
202     *
203     * Given that milliseconds are a long, day numbers such as Julian day
204     * numbers, Gregorian or Julian calendar days, or epoch days, are also
205     * longs. Years can fit into an int.
206     */
207
208//////////////////
209// Class Variables
210//////////////////
211
212    /**
213     * Value of the <code>ERA</code> field indicating
214     * the period before the common era (before Christ), also known as BCE.
215     * The sequence of years at the transition from <code>BC</code> to <code>AD</code> is
216     * ..., 2 BC, 1 BC, 1 AD, 2 AD,...
217     * @see Calendar#ERA
218     */
219    public static final int BC = 0;
220
221    /**
222     * Value of the <code>ERA</code> field indicating
223     * the common era (Anno Domini), also known as CE.
224     * The sequence of years at the transition from <code>BC</code> to <code>AD</code> is
225     * ..., 2 BC, 1 BC, 1 AD, 2 AD,...
226     * @see Calendar#ERA
227     */
228    public static final int AD = 1;
229
230    private static final int EPOCH_YEAR = 1970;
231
232    private static final int[][] MONTH_COUNT = {
233        //len len2   st  st2
234        {  31,  31,   0,   0 }, // Jan
235        {  28,  29,  31,  31 }, // Feb
236        {  31,  31,  59,  60 }, // Mar
237        {  30,  30,  90,  91 }, // Apr
238        {  31,  31, 120, 121 }, // May
239        {  30,  30, 151, 152 }, // Jun
240        {  31,  31, 181, 182 }, // Jul
241        {  31,  31, 212, 213 }, // Aug
242        {  30,  30, 243, 244 }, // Sep
243        {  31,  31, 273, 274 }, // Oct
244        {  30,  30, 304, 305 }, // Nov
245        {  31,  31, 334, 335 }  // Dec
246        // len  length of month
247        // len2 length of month in a leap year
248        // st   days in year before start of month
249        // st2  days in year before month in leap year
250    };
251
252    /**
253     * Old year limits were least max 292269054, max 292278994.
254     */
255    private static final int LIMITS[][] = {
256        // Minimum  Greatest    Least  Maximum
257        //           Minimum  Maximum
258        {        0,        0,       1,       1 }, // ERA
259        {        1,        1, 5828963, 5838270 }, // YEAR
260        {        0,        0,      11,      11 }, // MONTH
261        {        1,        1,      52,      53 }, // WEEK_OF_YEAR
262        {/*                                  */}, // WEEK_OF_MONTH
263        {        1,        1,      28,      31 }, // DAY_OF_MONTH
264        {        1,        1,     365,     366 }, // DAY_OF_YEAR
265        {/*                                  */}, // DAY_OF_WEEK
266        {       -1,       -1,       4,       5 }, // DAY_OF_WEEK_IN_MONTH
267        {/*                                  */}, // AM_PM
268        {/*                                  */}, // HOUR
269        {/*                                  */}, // HOUR_OF_DAY
270        {/*                                  */}, // MINUTE
271        {/*                                  */}, // SECOND
272        {/*                                  */}, // MILLISECOND
273        {/*                                  */}, // ZONE_OFFSET
274        {/*                                  */}, // DST_OFFSET
275        { -5838270, -5838270, 5828964, 5838271 }, // YEAR_WOY
276        {/*                                  */}, // DOW_LOCAL
277        { -5838269, -5838269, 5828963, 5838270 }, // EXTENDED_YEAR
278        {/*                                  */}, // JULIAN_DAY
279        {/*                                  */}, // MILLISECONDS_IN_DAY
280        {/*                                  */}, // IS_LEAP_MONTH
281    };
282
283    /**
284     */
285    protected int handleGetLimit(int field, int limitType) {
286        return LIMITS[field][limitType];
287    }
288
289/////////////////////
290// Instance Variables
291/////////////////////
292
293    /**
294     * The point at which the Gregorian calendar rules are used, measured in
295     * milliseconds from the standard epoch.  Default is October 15, 1582
296     * (Gregorian) 00:00:00 UTC or -12219292800000L.  For this value, October 4,
297     * 1582 (Julian) is followed by October 15, 1582 (Gregorian).  This
298     * corresponds to Julian day number 2299161.
299     * @serial
300     */
301    private long gregorianCutover = -12219292800000L;
302
303    /**
304     * Julian day number of the Gregorian cutover.
305     */
306    private transient int cutoverJulianDay = 2299161;
307
308    /**
309     * The year of the gregorianCutover, with 0 representing
310     * 1 BC, -1 representing 2 BC, etc.
311     */
312    private transient int gregorianCutoverYear = 1582;
313
314    /**
315     * Used by handleComputeJulianDay() and handleComputeMonthStart().
316     */
317    transient protected boolean isGregorian;
318
319    /**
320     * Used by handleComputeJulianDay() and handleComputeMonthStart().
321     */
322    transient protected boolean invertGregorian;
323
324///////////////
325// Constructors
326///////////////
327
328    /**
329     * Constructs a default GregorianCalendar using the current time
330     * in the default time zone with the default <code>FORMAT</code> locale.
331     * @see Category#FORMAT
332     */
333    public GregorianCalendar() {
334        this(TimeZone.getDefault(), ULocale.getDefault(Category.FORMAT));
335    }
336
337    /**
338     * Constructs a GregorianCalendar based on the current time
339     * in the given time zone with the default <code>FORMAT</code> locale.
340     * @param zone the given time zone.
341     * @see Category#FORMAT
342     */
343    public GregorianCalendar(TimeZone zone) {
344        this(zone, ULocale.getDefault(Category.FORMAT));
345    }
346
347    /**
348     * Constructs a GregorianCalendar based on the current time
349     * in the default time zone with the given locale.
350     * @param aLocale the given locale.
351     */
352    public GregorianCalendar(Locale aLocale) {
353        this(TimeZone.getDefault(), aLocale);
354    }
355
356    /**
357     * <strong>[icu]</strong> Constructs a GregorianCalendar based on the current time
358     * in the default time zone with the given locale.
359     * @param locale the given ulocale.
360     */
361    public GregorianCalendar(ULocale locale) {
362        this(TimeZone.getDefault(), locale);
363    }
364
365    /**
366     * <strong>[icu]</strong> Constructs a GregorianCalendar based on the current time
367     * in the given time zone with the given locale.
368     * @param zone the given time zone.
369     * @param aLocale the given locale.
370     */
371    public GregorianCalendar(TimeZone zone, Locale aLocale) {
372        super(zone, aLocale);
373        setTimeInMillis(System.currentTimeMillis());
374    }
375
376    /**
377     * Constructs a GregorianCalendar based on the current time
378     * in the given time zone with the given locale.
379     * @param zone the given time zone.
380     * @param locale the given ulocale.
381     */
382    public GregorianCalendar(TimeZone zone, ULocale locale) {
383        super(zone, locale);
384        setTimeInMillis(System.currentTimeMillis());
385    }
386
387    /**
388     * Constructs a GregorianCalendar with the given date set
389     * in the default time zone with the default <code>FORMAT</code> locale.
390     * @param year the value used to set the YEAR time field in the calendar.
391     * @param month the value used to set the MONTH time field in the calendar.
392     * Month value is 0-based. e.g., 0 for January.
393     * @param date the value used to set the DATE time field in the calendar.
394     * @see Category#FORMAT
395     */
396    public GregorianCalendar(int year, int month, int date) {
397        super(TimeZone.getDefault(), ULocale.getDefault(Category.FORMAT));
398        set(ERA, AD);
399        set(YEAR, year);
400        set(MONTH, month);
401        set(DATE, date);
402    }
403
404    /**
405     * Constructs a GregorianCalendar with the given date
406     * and time set for the default time zone with the default <code>FORMAT</code> locale.
407     * @param year the value used to set the YEAR time field in the calendar.
408     * @param month the value used to set the MONTH time field in the calendar.
409     * Month value is 0-based. e.g., 0 for January.
410     * @param date the value used to set the DATE time field in the calendar.
411     * @param hour the value used to set the HOUR_OF_DAY time field
412     * in the calendar.
413     * @param minute the value used to set the MINUTE time field
414     * in the calendar.
415     * @see Category#FORMAT
416     */
417    public GregorianCalendar(int year, int month, int date, int hour,
418                             int minute) {
419        super(TimeZone.getDefault(), ULocale.getDefault(Category.FORMAT));
420        set(ERA, AD);
421        set(YEAR, year);
422        set(MONTH, month);
423        set(DATE, date);
424        set(HOUR_OF_DAY, hour);
425        set(MINUTE, minute);
426    }
427
428    /**
429     * Constructs a GregorianCalendar with the given date
430     * and time set for the default time zone with the default <code>FORMAT</code> locale.
431     * @param year the value used to set the YEAR time field in the calendar.
432     * @param month the value used to set the MONTH time field in the calendar.
433     * Month value is 0-based. e.g., 0 for January.
434     * @param date the value used to set the DATE time field in the calendar.
435     * @param hour the value used to set the HOUR_OF_DAY time field
436     * in the calendar.
437     * @param minute the value used to set the MINUTE time field
438     * in the calendar.
439     * @param second the value used to set the SECOND time field
440     * in the calendar.
441     * @see Category#FORMAT
442     */
443    public GregorianCalendar(int year, int month, int date, int hour,
444                             int minute, int second) {
445        super(TimeZone.getDefault(), ULocale.getDefault(Category.FORMAT));
446        set(ERA, AD);
447        set(YEAR, year);
448        set(MONTH, month);
449        set(DATE, date);
450        set(HOUR_OF_DAY, hour);
451        set(MINUTE, minute);
452        set(SECOND, second);
453    }
454
455/////////////////
456// Public methods
457/////////////////
458
459    /**
460     * Sets the GregorianCalendar change date. This is the point when the switch
461     * from Julian dates to Gregorian dates occurred. Default is October 15,
462     * 1582. Previous to this, dates will be in the Julian calendar.
463     * <p>
464     * To obtain a pure Julian calendar, set the change date to
465     * <code>Date(Long.MAX_VALUE)</code>.  To obtain a pure Gregorian calendar,
466     * set the change date to <code>Date(Long.MIN_VALUE)</code>.
467     *
468     * @param date the given Gregorian cutover date.
469     */
470    public void setGregorianChange(Date date) {
471        gregorianCutover = date.getTime();
472
473        // If the cutover has an extreme value, then create a pure
474        // Gregorian or pure Julian calendar by giving the cutover year and
475        // JD extreme values.
476        if (gregorianCutover <= MIN_MILLIS) {
477            gregorianCutoverYear = cutoverJulianDay = Integer.MIN_VALUE;
478        } else if (gregorianCutover >= MAX_MILLIS) {
479            gregorianCutoverYear = cutoverJulianDay = Integer.MAX_VALUE;
480        } else {
481            // Precompute two internal variables which we use to do the actual
482            // cutover computations.  These are the Julian day of the cutover
483            // and the cutover year.
484            cutoverJulianDay = (int) floorDivide(gregorianCutover, ONE_DAY);
485
486            // Convert cutover millis to extended year
487            GregorianCalendar cal = new GregorianCalendar(getTimeZone());
488            cal.setTime(date);
489            gregorianCutoverYear = cal.get(EXTENDED_YEAR);
490        }
491    }
492
493    /**
494     * Gets the Gregorian Calendar change date.  This is the point when the
495     * switch from Julian dates to Gregorian dates occurred. Default is
496     * October 15, 1582. Previous to this, dates will be in the Julian
497     * calendar.
498     * @return the Gregorian cutover date for this calendar.
499     */
500    public final Date getGregorianChange() {
501        return new Date(gregorianCutover);
502    }
503
504    /**
505     * Determines if the given year is a leap year. Returns true if the
506     * given year is a leap year.
507     * @param year the given year.
508     * @return true if the given year is a leap year; false otherwise.
509     */
510    public boolean isLeapYear(int year) {
511        return year >= gregorianCutoverYear ?
512            ((year%4 == 0) && ((year%100 != 0) || (year%400 == 0))) : // Gregorian
513            (year%4 == 0); // Julian
514    }
515
516    /**
517     * Returns true if the given Calendar object is equivalent to this
518     * one.  Calendar override.
519     *
520     * @param other the Calendar to be compared with this Calendar
521     */
522    public boolean isEquivalentTo(Calendar other) {
523        return super.isEquivalentTo(other) &&
524            gregorianCutover == ((GregorianCalendar)other).gregorianCutover;
525    }
526
527    /**
528     * Override hashCode.
529     * Generates the hash code for the GregorianCalendar object
530     */
531    public int hashCode() {
532        return super.hashCode() ^ (int)gregorianCutover;
533    }
534
535    /**
536     * Roll a field by a signed amount.
537     */
538    public void roll(int field, int amount) {
539
540        switch (field) {
541        case WEEK_OF_YEAR:
542            {
543                // Unlike WEEK_OF_MONTH, WEEK_OF_YEAR never shifts the day of the
544                // week.  Also, rolling the week of the year can have seemingly
545                // strange effects simply because the year of the week of year
546                // may be different from the calendar year.  For example, the
547                // date Dec 28, 1997 is the first day of week 1 of 1998 (if
548                // weeks start on Sunday and the minimal days in first week is
549                // <= 3).
550                int woy = get(WEEK_OF_YEAR);
551                // Get the ISO year, which matches the week of year.  This
552                // may be one year before or after the calendar year.
553                int isoYear = get(YEAR_WOY);
554                int isoDoy = internalGet(DAY_OF_YEAR);
555                if (internalGet(MONTH) == Calendar.JANUARY) {
556                    if (woy >= 52) {
557                        isoDoy += handleGetYearLength(isoYear);
558                    }
559                } else {
560                    if (woy == 1) {
561                        isoDoy -= handleGetYearLength(isoYear - 1);
562                    }
563                }
564                woy += amount;
565                // Do fast checks to avoid unnecessary computation:
566                if (woy < 1 || woy > 52) {
567                    // Determine the last week of the ISO year.
568                    // We do this using the standard formula we use
569                    // everywhere in this file.  If we can see that the
570                    // days at the end of the year are going to fall into
571                    // week 1 of the next year, we drop the last week by
572                    // subtracting 7 from the last day of the year.
573                    int lastDoy = handleGetYearLength(isoYear);
574                    int lastRelDow = (lastDoy - isoDoy + internalGet(DAY_OF_WEEK) -
575                                      getFirstDayOfWeek()) % 7;
576                    if (lastRelDow < 0) lastRelDow += 7;
577                    if ((6 - lastRelDow) >= getMinimalDaysInFirstWeek()) lastDoy -= 7;
578                    int lastWoy = weekNumber(lastDoy, lastRelDow + 1);
579                    woy = ((woy + lastWoy - 1) % lastWoy) + 1;
580                }
581                set(WEEK_OF_YEAR, woy);
582                set(YEAR, isoYear); // Why not YEAR_WOY? - Alan 11/6/00
583                return;
584            }
585
586        default:
587            super.roll(field, amount);
588            return;
589        }
590    }
591
592    /**
593     * Return the minimum value that this field could have, given the current date.
594     * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
595     */
596    public int getActualMinimum(int field) {
597        return getMinimum(field);
598    }
599
600    /**
601     * Return the maximum value that this field could have, given the current date.
602     * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual
603     * maximum would be 28; for "Feb 3, 1996" it s 29.  Similarly for a Hebrew calendar,
604     * for some years the actual maximum for MONTH is 12, and for others 13.
605     */
606    public int getActualMaximum(int field) {
607        /* It is a known limitation that the code here (and in getActualMinimum)
608         * won't behave properly at the extreme limits of GregorianCalendar's
609         * representable range (except for the code that handles the YEAR
610         * field).  That's because the ends of the representable range are at
611         * odd spots in the year.  For calendars with the default Gregorian
612         * cutover, these limits are Sun Dec 02 16:47:04 GMT 292269055 BC to Sun
613         * Aug 17 07:12:55 GMT 292278994 AD, somewhat different for non-GMT
614         * zones.  As a result, if the calendar is set to Aug 1 292278994 AD,
615         * the actual maximum of DAY_OF_MONTH is 17, not 30.  If the date is Mar
616         * 31 in that year, the actual maximum month might be Jul, whereas is
617         * the date is Mar 15, the actual maximum might be Aug -- depending on
618         * the precise semantics that are desired.  Similar considerations
619         * affect all fields.  Nonetheless, this effect is sufficiently arcane
620         * that we permit it, rather than complicating the code to handle such
621         * intricacies. - liu 8/20/98
622
623         * UPDATE: No longer true, since we have pulled in the limit values on
624         * the year. - Liu 11/6/00 */
625
626        switch (field) {
627
628        case YEAR:
629            /* The year computation is no different, in principle, from the
630             * others, however, the range of possible maxima is large.  In
631             * addition, the way we know we've exceeded the range is different.
632             * For these reasons, we use the special case code below to handle
633             * this field.
634             *
635             * The actual maxima for YEAR depend on the type of calendar:
636             *
637             *     Gregorian = May 17, 292275056 BC - Aug 17, 292278994 AD
638             *     Julian    = Dec  2, 292269055 BC - Jan  3, 292272993 AD
639             *     Hybrid    = Dec  2, 292269055 BC - Aug 17, 292278994 AD
640             *
641             * We know we've exceeded the maximum when either the month, date,
642             * time, or era changes in response to setting the year.  We don't
643             * check for month, date, and time here because the year and era are
644             * sufficient to detect an invalid year setting.  NOTE: If code is
645             * added to check the month and date in the future for some reason,
646             * Feb 29 must be allowed to shift to Mar 1 when setting the year.
647             */
648            {
649                Calendar cal = (Calendar) clone();
650                cal.setLenient(true);
651
652                int era = cal.get(ERA);
653                Date d = cal.getTime();
654
655                /* Perform a binary search, with the invariant that lowGood is a
656                 * valid year, and highBad is an out of range year.
657                 */
658                int lowGood = LIMITS[YEAR][1];
659                int highBad = LIMITS[YEAR][2]+1;
660                while ((lowGood + 1) < highBad) {
661                    int y = (lowGood + highBad) / 2;
662                    cal.set(YEAR, y);
663                    if (cal.get(YEAR) == y && cal.get(ERA) == era) {
664                        lowGood = y;
665                    } else {
666                        highBad = y;
667                        cal.setTime(d); // Restore original fields
668                    }
669                }
670
671                return lowGood;
672            }
673
674        default:
675            return super.getActualMaximum(field);
676        }
677    }
678
679//////////////////////
680// Proposed public API
681//////////////////////
682
683    /**
684     * Return true if the current time for this Calendar is in Daylignt
685     * Savings Time.
686     */
687    boolean inDaylightTime() {
688        if (!getTimeZone().useDaylightTime()) return false;
689        complete(); // Force update of DST_OFFSET field
690        return internalGet(DST_OFFSET) != 0;
691    }
692
693
694/////////////////////
695// Calendar framework
696/////////////////////
697
698    /**
699     */
700    protected int handleGetMonthLength(int extendedYear, int month) {
701        // If the month is out of range, adjust it into range, and
702        // modify the extended year value accordingly.
703        if (month < 0 || month > 11) {
704            int[] rem = new int[1];
705            extendedYear += floorDivide(month, 12, rem);
706            month = rem[0];
707        }
708
709        return MONTH_COUNT[month][isLeapYear(extendedYear)?1:0];
710    }
711
712    /**
713     */
714    protected int handleGetYearLength(int eyear) {
715        return isLeapYear(eyear) ? 366 : 365;
716    }
717
718/////////////////////////////
719// Time => Fields computation
720/////////////////////////////
721
722    /**
723     * Override Calendar to compute several fields specific to the hybrid
724     * Gregorian-Julian calendar system.  These are:
725     *
726     * <ul><li>ERA
727     * <li>YEAR
728     * <li>MONTH
729     * <li>DAY_OF_MONTH
730     * <li>DAY_OF_YEAR
731     * <li>EXTENDED_YEAR</ul>
732     */
733    protected void handleComputeFields(int julianDay) {
734        int eyear, month, dayOfMonth, dayOfYear;
735
736        if (julianDay >= cutoverJulianDay) {
737            month = getGregorianMonth();
738            dayOfMonth = getGregorianDayOfMonth();
739            dayOfYear = getGregorianDayOfYear();
740            eyear = getGregorianYear();
741        } else {
742            // The Julian epoch day (not the same as Julian Day)
743            // is zero on Saturday December 30, 0 (Gregorian).
744            long julianEpochDay = julianDay - (JAN_1_1_JULIAN_DAY - 2);
745            eyear = (int) floorDivide(4*julianEpochDay + 1464, 1461);
746
747            // Compute the Julian calendar day number for January 1, eyear
748            long january1 = 365L*(eyear-1L) + floorDivide(eyear-1L, 4L);
749            dayOfYear = (int)(julianEpochDay - january1); // 0-based
750
751            // Julian leap years occurred historically every 4 years starting
752            // with 8 AD.  Before 8 AD the spacing is irregular; every 3 years
753            // from 45 BC to 9 BC, and then none until 8 AD.  However, we don't
754            // implement this historical detail; instead, we implement the
755            // computatinally cleaner proleptic calendar, which assumes
756            // consistent 4-year cycles throughout time.
757            boolean isLeap = ((eyear&0x3) == 0); // equiv. to (eyear%4 == 0)
758
759            // Common Julian/Gregorian calculation
760            int correction = 0;
761            int march1 = isLeap ? 60 : 59; // zero-based DOY for March 1
762            if (dayOfYear >= march1) {
763                correction = isLeap ? 1 : 2;
764            }
765            month = (12 * (dayOfYear + correction) + 6) / 367; // zero-based month
766            dayOfMonth = dayOfYear - MONTH_COUNT[month][isLeap?3:2] + 1; // one-based DOM
767            ++dayOfYear;
768        }
769        internalSet(MONTH, month);
770        internalSet(DAY_OF_MONTH, dayOfMonth);
771        internalSet(DAY_OF_YEAR, dayOfYear);
772        internalSet(EXTENDED_YEAR, eyear);
773        int era = AD;
774        if (eyear < 1) {
775            era = BC;
776            eyear = 1 - eyear;
777        }
778        internalSet(ERA, era);
779        internalSet(YEAR, eyear);
780    }
781
782/////////////////////////////
783// Fields => Time computation
784/////////////////////////////
785
786    /**
787     */
788    protected int handleGetExtendedYear() {
789        int year;
790        if (newerField(EXTENDED_YEAR, YEAR) == EXTENDED_YEAR) {
791            year = internalGet(EXTENDED_YEAR, EPOCH_YEAR);
792        } else {
793            // The year defaults to the epoch start, the era to AD
794            int era = internalGet(ERA, AD);
795            if (era == BC) {
796                year = 1 - internalGet(YEAR, 1); // Convert to extended year
797            } else {
798                year = internalGet(YEAR, EPOCH_YEAR);
799            }
800        }
801        return year;
802    }
803
804    /**
805     */
806    protected int handleComputeJulianDay(int bestField) {
807
808        invertGregorian = false;
809
810        int jd = super.handleComputeJulianDay(bestField);
811
812        // The following check handles portions of the cutover year BEFORE the
813        // cutover itself happens.
814        if (isGregorian != (jd >= cutoverJulianDay)) {
815            invertGregorian = true;
816            jd = super.handleComputeJulianDay(bestField);
817        }
818
819        return jd;
820    }
821
822    /**
823     * Return JD of start of given month/year
824     */
825    protected int handleComputeMonthStart(int eyear, int month, boolean useMonth) {
826
827        // If the month is out of range, adjust it into range, and
828        // modify the extended year value accordingly.
829        if (month < 0 || month > 11) {
830            int[] rem = new int[1];
831            eyear += floorDivide(month, 12, rem);
832            month = rem[0];
833        }
834
835        boolean isLeap = eyear%4 == 0;
836        int y = eyear - 1;
837        int julianDay = 365*y + floorDivide(y, 4) + (JAN_1_1_JULIAN_DAY - 3);
838
839        isGregorian = (eyear >= gregorianCutoverYear);
840        if (invertGregorian) {
841            isGregorian = !isGregorian;
842        }
843        if (isGregorian) {
844            isLeap = isLeap && ((eyear%100 != 0) || (eyear%400 == 0));
845            // Add 2 because Gregorian calendar starts 2 days after
846            // Julian calendar
847            julianDay += floorDivide(y, 400) - floorDivide(y, 100) + 2;
848        }
849
850        // At this point julianDay indicates the day BEFORE the first
851        // day of January 1, <eyear> of either the Julian or Gregorian
852        // calendar.
853
854        if (month != 0) {
855            julianDay += MONTH_COUNT[month][isLeap?3:2];
856        }
857
858        return julianDay;
859    }
860
861    /**
862     * {@inheritDoc}
863     */
864    public String getType() {
865        return "gregorian";
866    }
867
868    /*
869    private static CalendarFactory factory;
870    public static CalendarFactory factory() {
871        if (factory == null) {
872            factory = new CalendarFactory() {
873                public Calendar create(TimeZone tz, ULocale loc) {
874                    return new GregorianCalendar(tz, loc);
875                }
876
877                public String factoryName() {
878                    return "Gregorian";
879                }
880            };
881        }
882        return factory;
883    }
884    */
885}
886