KickJava   Java API By Example, From Geeks To Geeks.

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


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

5 package com.ibm.icu.util;
6
7 import java.util.Date JavaDoc;
8 import java.util.Locale JavaDoc;
9
10 /**
11  * <code>GregorianCalendar</code> is a concrete subclass of
12  * {@link Calendar}
13  * and provides the standard calendar used by most of the world.
14  *
15  * <p>
16  * The standard (Gregorian) calendar has 2 eras, BC and AD.
17  *
18  * <p>
19  * This implementation handles a single discontinuity, which corresponds by
20  * default to the date the Gregorian calendar was instituted (October 15, 1582
21  * in some countries, later in others). The cutover date may be changed by the
22  * caller by calling <code>setGregorianChange()</code>.
23  *
24  * <p>
25  * Historically, in those countries which adopted the Gregorian calendar first,
26  * October 4, 1582 was thus followed by October 15, 1582. This calendar models
27  * this correctly. Before the Gregorian cutover, <code>GregorianCalendar</code>
28  * implements the Julian calendar. The only difference between the Gregorian
29  * and the Julian calendar is the leap year rule. The Julian calendar specifies
30  * leap years every four years, whereas the Gregorian calendar omits century
31  * years which are not divisible by 400.
32  *
33  * <p>
34  * <code>GregorianCalendar</code> implements <em>proleptic</em> Gregorian and
35  * Julian calendars. That is, dates are computed by extrapolating the current
36  * rules indefinitely far backward and forward in time. As a result,
37  * <code>GregorianCalendar</code> may be used for all years to generate
38  * meaningful and consistent results. However, dates obtained using
39  * <code>GregorianCalendar</code> are historically accurate only from March 1, 4
40  * AD onward, when modern Julian calendar rules were adopted. Before this date,
41  * leap year rules were applied irregularly, and before 45 BC the Julian
42  * calendar did not even exist.
43  *
44  * <p>
45  * Prior to the institution of the Gregorian calendar, New Year's Day was
46  * March 25. To avoid confusion, this calendar always uses January 1. A manual
47  * adjustment may be made if desired for dates that are prior to the Gregorian
48  * changeover and which fall between January 1 and March 24.
49  *
50  * <p>Values calculated for the <code>WEEK_OF_YEAR</code> field range from 1 to
51  * 53. Week 1 for a year is the earliest seven day period starting on
52  * <code>getFirstDayOfWeek()</code> that contains at least
53  * <code>getMinimalDaysInFirstWeek()</code> days from that year. It thus
54  * depends on the values of <code>getMinimalDaysInFirstWeek()</code>,
55  * <code>getFirstDayOfWeek()</code>, and the day of the week of January 1.
56  * Weeks between week 1 of one year and week 1 of the following year are
57  * numbered sequentially from 2 to 52 or 53 (as needed).
58
59  * <p>For example, January 1, 1998 was a Thursday. If
60  * <code>getFirstDayOfWeek()</code> is <code>MONDAY</code> and
61  * <code>getMinimalDaysInFirstWeek()</code> is 4 (these are the values
62  * reflecting ISO 8601 and many national standards), then week 1 of 1998 starts
63  * on December 29, 1997, and ends on January 4, 1998. If, however,
64  * <code>getFirstDayOfWeek()</code> is <code>SUNDAY</code>, then week 1 of 1998
65  * starts on January 4, 1998, and ends on January 10, 1998; the first three days
66  * of 1998 then are part of week 53 of 1997.
67  *
68  * <p>Values calculated for the <code>WEEK_OF_MONTH</code> field range from 0 or
69  * 1 to 4 or 5. Week 1 of a month (the days with <code>WEEK_OF_MONTH =
70  * 1</code>) is the earliest set of at least
71  * <code>getMinimalDaysInFirstWeek()</code> contiguous days in that month,
72  * ending on the day before <code>getFirstDayOfWeek()</code>. Unlike
73  * week 1 of a year, week 1 of a month may be shorter than 7 days, need
74  * not start on <code>getFirstDayOfWeek()</code>, and will not include days of
75  * the previous month. Days of a month before week 1 have a
76  * <code>WEEK_OF_MONTH</code> of 0.
77  *
78  * <p>For example, if <code>getFirstDayOfWeek()</code> is <code>SUNDAY</code>
79  * and <code>getMinimalDaysInFirstWeek()</code> is 4, then the first week of
80  * January 1998 is Sunday, January 4 through Saturday, January 10. These days
81  * have a <code>WEEK_OF_MONTH</code> of 1. Thursday, January 1 through
82  * Saturday, January 3 have a <code>WEEK_OF_MONTH</code> of 0. If
83  * <code>getMinimalDaysInFirstWeek()</code> is changed to 3, then January 1
84  * through January 3 have a <code>WEEK_OF_MONTH</code> of 1.
85  *
86  * <p>
87  * <strong>Example:</strong>
88  * <blockquote>
89  * <pre>
90  * // get the supported ids for GMT-08:00 (Pacific Standard Time)
91  * String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
92  * // if no ids were returned, something is wrong. get out.
93  * if (ids.length == 0)
94  * System.exit(0);
95  *
96  * // begin output
97  * System.out.println("Current Time");
98  *
99  * // create a Pacific Standard Time time zone
100  * SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
101  *
102  * // set up rules for daylight savings time
103  * pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
104  * pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
105  *
106  * // create a GregorianCalendar with the Pacific Daylight time zone
107  * // and the current date and time
108  * Calendar calendar = new GregorianCalendar(pdt);
109  * Date trialTime = new Date();
110  * calendar.setTime(trialTime);
111  *
112  * // print out a bunch of interesting things
113  * System.out.println("ERA: " + calendar.get(Calendar.ERA));
114  * System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
115  * System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
116  * System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR));
117  * System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH));
118  * System.out.println("DATE: " + calendar.get(Calendar.DATE));
119  * System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
120  * System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR));
121  * System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));
122  * System.out.println("DAY_OF_WEEK_IN_MONTH: "
123  * + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
124  * System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
125  * System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
126  * System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
127  * System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
128  * System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
129  * System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
130  * System.out.println("ZONE_OFFSET: "
131  * + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000)));
132  * System.out.println("DST_OFFSET: "
133  * + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000)));
134
135  * System.out.println("Current Time, with hour reset to 3");
136  * calendar.clear(Calendar.HOUR_OF_DAY); // so doesn't override
137  * calendar.set(Calendar.HOUR, 3);
138  * System.out.println("ERA: " + calendar.get(Calendar.ERA));
139  * System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
140  * System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
141  * System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR));
142  * System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH));
143  * System.out.println("DATE: " + calendar.get(Calendar.DATE));
144  * System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
145  * System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR));
146  * System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));
147  * System.out.println("DAY_OF_WEEK_IN_MONTH: "
148  * + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
149  * System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
150  * System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
151  * System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
152  * System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
153  * System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
154  * System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
155  * System.out.println("ZONE_OFFSET: "
156  * + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000))); // in hours
157  * System.out.println("DST_OFFSET: "
158  * + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000))); // in hours</pre>
159  * </blockquote>
160  * <p>
161  * GregorianCalendar usually should be instantiated using
162  * {@link com.ibm.icu.util.Calendar#getInstance(ULocale)} passing in a <code>ULocale</code>
163  * with the tag <code>"@calendar=gregorian"</code>.</p>
164
165  * @see Calendar
166  * @see TimeZone
167  * @author David Goldsmith, Mark Davis, Chen-Lieh Huang, Alan Liu
168  * @stable ICU 2.0
169  */

170 public class GregorianCalendar extends Calendar {
171     // jdk1.4.2 serialver
172
private static final long serialVersionUID = 9199388694351062137L;
173
174     /*
175      * Implementation Notes
176      *
177      * The Julian day number, as used here, is a modified number which has its
178      * onset at midnight, rather than noon.
179      *
180      * The epoch is the number of days or milliseconds from some defined
181      * starting point. The epoch for java.util.Date is used here; that is,
182      * milliseconds from January 1, 1970 (Gregorian), midnight UTC. Other
183      * epochs which are used are January 1, year 1 (Gregorian), which is day 1
184      * of the Gregorian calendar, and December 30, year 0 (Gregorian), which is
185      * day 1 of the Julian calendar.
186      *
187      * We implement the proleptic Julian and Gregorian calendars. This means we
188      * implement the modern definition of the calendar even though the
189      * historical usage differs. For example, if the Gregorian change is set
190      * to new Date(Long.MIN_VALUE), we have a pure Gregorian calendar which
191      * labels dates preceding the invention of the Gregorian calendar in 1582 as
192      * if the calendar existed then.
193      *
194      * Likewise, with the Julian calendar, we assume a consistent 4-year leap
195      * rule, even though the historical pattern of leap years is irregular,
196      * being every 3 years from 45 BC through 9 BC, then every 4 years from 8 AD
197      * onwards, with no leap years in-between. Thus date computations and
198      * functions such as isLeapYear() are not intended to be historically
199      * accurate.
200      *
201      * Given that milliseconds are a long, day numbers such as Julian day
202      * numbers, Gregorian or Julian calendar days, or epoch days, are also
203      * longs. Years can fit into an int.
204      */

205
206 //////////////////
207
// Class Variables
208
//////////////////
209

210     /**
211      * Value of the <code>ERA</code> field indicating
212      * the period before the common era (before Christ), also known as BCE.
213      * The sequence of years at the transition from <code>BC</code> to <code>AD</code> is
214      * ..., 2 BC, 1 BC, 1 AD, 2 AD,...
215      * @see Calendar#ERA
216      * @stable ICU 2.0
217      */

218     public static final int BC = 0;
219
220     /**
221      * Value of the <code>ERA</code> field indicating
222      * the common era (Anno Domini), also known as CE.
223      * The sequence of years at the transition from <code>BC</code> to <code>AD</code> is
224      * ..., 2 BC, 1 BC, 1 AD, 2 AD,...
225      * @see Calendar#ERA
226      * @stable ICU 2.0
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
{ 0, 0, 4, 6 }, // 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, 6 }, // 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
};
281
282     /**
283      * @stable ICU 2.0
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      * @stable ICU 2.0
317      */

318     transient protected boolean isGregorian;
319
320     /**
321      * Used by handleComputeJulianDay() and handleComputeMonthStart().
322      * @stable ICU 2.0
323      */

324     transient protected boolean invertGregorian;
325
326 ///////////////
327
// Constructors
328
///////////////
329

330     /**
331      * Constructs a default GregorianCalendar using the current time
332      * in the default time zone with the default locale.
333      * @stable ICU 2.0
334      */

335     public GregorianCalendar() {
336         this(TimeZone.getDefault(), ULocale.getDefault());
337     }
338
339     /**
340      * Constructs a GregorianCalendar based on the current time
341      * in the given time zone with the default locale.
342      * @param zone the given time zone.
343      * @stable ICU 2.0
344      */

345     public GregorianCalendar(TimeZone zone) {
346         this(zone, ULocale.getDefault());
347     }
348
349     /**
350      * Constructs a GregorianCalendar based on the current time
351      * in the default time zone with the given locale.
352      * @param aLocale the given locale.
353      * @stable ICU 2.0
354      */

355     public GregorianCalendar(Locale JavaDoc aLocale) {
356         this(TimeZone.getDefault(), aLocale);
357     }
358
359     /**
360      * Constructs a GregorianCalendar based on the current time
361      * in the default time zone with the given locale.
362      * @param locale the given ulocale.
363      * @draft ICU 3.2
364      * @provisional This API might change or be removed in a future release.
365      */

366     public GregorianCalendar(ULocale locale) {
367         this(TimeZone.getDefault(), locale);
368     }
369
370     /**
371      * Constructs a GregorianCalendar based on the current time
372      * in the given time zone with the given locale.
373      * @param zone the given time zone.
374      * @param aLocale the given locale.
375      * @stable ICU 2.0
376      */

377     public GregorianCalendar(TimeZone zone, Locale JavaDoc aLocale) {
378         super(zone, aLocale);
379         setTimeInMillis(System.currentTimeMillis());
380     }
381
382     /**
383      * Constructs a GregorianCalendar based on the current time
384      * in the given time zone with the given locale.
385      * @param zone the given time zone.
386      * @param locale the given ulocale.
387      * @draft ICU 3.2
388      * @provisional This API might change or be removed in a future release.
389      */

390     public GregorianCalendar(TimeZone zone, ULocale locale) {
391         super(zone, locale);
392         setTimeInMillis(System.currentTimeMillis());
393     }
394
395     /**
396      * Constructs a GregorianCalendar with the given date set
397      * in the default time zone with the default locale.
398      * @param year the value used to set the YEAR time field in the calendar.
399      * @param month the value used to set the MONTH time field in the calendar.
400      * Month value is 0-based. e.g., 0 for January.
401      * @param date the value used to set the DATE time field in the calendar.
402      * @stable ICU 2.0
403      */

404     public GregorianCalendar(int year, int month, int date) {
405         super(TimeZone.getDefault(), ULocale.getDefault());
406         set(ERA, AD);
407         set(YEAR, year);
408         set(MONTH, month);
409         set(DATE, date);
410     }
411
412     /**
413      * Constructs a GregorianCalendar with the given date
414      * and time set for the default time zone with the default locale.
415      * @param year the value used to set the YEAR time field in the calendar.
416      * @param month the value used to set the MONTH time field in the calendar.
417      * Month value is 0-based. e.g., 0 for January.
418      * @param date the value used to set the DATE time field in the calendar.
419      * @param hour the value used to set the HOUR_OF_DAY time field
420      * in the calendar.
421      * @param minute the value used to set the MINUTE time field
422      * in the calendar.
423      * @stable ICU 2.0
424      */

425     public GregorianCalendar(int year, int month, int date, int hour,
426                              int minute) {
427         super(TimeZone.getDefault(), ULocale.getDefault());
428         set(ERA, AD);
429         set(YEAR, year);
430         set(MONTH, month);
431         set(DATE, date);
432         set(HOUR_OF_DAY, hour);
433         set(MINUTE, minute);
434     }
435
436     /**
437      * Constructs a GregorianCalendar with the given date
438      * and time set for the default time zone with the default locale.
439      * @param year the value used to set the YEAR time field in the calendar.
440      * @param month the value used to set the MONTH time field in the calendar.
441      * Month value is 0-based. e.g., 0 for January.
442      * @param date the value used to set the DATE time field in the calendar.
443      * @param hour the value used to set the HOUR_OF_DAY time field
444      * in the calendar.
445      * @param minute the value used to set the MINUTE time field
446      * in the calendar.
447      * @param second the value used to set the SECOND time field
448      * in the calendar.
449      * @stable ICU 2.0
450      */

451     public GregorianCalendar(int year, int month, int date, int hour,
452                              int minute, int second) {
453         super(TimeZone.getDefault(), ULocale.getDefault());
454         set(ERA, AD);
455         set(YEAR, year);
456         set(MONTH, month);
457         set(DATE, date);
458         set(HOUR_OF_DAY, hour);
459         set(MINUTE, minute);
460         set(SECOND, second);
461     }
462
463 /////////////////
464
// Public methods
465
/////////////////
466

467     /**
468      * Sets the GregorianCalendar change date. This is the point when the switch
469      * from Julian dates to Gregorian dates occurred. Default is October 15,
470      * 1582. Previous to this, dates will be in the Julian calendar.
471      * <p>
472      * To obtain a pure Julian calendar, set the change date to
473      * <code>Date(Long.MAX_VALUE)</code>. To obtain a pure Gregorian calendar,
474      * set the change date to <code>Date(Long.MIN_VALUE)</code>.
475      *
476      * @param date the given Gregorian cutover date.
477      * @stable ICU 2.0
478      */

479     public void setGregorianChange(Date JavaDoc date) {
480         gregorianCutover = date.getTime();
481
482         // If the cutover has an extreme value, then create a pure
483
// Gregorian or pure Julian calendar by giving the cutover year and
484
// JD extreme values.
485
if (gregorianCutover <= MIN_MILLIS) {
486             gregorianCutoverYear = cutoverJulianDay = Integer.MIN_VALUE;
487         } else if (gregorianCutover >= MAX_MILLIS) {
488             gregorianCutoverYear = cutoverJulianDay = Integer.MAX_VALUE;
489         } else {
490             // Precompute two internal variables which we use to do the actual
491
// cutover computations. These are the Julian day of the cutover
492
// and the cutover year.
493
cutoverJulianDay = (int) floorDivide(gregorianCutover, ONE_DAY);
494             
495             // Convert cutover millis to extended year
496
GregorianCalendar cal = new GregorianCalendar(getTimeZone());
497             cal.setTime(date);
498             gregorianCutoverYear = cal.get(EXTENDED_YEAR);
499         }
500     }
501
502     /**
503      * Gets the Gregorian Calendar change date. This is the point when the
504      * switch from Julian dates to Gregorian dates occurred. Default is
505      * October 15, 1582. Previous to this, dates will be in the Julian
506      * calendar.
507      * @return the Gregorian cutover date for this calendar.
508      * @stable ICU 2.0
509      */

510     public final Date JavaDoc getGregorianChange() {
511         return new Date JavaDoc(gregorianCutover);
512     }
513
514     /**
515      * Determines if the given year is a leap year. Returns true if the
516      * given year is a leap year.
517      * @param year the given year.
518      * @return true if the given year is a leap year; false otherwise.
519      * @stable ICU 2.0
520      */

521     public boolean isLeapYear(int year) {
522         return year >= gregorianCutoverYear ?
523             ((year%4 == 0) && ((year%100 != 0) || (year%400 == 0))) : // Gregorian
524
(year%4 == 0); // Julian
525
}
526
527     /**
528      * Returns true if the given Calendar object is equivalent to this
529      * one. Calendar override.
530      *
531      * @param other the Calendar to be compared with this Calendar
532      * @stable ICU 2.4
533      */

534     public boolean isEquivalentTo(Calendar other) {
535         return super.isEquivalentTo(other) &&
536             gregorianCutover == ((GregorianCalendar)other).gregorianCutover;
537     }
538
539     /**
540      * Override hashCode.
541      * Generates the hash code for the GregorianCalendar object
542      * @stable ICU 2.0
543      */

544     public int hashCode() {
545         return super.hashCode() ^ (int)gregorianCutover;
546     }
547
548     /**
549      * Roll a field by a signed amount.
550      * @stable ICU 2.0
551      */

552     public void roll(int field, int amount) {
553
554         switch (field) {
555         case WEEK_OF_YEAR:
556             {
557                 // Unlike WEEK_OF_MONTH, WEEK_OF_YEAR never shifts the day of the
558
// week. Also, rolling the week of the year can have seemingly
559
// strange effects simply because the year of the week of year
560
// may be different from the calendar year. For example, the
561
// date Dec 28, 1997 is the first day of week 1 of 1998 (if
562
// weeks start on Sunday and the minimal days in first week is
563
// <= 3).
564
int woy = get(WEEK_OF_YEAR);
565                 // Get the ISO year, which matches the week of year. This
566
// may be one year before or after the calendar year.
567
int isoYear = get(YEAR_WOY);
568                 int isoDoy = internalGet(DAY_OF_YEAR);
569                 if (internalGet(MONTH) == Calendar.JANUARY) {
570                     if (woy >= 52) {
571                         isoDoy += handleGetYearLength(isoYear);
572                     }
573                 } else {
574                     if (woy == 1) {
575                         isoDoy -= handleGetYearLength(isoYear - 1);
576                     }
577                 }
578                 woy += amount;
579                 // Do fast checks to avoid unnecessary computation:
580
if (woy < 1 || woy > 52) {
581                     // Determine the last week of the ISO year.
582
// We do this using the standard formula we use
583
// everywhere in this file. If we can see that the
584
// days at the end of the year are going to fall into
585
// week 1 of the next year, we drop the last week by
586
// subtracting 7 from the last day of the year.
587
int lastDoy = handleGetYearLength(isoYear);
588                     int lastRelDow = (lastDoy - isoDoy + internalGet(DAY_OF_WEEK) -
589                                       getFirstDayOfWeek()) % 7;
590                     if (lastRelDow < 0) lastRelDow += 7;
591                     if ((6 - lastRelDow) >= getMinimalDaysInFirstWeek()) lastDoy -= 7;
592                     int lastWoy = weekNumber(lastDoy, lastRelDow + 1);
593                     woy = ((woy + lastWoy - 1) % lastWoy) + 1;
594                 }
595                 set(WEEK_OF_YEAR, woy);
596                 set(YEAR, isoYear); // Why not YEAR_WOY? - Alan 11/6/00
597
return;
598             }
599
600         default:
601             super.roll(field, amount);
602             return;
603         }
604     }
605
606     /**
607      * Return the minimum value that this field could have, given the current date.
608      * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
609      * @stable ICU 2.0
610      */

611     public int getActualMinimum(int field) {
612         return getMinimum(field);
613     }
614
615     /**
616      * Return the maximum value that this field could have, given the current date.
617      * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual
618      * maximum would be 28; for "Feb 3, 1996" it s 29. Similarly for a Hebrew calendar,
619      * for some years the actual maximum for MONTH is 12, and for others 13.
620      * @stable ICU 2.0
621      */

622     public int getActualMaximum(int field) {
623         /* It is a known limitation that the code here (and in getActualMinimum)
624          * won't behave properly at the extreme limits of GregorianCalendar's
625          * representable range (except for the code that handles the YEAR
626          * field). That's because the ends of the representable range are at
627          * odd spots in the year. For calendars with the default Gregorian
628          * cutover, these limits are Sun Dec 02 16:47:04 GMT 292269055 BC to Sun
629          * Aug 17 07:12:55 GMT 292278994 AD, somewhat different for non-GMT
630          * zones. As a result, if the calendar is set to Aug 1 292278994 AD,
631          * the actual maximum of DAY_OF_MONTH is 17, not 30. If the date is Mar
632          * 31 in that year, the actual maximum month might be Jul, whereas is
633          * the date is Mar 15, the actual maximum might be Aug -- depending on
634          * the precise semantics that are desired. Similar considerations
635          * affect all fields. Nonetheless, this effect is sufficiently arcane
636          * that we permit it, rather than complicating the code to handle such
637          * intricacies. - liu 8/20/98
638
639          * UPDATE: No longer true, since we have pulled in the limit values on
640          * the year. - Liu 11/6/00 */

641
642         switch (field) {
643
644         case YEAR:
645             /* The year computation is no different, in principle, from the
646              * others, however, the range of possible maxima is large. In
647              * addition, the way we know we've exceeded the range is different.
648              * For these reasons, we use the special case code below to handle
649              * this field.
650              *
651              * The actual maxima for YEAR depend on the type of calendar:
652              *
653              * Gregorian = May 17, 292275056 BC - Aug 17, 292278994 AD
654              * Julian = Dec 2, 292269055 BC - Jan 3, 292272993 AD
655              * Hybrid = Dec 2, 292269055 BC - Aug 17, 292278994 AD
656              *
657              * We know we've exceeded the maximum when either the month, date,
658              * time, or era changes in response to setting the year. We don't
659              * check for month, date, and time here because the year and era are
660              * sufficient to detect an invalid year setting. NOTE: If code is
661              * added to check the month and date in the future for some reason,
662              * Feb 29 must be allowed to shift to Mar 1 when setting the year.
663              */

664             {
665                 Calendar cal = (Calendar) clone();
666                 cal.setLenient(true);
667                 
668                 int era = cal.get(ERA);
669                 Date JavaDoc d = cal.getTime();
670
671                 /* Perform a binary search, with the invariant that lowGood is a
672                  * valid year, and highBad is an out of range year.
673                  */

674                 int lowGood = LIMITS[YEAR][1];
675                 int highBad = LIMITS[YEAR][2]+1;
676                 while ((lowGood + 1) < highBad) {
677                     int y = (lowGood + highBad) / 2;
678                     cal.set(YEAR, y);
679                     if (cal.get(YEAR) == y && cal.get(ERA) == era) {
680                         lowGood = y;
681                     } else {
682                         highBad = y;
683                         cal.setTime(d); // Restore original fields
684
}
685                 }
686                 
687                 return lowGood;
688             }
689
690         default:
691             return super.getActualMaximum(field);
692         }
693     }
694
695 //////////////////////
696
// Proposed public API
697
//////////////////////
698

699     /**
700      * Return true if the current time for this Calendar is in Daylignt
701      * Savings Time.
702      *
703      * Note -- MAKE THIS PUBLIC AT THE NEXT API CHANGE. POSSIBLY DEPRECATE
704      * AND REMOVE TimeZone.inDaylightTime().
705      */

706     boolean inDaylightTime() {
707         if (!getTimeZone().useDaylightTime()) return false;
708         complete(); // Force update of DST_OFFSET field
709
return internalGet(DST_OFFSET) != 0;
710     }
711
712
713 /////////////////////
714
// Calendar framework
715
/////////////////////
716

717     /**
718      * @stable ICU 2.0
719      */

720     protected int handleGetMonthLength(int extendedYear, int month) {
721         return MONTH_COUNT[month][isLeapYear(extendedYear)?1:0];
722     }
723
724     /**
725      * @stable ICU 2.0
726      */

727     protected int handleGetYearLength(int eyear) {
728         return isLeapYear(eyear) ? 366 : 365;
729     }
730
731 /////////////////////////////
732
// Time => Fields computation
733
/////////////////////////////
734

735     /**
736      * Override Calendar to compute several fields specific to the hybrid
737      * Gregorian-Julian calendar system. These are:
738      *
739      * <ul><li>ERA
740      * <li>YEAR
741      * <li>MONTH
742      * <li>DAY_OF_MONTH
743      * <li>DAY_OF_YEAR
744      * <li>EXTENDED_YEAR</ul>
745      * @stable ICU 2.0
746      */

747     protected void handleComputeFields(int julianDay) {
748         int eyear, month, dayOfMonth, dayOfYear;
749
750         if (julianDay >= cutoverJulianDay) {
751             month = getGregorianMonth();
752             dayOfMonth = getGregorianDayOfMonth();
753             dayOfYear = getGregorianDayOfYear();
754             eyear = getGregorianYear();
755         } else {
756             // The Julian epoch day (not the same as Julian Day)
757
// is zero on Saturday December 30, 0 (Gregorian).
758
long julianEpochDay = julianDay - (JAN_1_1_JULIAN_DAY - 2);
759             eyear = (int) floorDivide(4*julianEpochDay + 1464, 1461);
760             
761             // Compute the Julian calendar day number for January 1, eyear
762
long january1 = 365*(eyear-1) + floorDivide(eyear-1, 4);
763             dayOfYear = (int)(julianEpochDay - january1); // 0-based
764

765             // Julian leap years occurred historically every 4 years starting
766
// with 8 AD. Before 8 AD the spacing is irregular; every 3 years
767
// from 45 BC to 9 BC, and then none until 8 AD. However, we don't
768
// implement this historical detail; instead, we implement the
769
// computatinally cleaner proleptic calendar, which assumes
770
// consistent 4-year cycles throughout time.
771
boolean isLeap = ((eyear&0x3) == 0); // equiv. to (eyear%4 == 0)
772

773             // Common Julian/Gregorian calculation
774
int correction = 0;
775             int march1 = isLeap ? 60 : 59; // zero-based DOY for March 1
776
if (dayOfYear >= march1) {
777                 correction = isLeap ? 1 : 2;
778             }
779             month = (12 * (dayOfYear + correction) + 6) / 367; // zero-based month
780
dayOfMonth = dayOfYear - MONTH_COUNT[month][isLeap?3:2] + 1; // one-based DOM
781
++dayOfYear;
782         }
783         internalSet(MONTH, month);
784         internalSet(DAY_OF_MONTH, dayOfMonth);
785         internalSet(DAY_OF_YEAR, dayOfYear);
786         internalSet(EXTENDED_YEAR, eyear);
787         int era = AD;
788         if (eyear < 1) {
789             era = BC;
790             eyear = 1 - eyear;
791         }
792         internalSet(ERA, era);
793         internalSet(YEAR, eyear);
794     }
795
796 /////////////////////////////
797
// Fields => Time computation
798
/////////////////////////////
799

800     /**
801      * @stable ICU 2.0
802      */

803     protected int handleGetExtendedYear() {
804         int year;
805         if (newerField(EXTENDED_YEAR, YEAR) == EXTENDED_YEAR) {
806             year = internalGet(EXTENDED_YEAR, EPOCH_YEAR);
807         } else {
808             // The year defaults to the epoch start, the era to AD
809
int era = internalGet(ERA, AD);
810             if (era == BC) {
811                 year = 1 - internalGet(YEAR, 1); // Convert to extended year
812
} else {
813                 year = internalGet(YEAR, EPOCH_YEAR);
814             }
815         }
816         return year;
817     }
818
819     /**
820      * @stable ICU 2.0
821      */

822     protected int handleComputeJulianDay(int bestField) {
823
824         invertGregorian = false;
825
826         int jd = super.handleComputeJulianDay(bestField);
827
828         // The following check handles portions of the cutover year BEFORE the
829
// cutover itself happens.
830
if (isGregorian != (jd >= cutoverJulianDay)) {
831             invertGregorian = true;
832             jd = super.handleComputeJulianDay(bestField);
833         }
834         
835         return jd;
836     }
837
838     /**
839      * Return JD of start of given month/year
840      * @stable ICU 2.0
841      */

842     protected int handleComputeMonthStart(int eyear, int month, boolean useMonth) {
843
844         // If the month is out of range, adjust it into range, and
845
// modify the extended year value accordingly.
846
if (month < 0 || month > 11) {
847             int[] rem = new int[1];
848             eyear += floorDivide(month, 12, rem);
849             month = rem[0];
850         }
851
852         boolean isLeap = eyear%4 == 0;
853         int y = eyear - 1;
854         int julianDay = 365*y + floorDivide(y, 4) + (JAN_1_1_JULIAN_DAY - 3);
855
856         isGregorian = (eyear >= gregorianCutoverYear);
857         if (invertGregorian) {
858             isGregorian = !isGregorian;
859         }
860         if (isGregorian) {
861             isLeap = isLeap && ((eyear%100 != 0) || (eyear%400 == 0));
862             // Add 2 because Gregorian calendar starts 2 days after
863
// Julian calendar
864
julianDay += floorDivide(y, 400) - floorDivide(y, 100) + 2;
865         }
866
867         // At this point julianDay indicates the day BEFORE the first
868
// day of January 1, <eyear> of either the Julian or Gregorian
869
// calendar.
870

871         if (month != 0) {
872             julianDay += MONTH_COUNT[month][isLeap?3:2];
873         }
874
875         return julianDay;
876     }
877
878     /**
879      * Return the current Calendar type.
880      * @return type of calendar (gregorian, etc.)
881      * @internal ICU 3.0
882      * @deprecated This API is ICU internal only.
883      */

884     public String JavaDoc getType() {
885         return "gregorian";
886     }
887
888     /*
889     private static CalendarFactory factory;
890     public static CalendarFactory factory() {
891         if (factory == null) {
892             factory = new CalendarFactory() {
893                 public Calendar create(TimeZone tz, ULocale loc) {
894                     return new GregorianCalendar(tz, loc);
895                 }
896
897                 public String factoryName() {
898                     return "Gregorian";
899                 }
900             };
901         }
902         return factory;
903     }
904     */

905 }
906
Popular Tags