PR rtl-optimization/24762
[official-gcc.git] / libjava / java / util / GregorianCalendar.java
blobe7a961880cf034aea1ab8477a2b3a45d609b31aa
1 /* java.util.GregorianCalendar
2 Copyright (C) 1998, 1999, 2001, 2002, 2003, 2004
3 Free Software Foundation, Inc.
5 This file is part of GNU Classpath.
7 GNU Classpath is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Classpath is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Classpath; see the file COPYING. If not, write to the
19 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20 02110-1301 USA.
22 Linking this library statically or dynamically with other modules is
23 making a combined work based on this library. Thus, the terms and
24 conditions of the GNU General Public License cover the whole
25 combination.
27 As a special exception, the copyright holders of this library give you
28 permission to link this library with independent modules to produce an
29 executable, regardless of the license terms of these independent
30 modules, and to copy and distribute the resulting executable under
31 terms of your choice, provided that you also meet, for each linked
32 independent module, the terms and conditions of the license of that
33 module. An independent module is a module which is not derived from
34 or based on this library. If you modify this library, you may extend
35 this exception to your version of the library, but you are not
36 obligated to do so. If you do not wish to do so, delete this
37 exception statement from your version. */
40 package java.util;
43 /**
44 * <p>
45 * This class represents the Gregorian calendar, that is used in most
46 * countries all over the world. It does also handle the Julian calendar
47 * for dates smaller than the date of the change to the Gregorian calendar.
48 * The Gregorian calendar differs from the Julian calendar by a different
49 * leap year rule (no leap year every 100 years, except if year is divisible
50 * by 400).
51 * </p>
52 * <p>
53 * This change date is different from country to country, and can be changed with
54 * <code>setGregorianChange</code>. The first countries to adopt the Gregorian
55 * calendar did so on the 15th of October, 1582. This date followed October
56 * the 4th, 1582 in the Julian calendar system. The non-existant days that were
57 * omitted when the change took place are interpreted as Gregorian dates.
58 * </p>
59 * <p>
60 * Prior to the changeover date, New Year's Day occurred on the 25th of March.
61 * However, this class always takes New Year's Day as being the 1st of January.
62 * Client code should manually adapt the year value, if required, for dates
63 * between January the 1st and March the 24th in years prior to the changeover.
64 * </p>
65 * <p>
66 * Any date infinitely forwards or backwards in time can be represented by
67 * this class. A <em>proleptic</em> calendar system is used, which allows
68 * future dates to be created via the existing rules. This allows meaningful
69 * and consistent dates to be produced for all years. However, dates are only
70 * historically accurate following March the 1st, 4AD when the Julian calendar
71 * system was adopted. Prior to this, leap year rules were applied erraticly.
72 * </p>
73 * <p>
74 * There are two eras available for the Gregorian calendar, namely BC and AD.
75 * </p>
76 * <p>
77 * Weeks are defined as a period of seven days, beginning on the first day
78 * of the week, as returned by <code>getFirstDayOfWeek()</code>, and ending
79 * on the day prior to this.
80 * </p>
81 * <p>
82 * The weeks of the year are numbered from 1 to a possible 53. The first week
83 * of the year is defined as the first week that contains at least the minimum
84 * number of days of the first week in the new year (retrieved via
85 * <code>getMinimalDaysInFirstWeek()</code>). All weeks after this are numbered
86 * from 2 onwards.
87 * </p>
88 * <p>
89 * For example, take the year 2004. It began on a Thursday. The first week
90 * of 2004 depends both on where a week begins and how long it must minimally
91 * last. Let's say that the week begins on a Monday and must have a minimum
92 * of 5 days. In this case, the first week begins on Monday, the 5th of January.
93 * The first 4 days (Thursday to Sunday) are not eligible, as they are too few
94 * to make up the minimum number of days of the first week which must be in
95 * the new year. If the minimum was lowered to 4 days, then the first week
96 * would instead begin on Monday, the 29th of December, 2003. This first week
97 * has 4 of its days in the new year, and is now eligible.
98 * </p>
99 * <p>
100 * The weeks of the month are numbered from 0 to a possible 6. The first week
101 * of the month (numbered 1) is a set of days, prior to the first day of the week,
102 * which number at least the minimum number of days in a week. Unlike the first
103 * week of the year, the first week of the month only uses days from that particular
104 * month. As a consequence, it may have a variable number of days (from the minimum
105 * number required up to a full week of 7) and it need not start on the first day of
106 * the week. It must, however, be following by the first day of the week, as this
107 * marks the beginning of week 2. Any days of the month which occur prior to the
108 * first week (because the first day of the week occurs before the minimum number
109 * of days is met) are seen as week 0.
110 * </p>
111 * <p>
112 * Again, we will take the example of the year 2004 to demonstrate this. September
113 * 2004 begins on a Wednesday. Taking our first day of the week as Monday, and the
114 * minimum length of the first week as 6, we find that week 1 runs from Monday,
115 * the 6th of September to Sunday the 12th. Prior to the 6th, there are only
116 * 5 days (Wednesday through to Sunday). This is too small a number to meet the
117 * minimum, so these are classed as being days in week 0. Week 2 begins on the
118 * 13th, and so on. This changes if we reduce the minimum to 5. In this case,
119 * week 1 is a truncated week from Wednesday the 1st to Sunday the 5th, and week
120 * 0 doesn't exist. The first seven day week is week 2, starting on the 6th.
121 * </p>
122 * <p>
123 * On using the <code>clear()</code> method, the Gregorian calendar returns
124 * to its default value of the 1st of January, 1970 AD 00:00:00 (the epoch).
125 * The day of the week is set to the correct day for that particular time.
126 * The day is also the first of the month, and the date is in week 0.
127 * </p>
129 * @see Calendar
130 * @see TimeZone
131 * @see Calendar#getFirstDayOfWeek()
132 * @see Calendar#getMinimalDaysInFirstWeek()
134 public class GregorianCalendar extends Calendar
137 * Constant representing the era BC (Before Christ).
139 public static final int BC = 0;
142 * Constant representing the era AD (Anno Domini).
144 public static final int AD = 1;
147 * The point at which the Gregorian calendar rules were used.
148 * This is locale dependent; the default for most catholic
149 * countries is midnight (UTC) on October 5, 1582 (Julian),
150 * or October 15, 1582 (Gregorian).
152 * @serial the changeover point from the Julian calendar
153 * system to the Gregorian.
155 private long gregorianCutover;
158 * For compatability with Sun's JDK.
160 static final long serialVersionUID = -8125100834729963327L;
163 * The name of the resource bundle. Used only by getBundle()
165 private static final String bundleName = "gnu.java.locale.Calendar";
168 * Days in the epoch. Relative Jan 1, year '0' which is not a leap year.
169 * (although there is no year zero, this does not matter.)
170 * This is consistent with the formula:
171 * = (year-1)*365L + ((year-1) >> 2)
173 * Plus the gregorian correction:
174 * Math.floor((year-1) / 400.) - Math.floor((year-1) / 100.);
175 * For a correct julian date, the correction is -2 instead.
177 * The gregorian cutover in 1582 was 10 days, so by calculating the
178 * correction from year zero, we have 15 non-leap days (even centuries)
179 * minus 3 leap days (year 400,800,1200) = 12. Subtracting two corrects
180 * this to the correct number 10.
182 private static final int EPOCH_DAYS = 719162;
185 * Constructs a new GregorianCalender representing the current
186 * time, using the default time zone and the default locale.
188 public GregorianCalendar()
190 this(TimeZone.getDefault(), Locale.getDefault());
194 * Constructs a new GregorianCalender representing the current
195 * time, using the specified time zone and the default locale.
197 * @param zone a time zone.
199 public GregorianCalendar(TimeZone zone)
201 this(zone, Locale.getDefault());
205 * Constructs a new GregorianCalender representing the current
206 * time, using the default time zone and the specified locale.
208 * @param locale a locale.
210 public GregorianCalendar(Locale locale)
212 this(TimeZone.getDefault(), locale);
216 * Constructs a new GregorianCalender representing the current
217 * time with the given time zone and the given locale.
219 * @param zone a time zone.
220 * @param locale a locale.
222 public GregorianCalendar(TimeZone zone, Locale locale)
224 this(zone, locale, false);
225 setTimeInMillis(System.currentTimeMillis());
226 complete();
230 * Common constructor that all constructors should call.
231 * @param zone a time zone.
232 * @param locale a locale.
233 * @param unused unused parameter to make the signature differ from
234 * the public constructor (TimeZone, Locale).
236 private GregorianCalendar(TimeZone zone, Locale locale, boolean unused)
238 super(zone, locale);
239 ResourceBundle rb = ResourceBundle.getBundle(bundleName, locale,
240 ClassLoader
241 .getSystemClassLoader());
242 gregorianCutover = ((Date) rb.getObject("gregorianCutOver")).getTime();
246 * Constructs a new GregorianCalendar representing midnight on the
247 * given date with the default time zone and locale.
248 * @param year corresponds to the YEAR time field.
249 * @param month corresponds to the MONTH time field.
250 * @param day corresponds to the DAY time field.
252 public GregorianCalendar(int year, int month, int day)
254 this(TimeZone.getDefault(), Locale.getDefault(), false);
255 set(year, month, day);
259 * Constructs a new GregorianCalendar representing midnight on the
260 * given date with the default time zone and locale.
262 * @param year corresponds to the YEAR time field.
263 * @param month corresponds to the MONTH time field.
264 * @param day corresponds to the DAY time field.
265 * @param hour corresponds to the HOUR_OF_DAY time field.
266 * @param minute corresponds to the MINUTE time field.
268 public GregorianCalendar(int year, int month, int day, int hour, int minute)
270 this(TimeZone.getDefault(), Locale.getDefault(), false);
271 set(year, month, day, hour, minute);
275 * Constructs a new GregorianCalendar representing midnight on the
276 * given date with the default time zone and locale.
278 * @param year corresponds to the YEAR time field.
279 * @param month corresponds to the MONTH time field.
280 * @param day corresponds to the DAY time field.
281 * @param hour corresponds to the HOUR_OF_DAY time field.
282 * @param minute corresponds to the MINUTE time field.
283 * @param second corresponds to the SECOND time field.
285 public GregorianCalendar(int year, int month, int day, int hour, int minute,
286 int second)
288 this(TimeZone.getDefault(), Locale.getDefault(), false);
289 set(year, month, day, hour, minute, second);
293 * Sets the date of the switch from Julian dates to Gregorian dates.
294 * You can use <code>new Date(Long.MAX_VALUE)</code> to use a pure
295 * Julian calendar, or <code>Long.MIN_VALUE</code> for a pure Gregorian
296 * calendar.
298 * @param date the date of the change.
300 public void setGregorianChange(Date date)
302 gregorianCutover = date.getTime();
306 * Gets the date of the switch from Julian dates to Gregorian dates.
308 * @return the date of the change.
310 public final Date getGregorianChange()
312 return new Date(gregorianCutover);
316 * <p>
317 * Determines if the given year is a leap year. The result is
318 * undefined if the Gregorian change took place in 1800, so that
319 * the end of February is skipped, and that year is specified.
320 * (well...).
321 * </p>
322 * <p>
323 * To specify a year in the BC era, use a negative value calculated
324 * as 1 - y, where y is the required year in BC. So, 1 BC is 0,
325 * 2 BC is -1, 3 BC is -2, etc.
326 * </p>
328 * @param year a year (use a negative value for BC).
329 * @return true, if the given year is a leap year, false otherwise.
331 public boolean isLeapYear(int year)
333 // Only years divisible by 4 can be leap years
334 if ((year & 3) != 0)
335 return false;
337 // Is the leap-day a Julian date? Then it's a leap year
338 if (! isGregorian(year, 31 + 29 - 1))
339 return true;
341 // Apply gregorian rules otherwise
342 return ((year % 100) != 0 || (year % 400) == 0);
346 * Retrieves the day of the week corresponding to the specified
347 * day of the specified year.
349 * @param year the year in which the dayOfYear occurs.
350 * @param dayOfYear the day of the year (an integer between 0 and
351 * and 366)
353 private int getWeekDay(int year, int dayOfYear)
355 boolean greg = isGregorian(year, dayOfYear);
356 int day = (int) getLinearDay(year, dayOfYear, greg);
358 // The epoch was a thursday.
359 int weekday = (day + THURSDAY) % 7;
360 if (weekday <= 0)
361 weekday += 7;
362 return weekday;
366 * Returns the day of the week for the first day of a given month (0..11)
368 private int getFirstDayOfMonth(int year, int month)
370 int[] dayCount = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
372 if (month > 11)
374 year += (month / 12);
375 month = month % 12;
378 if (month < 0)
380 year += (int) month / 12;
381 month = month % 12;
382 if (month < 0)
384 month += 12;
385 year--;
389 int dayOfYear = dayCount[month] + 1;
390 if (month > 1)
391 if (isLeapYear(year))
392 dayOfYear++;
394 boolean greg = isGregorian(year, dayOfYear);
395 int day = (int) getLinearDay(year, dayOfYear, greg);
397 // The epoch was a thursday.
398 int weekday = (day + THURSDAY) % 7;
399 if (weekday <= 0)
400 weekday += 7;
401 return weekday;
405 * Takes a year, and a (zero based) day of year and determines
406 * if it is gregorian or not.
408 private boolean isGregorian(int year, int dayOfYear)
410 int relativeDay = (year - 1) * 365 + ((year - 1) >> 2) + dayOfYear
411 - EPOCH_DAYS; // gregorian days from 1 to epoch.
412 int gregFactor = (int) Math.floor((double) (year - 1) / 400.)
413 - (int) Math.floor((double) (year - 1) / 100.);
415 return ((relativeDay + gregFactor) * 60L * 60L * 24L * 1000L >= gregorianCutover);
419 * Check set fields for validity, without leniency.
421 * @throws IllegalArgumentException if a field is invalid
423 private void nonLeniencyCheck() throws IllegalArgumentException
425 int[] month_days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
426 int year = fields[YEAR];
427 int month = fields[MONTH];
428 int leap = isLeapYear(year) ? 1 : 0;
430 if (isSet[ERA] && fields[ERA] != AD && fields[ERA] != BC)
431 throw new IllegalArgumentException("Illegal ERA.");
432 if (isSet[YEAR] && fields[YEAR] < 1)
433 throw new IllegalArgumentException("Illegal YEAR.");
434 if (isSet[MONTH] && (month < 0 || month > 11))
435 throw new IllegalArgumentException("Illegal MONTH.");
436 if (isSet[WEEK_OF_YEAR])
438 int daysInYear = 365 + leap;
439 daysInYear += (getFirstDayOfMonth(year, 0) - 1); // pad first week
440 int last = getFirstDayOfMonth(year, 11) + 4;
441 if (last > 7)
442 last -= 7;
443 daysInYear += 7 - last;
444 int weeks = daysInYear / 7;
445 if (fields[WEEK_OF_YEAR] < 1 || fields[WEEK_OF_YEAR] > weeks)
446 throw new IllegalArgumentException("Illegal WEEK_OF_YEAR.");
449 if (isSet[WEEK_OF_MONTH])
451 int weeks = (month == 1 && leap == 0) ? 4 : 5;
452 if (fields[WEEK_OF_MONTH] < 1 || fields[WEEK_OF_MONTH] > weeks)
453 throw new IllegalArgumentException("Illegal WEEK_OF_MONTH.");
456 if (isSet[DAY_OF_MONTH])
457 if (fields[DAY_OF_MONTH] < 1
458 || fields[DAY_OF_MONTH] > month_days[month]
459 + ((month == 1) ? leap : 0))
460 throw new IllegalArgumentException("Illegal DAY_OF_MONTH.");
462 if (isSet[DAY_OF_YEAR]
463 && (fields[DAY_OF_YEAR] < 1 || fields[DAY_OF_YEAR] > 365 + leap))
464 throw new IllegalArgumentException("Illegal DAY_OF_YEAR.");
466 if (isSet[DAY_OF_WEEK]
467 && (fields[DAY_OF_WEEK] < 1 || fields[DAY_OF_WEEK] > 7))
468 throw new IllegalArgumentException("Illegal DAY_OF_WEEK.");
470 if (isSet[DAY_OF_WEEK_IN_MONTH])
472 int weeks = (month == 1 && leap == 0) ? 4 : 5;
473 if (fields[DAY_OF_WEEK_IN_MONTH] < -weeks
474 || fields[DAY_OF_WEEK_IN_MONTH] > weeks)
475 throw new IllegalArgumentException("Illegal DAY_OF_WEEK_IN_MONTH.");
478 if (isSet[AM_PM] && fields[AM_PM] != AM && fields[AM_PM] != PM)
479 throw new IllegalArgumentException("Illegal AM_PM.");
480 if (isSet[HOUR] && (fields[HOUR] < 0 || fields[HOUR] > 11))
481 throw new IllegalArgumentException("Illegal HOUR.");
482 if (isSet[HOUR_OF_DAY]
483 && (fields[HOUR_OF_DAY] < 0 || fields[HOUR_OF_DAY] > 23))
484 throw new IllegalArgumentException("Illegal HOUR_OF_DAY.");
485 if (isSet[MINUTE] && (fields[MINUTE] < 0 || fields[MINUTE] > 59))
486 throw new IllegalArgumentException("Illegal MINUTE.");
487 if (isSet[SECOND] && (fields[SECOND] < 0 || fields[SECOND] > 59))
488 throw new IllegalArgumentException("Illegal SECOND.");
489 if (isSet[MILLISECOND]
490 && (fields[MILLISECOND] < 0 || fields[MILLISECOND] > 999))
491 throw new IllegalArgumentException("Illegal MILLISECOND.");
492 if (isSet[ZONE_OFFSET]
493 && (fields[ZONE_OFFSET] < -12 * 60 * 60 * 1000L
494 || fields[ZONE_OFFSET] > 12 * 60 * 60 * 1000L))
495 throw new IllegalArgumentException("Illegal ZONE_OFFSET.");
496 if (isSet[DST_OFFSET]
497 && (fields[DST_OFFSET] < -12 * 60 * 60 * 1000L
498 || fields[DST_OFFSET] > 12 * 60 * 60 * 1000L))
499 throw new IllegalArgumentException("Illegal DST_OFFSET.");
503 * Converts the time field values (<code>fields</code>) to
504 * milliseconds since the epoch UTC (<code>time</code>).
506 * @throws IllegalArgumentException if any calendar fields
507 * are invalid.
509 protected synchronized void computeTime()
511 int millisInDay = 0;
512 int era = fields[ERA];
513 int year = fields[YEAR];
514 int month = fields[MONTH];
515 int day = fields[DAY_OF_MONTH];
517 int minute = fields[MINUTE];
518 int second = fields[SECOND];
519 int millis = fields[MILLISECOND];
520 int[] month_days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
521 int[] dayCount = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
522 int hour = 0;
524 if (! isLenient())
525 nonLeniencyCheck();
527 if (! isSet[MONTH] && (! isSet[DAY_OF_WEEK] || isSet[WEEK_OF_YEAR]))
529 // 5: YEAR + DAY_OF_WEEK + WEEK_OF_YEAR
530 if (isSet[WEEK_OF_YEAR])
532 int first = getFirstDayOfMonth(year, 0);
533 int offs = 1;
534 int daysInFirstWeek = getFirstDayOfWeek() - first;
535 if (daysInFirstWeek <= 0)
536 daysInFirstWeek += 7;
538 if (daysInFirstWeek < getMinimalDaysInFirstWeek())
539 offs += daysInFirstWeek;
540 else
541 offs -= 7 - daysInFirstWeek;
542 month = 0;
543 day = offs + 7 * (fields[WEEK_OF_YEAR] - 1);
544 offs = fields[DAY_OF_WEEK] - getFirstDayOfWeek();
546 if (offs < 0)
547 offs += 7;
548 day += offs;
550 else
552 // 4: YEAR + DAY_OF_YEAR
553 month = 0;
554 day = fields[DAY_OF_YEAR];
557 else
559 if (isSet[DAY_OF_WEEK])
561 int first = getFirstDayOfMonth(year, month);
563 // 3: YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
564 if (isSet[DAY_OF_WEEK_IN_MONTH])
566 if (fields[DAY_OF_WEEK_IN_MONTH] < 0)
568 month++;
569 first = getFirstDayOfMonth(year, month);
570 day = 1 + 7 * (fields[DAY_OF_WEEK_IN_MONTH]);
572 else
573 day = 1 + 7 * (fields[DAY_OF_WEEK_IN_MONTH] - 1);
575 int offs = fields[DAY_OF_WEEK] - first;
576 if (offs < 0)
577 offs += 7;
578 day += offs;
580 else
581 { // 2: YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
582 int offs = 1;
583 int daysInFirstWeek = getFirstDayOfWeek() - first;
584 if (daysInFirstWeek <= 0)
585 daysInFirstWeek += 7;
587 if (daysInFirstWeek < getMinimalDaysInFirstWeek())
588 offs += daysInFirstWeek;
589 else
590 offs -= 7 - daysInFirstWeek;
592 day = offs + 7 * (fields[WEEK_OF_MONTH] - 1);
593 offs = fields[DAY_OF_WEEK] - getFirstDayOfWeek();
594 if (offs <= 0)
595 offs += 7;
596 day += offs;
600 // 1: YEAR + MONTH + DAY_OF_MONTH
602 if (era == BC && year > 0)
603 year = 1 - year;
605 // rest of code assumes day/month/year set
606 // should negative BC years be AD?
607 // get the hour (but no check for validity)
608 if (isSet[HOUR])
610 hour = fields[HOUR];
611 if (fields[AM_PM] == PM)
612 hour += 12;
614 else
615 hour = fields[HOUR_OF_DAY];
617 // Read the era,year,month,day fields and convert as appropriate.
618 // Calculate number of milliseconds into the day
619 // This takes care of both h, m, s, ms over/underflows.
620 long allMillis = (((hour * 60L) + minute) * 60L + second) * 1000L + millis;
621 day += allMillis / (24 * 60 * 60 * 1000L);
622 millisInDay = (int) (allMillis % (24 * 60 * 60 * 1000L));
624 if (month < 0)
626 year += (int) month / 12;
627 month = month % 12;
628 if (month < 0)
630 month += 12;
631 year--;
634 if (month > 11)
636 year += (month / 12);
637 month = month % 12;
640 month_days[1] = isLeapYear(year) ? 29 : 28;
642 while (day <= 0)
644 if (month == 0)
646 year--;
647 month_days[1] = isLeapYear(year) ? 29 : 28;
649 month = (month + 11) % 12;
650 day += month_days[month];
652 while (day > month_days[month])
654 day -= (month_days[month]);
655 month = (month + 1) % 12;
656 if (month == 0)
658 year++;
659 month_days[1] = isLeapYear(year) ? 29 : 28;
663 // ok, by here we have valid day,month,year,era and millisinday
664 int dayOfYear = dayCount[month] + day - 1; // (day starts on 1)
665 if (isLeapYear(year) && month > 1)
666 dayOfYear++;
668 int relativeDay = (year - 1) * 365 + ((year - 1) >> 2) + dayOfYear
669 - EPOCH_DAYS; // gregorian days from 1 to epoch.
670 int gregFactor = (int) Math.floor((double) (year - 1) / 400.)
671 - (int) Math.floor((double) (year - 1) / 100.);
673 if ((relativeDay + gregFactor) * 60L * 60L * 24L * 1000L >= gregorianCutover)
674 relativeDay += gregFactor;
675 else
676 relativeDay -= 2;
678 time = relativeDay * (24 * 60 * 60 * 1000L) + millisInDay;
680 // the epoch was a Thursday.
681 int weekday = (int) (relativeDay + THURSDAY) % 7;
682 if (weekday <= 0)
683 weekday += 7;
684 fields[DAY_OF_WEEK] = weekday;
686 // Time zone corrections.
687 TimeZone zone = getTimeZone();
688 int rawOffset = isSet[ZONE_OFFSET] ? fields[ZONE_OFFSET]
689 : zone.getRawOffset();
691 int dstOffset = isSet[DST_OFFSET] ? fields[DST_OFFSET]
692 : (zone.getOffset((year < 0) ? BC : AD,
693 (year < 0) ? 1 - year
694 : year,
695 month, day, weekday,
696 millisInDay)
697 - zone.getRawOffset());
699 time -= rawOffset + dstOffset;
701 isTimeSet = true;
705 * Get the linear day in days since the epoch, using the
706 * Julian or Gregorian calendar as specified. If you specify a
707 * nonpositive year it is interpreted as BC as following: 0 is 1
708 * BC, -1 is 2 BC and so on.
710 * @param year the year of the date.
711 * @param dayOfYear the day of year of the date; 1 based.
712 * @param gregorian <code>true</code>, if we should use the Gregorian rules.
713 * @return the days since the epoch, may be negative.
715 private long getLinearDay(int year, int dayOfYear, boolean gregorian)
717 // The 13 is the number of days, that were omitted in the Gregorian
718 // Calender until the epoch.
719 // We shift right by 2 instead of dividing by 4, to get correct
720 // results for negative years (and this is even more efficient).
721 long julianDay = (year - 1) * 365L + ((year - 1) >> 2) + (dayOfYear - 1)
722 - EPOCH_DAYS; // gregorian days from 1 to epoch.
724 if (gregorian)
726 // subtract the days that are missing in gregorian calendar
727 // with respect to julian calendar.
729 // Okay, here we rely on the fact that the gregorian
730 // calendar was introduced in the AD era. This doesn't work
731 // with negative years.
733 // The additional leap year factor accounts for the fact that
734 // a leap day is not seen on Jan 1 of the leap year.
735 int gregOffset = (int) Math.floor((double) (year - 1) / 400.)
736 - (int) Math.floor((double) (year - 1) / 100.);
738 return julianDay + gregOffset;
740 else
741 julianDay -= 2;
742 return julianDay;
746 * Converts the given linear day into era, year, month,
747 * day_of_year, day_of_month, day_of_week, and writes the result
748 * into the fields array.
750 * @param day the linear day.
751 * @param gregorian true, if we should use Gregorian rules.
753 private void calculateDay(int[] fields, long day, boolean gregorian)
755 // the epoch was a Thursday.
756 int weekday = (int) (day + THURSDAY) % 7;
757 if (weekday <= 0)
758 weekday += 7;
759 fields[DAY_OF_WEEK] = weekday;
761 // get a first approximation of the year. This may be one
762 // year too big.
763 int year = 1970
764 + (int) (gregorian
765 ? ((day - 100L) * 400L) / (365L * 400L + 100L - 4L
766 + 1L) : ((day - 100L) * 4L) / (365L * 4L + 1L));
767 if (day >= 0)
768 year++;
770 long firstDayOfYear = getLinearDay(year, 1, gregorian);
772 // Now look in which year day really lies.
773 if (day < firstDayOfYear)
775 year--;
776 firstDayOfYear = getLinearDay(year, 1, gregorian);
779 day -= firstDayOfYear - 1; // day of year, one based.
781 fields[DAY_OF_YEAR] = (int) day;
782 if (year <= 0)
784 fields[ERA] = BC;
785 fields[YEAR] = 1 - year;
787 else
789 fields[ERA] = AD;
790 fields[YEAR] = year;
793 int leapday = isLeapYear(year) ? 1 : 0;
794 if (day <= 31 + 28 + leapday)
796 fields[MONTH] = (int) day / 32; // 31->JANUARY, 32->FEBRUARY
797 fields[DAY_OF_MONTH] = (int) day - 31 * fields[MONTH];
799 else
801 // A few more magic formulas
802 int scaledDay = ((int) day - leapday) * 5 + 8;
803 fields[MONTH] = scaledDay / (31 + 30 + 31 + 30 + 31);
804 fields[DAY_OF_MONTH] = (scaledDay % (31 + 30 + 31 + 30 + 31)) / 5 + 1;
809 * Converts the milliseconds since the epoch UTC
810 * (<code>time</code>) to time fields
811 * (<code>fields</code>).
813 protected synchronized void computeFields()
815 boolean gregorian = (time >= gregorianCutover);
817 TimeZone zone = getTimeZone();
818 fields[ZONE_OFFSET] = zone.getRawOffset();
819 long localTime = time + fields[ZONE_OFFSET];
821 long day = localTime / (24 * 60 * 60 * 1000L);
822 int millisInDay = (int) (localTime % (24 * 60 * 60 * 1000L));
824 if (millisInDay < 0)
826 millisInDay += (24 * 60 * 60 * 1000);
827 day--;
830 calculateDay(fields, day, gregorian);
831 fields[DST_OFFSET] = zone.getOffset(fields[ERA], fields[YEAR],
832 fields[MONTH], fields[DAY_OF_MONTH],
833 fields[DAY_OF_WEEK], millisInDay)
834 - fields[ZONE_OFFSET];
836 millisInDay += fields[DST_OFFSET];
837 if (millisInDay >= 24 * 60 * 60 * 1000)
839 millisInDay -= 24 * 60 * 60 * 1000;
840 calculateDay(fields, ++day, gregorian);
843 fields[DAY_OF_WEEK_IN_MONTH] = (fields[DAY_OF_MONTH] + 6) / 7;
845 // which day of the week are we (0..6), relative to getFirstDayOfWeek
846 int relativeWeekday = (7 + fields[DAY_OF_WEEK] - getFirstDayOfWeek()) % 7;
848 fields[WEEK_OF_MONTH] = (fields[DAY_OF_MONTH] - relativeWeekday + 12) / 7;
850 int weekOfYear = (fields[DAY_OF_YEAR] - relativeWeekday + 6) / 7;
852 // Do the Correction: getMinimalDaysInFirstWeek() is always in the
853 // first week.
854 int minDays = getMinimalDaysInFirstWeek();
855 int firstWeekday = (7 + getWeekDay(fields[YEAR], minDays)
856 - getFirstDayOfWeek()) % 7;
857 if (minDays - firstWeekday < 1)
858 weekOfYear++;
859 fields[WEEK_OF_YEAR] = weekOfYear;
861 int hourOfDay = millisInDay / (60 * 60 * 1000);
862 fields[AM_PM] = (hourOfDay < 12) ? AM : PM;
863 int hour = hourOfDay % 12;
864 fields[HOUR] = hour;
865 fields[HOUR_OF_DAY] = hourOfDay;
866 millisInDay %= (60 * 60 * 1000);
867 fields[MINUTE] = millisInDay / (60 * 1000);
868 millisInDay %= (60 * 1000);
869 fields[SECOND] = millisInDay / (1000);
870 fields[MILLISECOND] = millisInDay % 1000;
872 areFieldsSet = isSet[ERA] = isSet[YEAR] = isSet[MONTH] = isSet[WEEK_OF_YEAR] = isSet[WEEK_OF_MONTH] = isSet[DAY_OF_MONTH] = isSet[DAY_OF_YEAR] = isSet[DAY_OF_WEEK] = isSet[DAY_OF_WEEK_IN_MONTH] = isSet[AM_PM] = isSet[HOUR] = isSet[HOUR_OF_DAY] = isSet[MINUTE] = isSet[SECOND] = isSet[MILLISECOND] = isSet[ZONE_OFFSET] = isSet[DST_OFFSET] = true;
876 * Compares the given calendar with this. An object, o, is
877 * equivalent to this if it is also a <code>GregorianCalendar</code>
878 * with the same time since the epoch under the same conditions
879 * (same change date and same time zone).
881 * @param o the object to that we should compare.
882 * @return true, if the given object is a calendar, that represents
883 * the same time (but doesn't necessarily have the same fields).
884 * @throws IllegalArgumentException if one of the fields
885 * <code>ZONE_OFFSET</code> or <code>DST_OFFSET</code> is
886 * specified, if an unknown field is specified or if one
887 * of the calendar fields receives an illegal value when
888 * leniancy is not enabled.
890 public boolean equals(Object o)
892 if (! (o instanceof GregorianCalendar))
893 return false;
895 GregorianCalendar cal = (GregorianCalendar) o;
896 return (cal.getTimeInMillis() == getTimeInMillis());
900 * Adds the specified amount of time to the given time field. The
901 * amount may be negative to subtract the time. If the field overflows
902 * it does what you expect: Jan, 25 + 10 Days is Feb, 4.
903 * @param field one of the time field constants.
904 * @param amount the amount of time to add.
905 * @exception IllegalArgumentException if <code>field</code> is
906 * <code>ZONE_OFFSET</code>, <code>DST_OFFSET</code>, or invalid; or
907 * if <code>amount</code> contains an out-of-range value and the calendar
908 * is not in lenient mode.
910 public void add(int field, int amount)
912 switch (field)
914 case YEAR:
915 complete();
916 fields[YEAR] += amount;
917 isTimeSet = false;
918 break;
919 case MONTH:
920 complete();
921 int months = fields[MONTH] + amount;
922 fields[YEAR] += months / 12;
923 fields[MONTH] = months % 12;
924 if (fields[MONTH] < 0)
926 fields[MONTH] += 12;
927 fields[YEAR]--;
929 int maxDay = getActualMaximum(DAY_OF_MONTH);
930 if (fields[DAY_OF_MONTH] > maxDay)
931 fields[DAY_OF_MONTH] = maxDay;
932 set(YEAR, fields[YEAR]);
933 set(MONTH, fields[MONTH]);
934 break;
935 case DAY_OF_MONTH:
936 case DAY_OF_YEAR:
937 case DAY_OF_WEEK:
938 if (! isTimeSet)
939 computeTime();
940 time += amount * (24 * 60 * 60 * 1000L);
941 areFieldsSet = false;
942 break;
943 case WEEK_OF_YEAR:
944 case WEEK_OF_MONTH:
945 case DAY_OF_WEEK_IN_MONTH:
946 if (! isTimeSet)
947 computeTime();
948 time += amount * (7 * 24 * 60 * 60 * 1000L);
949 areFieldsSet = false;
950 break;
951 case AM_PM:
952 if (! isTimeSet)
953 computeTime();
954 time += amount * (12 * 60 * 60 * 1000L);
955 areFieldsSet = false;
956 break;
957 case HOUR:
958 case HOUR_OF_DAY:
959 if (! isTimeSet)
960 computeTime();
961 time += amount * (60 * 60 * 1000L);
962 areFieldsSet = false;
963 break;
964 case MINUTE:
965 if (! isTimeSet)
966 computeTime();
967 time += amount * (60 * 1000L);
968 areFieldsSet = false;
969 break;
970 case SECOND:
971 if (! isTimeSet)
972 computeTime();
973 time += amount * (1000L);
974 areFieldsSet = false;
975 break;
976 case MILLISECOND:
977 if (! isTimeSet)
978 computeTime();
979 time += amount;
980 areFieldsSet = false;
981 break;
982 case ZONE_OFFSET:
983 case DST_OFFSET:default:
984 throw new IllegalArgumentException("Invalid or unknown field");
989 * Rolls the specified time field up or down. This means add one
990 * to the specified field, but don't change the other fields. If
991 * the maximum for this field is reached, start over with the
992 * minimum value.
994 * <strong>Note:</strong> There may be situation, where the other
995 * fields must be changed, e.g rolling the month on May, 31.
996 * The date June, 31 is automatically converted to July, 1.
997 * This requires lenient settings.
999 * @param field the time field. One of the time field constants.
1000 * @param up the direction, true for up, false for down.
1001 * @throws IllegalArgumentException if one of the fields
1002 * <code>ZONE_OFFSET</code> or <code>DST_OFFSET</code> is
1003 * specified, if an unknown field is specified or if one
1004 * of the calendar fields receives an illegal value when
1005 * leniancy is not enabled.
1007 public void roll(int field, boolean up)
1009 roll(field, up ? 1 : -1);
1013 * Checks that the fields are still within their legal bounds,
1014 * following use of the <code>roll()</code> method.
1016 * @param field the field to check.
1017 * @param delta multipler for alterations to the <code>time</code>.
1018 * @see #roll(int, boolean)
1019 * @see #roll(int, int)
1021 private void cleanUpAfterRoll(int field, int delta)
1023 switch (field)
1025 case ERA:
1026 case YEAR:
1027 case MONTH:
1028 // check that day of month is still in correct range
1029 if (fields[DAY_OF_MONTH] > getActualMaximum(DAY_OF_MONTH))
1030 fields[DAY_OF_MONTH] = getActualMaximum(DAY_OF_MONTH);
1031 isTimeSet = false;
1032 isSet[WEEK_OF_MONTH] = false;
1033 isSet[DAY_OF_WEEK] = false;
1034 isSet[DAY_OF_WEEK_IN_MONTH] = false;
1035 isSet[DAY_OF_YEAR] = false;
1036 isSet[WEEK_OF_YEAR] = false;
1037 break;
1038 case DAY_OF_MONTH:
1039 isSet[WEEK_OF_MONTH] = false;
1040 isSet[DAY_OF_WEEK] = false;
1041 isSet[DAY_OF_WEEK_IN_MONTH] = false;
1042 isSet[DAY_OF_YEAR] = false;
1043 isSet[WEEK_OF_YEAR] = false;
1044 time += delta * (24 * 60 * 60 * 1000L);
1045 break;
1046 case WEEK_OF_MONTH:
1047 isSet[DAY_OF_MONTH] = false;
1048 isSet[DAY_OF_WEEK_IN_MONTH] = false;
1049 isSet[DAY_OF_YEAR] = false;
1050 isSet[WEEK_OF_YEAR] = false;
1051 time += delta * (7 * 24 * 60 * 60 * 1000L);
1052 break;
1053 case DAY_OF_WEEK_IN_MONTH:
1054 isSet[DAY_OF_MONTH] = false;
1055 isSet[WEEK_OF_MONTH] = false;
1056 isSet[DAY_OF_YEAR] = false;
1057 isSet[WEEK_OF_YEAR] = false;
1058 time += delta * (7 * 24 * 60 * 60 * 1000L);
1059 break;
1060 case DAY_OF_YEAR:
1061 isSet[MONTH] = false;
1062 isSet[DAY_OF_MONTH] = false;
1063 isSet[WEEK_OF_MONTH] = false;
1064 isSet[DAY_OF_WEEK_IN_MONTH] = false;
1065 isSet[DAY_OF_WEEK] = false;
1066 isSet[WEEK_OF_YEAR] = false;
1067 time += delta * (24 * 60 * 60 * 1000L);
1068 break;
1069 case WEEK_OF_YEAR:
1070 isSet[MONTH] = false;
1071 isSet[DAY_OF_MONTH] = false;
1072 isSet[WEEK_OF_MONTH] = false;
1073 isSet[DAY_OF_WEEK_IN_MONTH] = false;
1074 isSet[DAY_OF_YEAR] = false;
1075 time += delta * (7 * 24 * 60 * 60 * 1000L);
1076 break;
1077 case AM_PM:
1078 isSet[HOUR_OF_DAY] = false;
1079 time += delta * (12 * 60 * 60 * 1000L);
1080 break;
1081 case HOUR:
1082 isSet[HOUR_OF_DAY] = false;
1083 time += delta * (60 * 60 * 1000L);
1084 break;
1085 case HOUR_OF_DAY:
1086 isSet[HOUR] = false;
1087 isSet[AM_PM] = false;
1088 time += delta * (60 * 60 * 1000L);
1089 break;
1090 case MINUTE:
1091 time += delta * (60 * 1000L);
1092 break;
1093 case SECOND:
1094 time += delta * (1000L);
1095 break;
1096 case MILLISECOND:
1097 time += delta;
1098 break;
1103 * Rolls the specified time field by the given amount. This means
1104 * add amount to the specified field, but don't change the other
1105 * fields. If the maximum for this field is reached, start over
1106 * with the minimum value and vice versa for negative amounts.
1108 * <strong>Note:</strong> There may be situation, where the other
1109 * fields must be changed, e.g rolling the month on May, 31.
1110 * The date June, 31 is automatically corrected to June, 30.
1112 * @param field the time field. One of the time field constants.
1113 * @param amount the amount by which we should roll.
1114 * @throws IllegalArgumentException if one of the fields
1115 * <code>ZONE_OFFSET</code> or <code>DST_OFFSET</code> is
1116 * specified, if an unknown field is specified or if one
1117 * of the calendar fields receives an illegal value when
1118 * leniancy is not enabled.
1120 public void roll(int field, int amount)
1122 switch (field)
1124 case DAY_OF_WEEK:
1125 // day of week is special: it rolls automatically
1126 add(field, amount);
1127 return;
1128 case ZONE_OFFSET:
1129 case DST_OFFSET:
1130 throw new IllegalArgumentException("Can't roll time zone");
1132 complete();
1133 int min = getActualMinimum(field);
1134 int range = getActualMaximum(field) - min + 1;
1135 int oldval = fields[field];
1136 int newval = (oldval - min + range + amount) % range + min;
1137 if (newval < min)
1138 newval += range;
1139 fields[field] = newval;
1140 cleanUpAfterRoll(field, newval - oldval);
1144 * The minimum values for the calendar fields.
1146 private static final int[] minimums =
1148 BC, 1, 0, 0, 1, 1, 1, SUNDAY, 1, AM,
1149 1, 0, 0, 0, 0, -(12 * 60 * 60 * 1000),
1154 * The maximum values for the calendar fields.
1156 private static final int[] maximums =
1158 AD, 5000000, 11, 53, 5, 31, 366,
1159 SATURDAY, 5, PM, 12, 23, 59, 59, 999,
1160 +(12 * 60 * 60 * 1000),
1161 (12 * 60 * 60 * 1000)
1165 * Gets the smallest value that is allowed for the specified field.
1167 * @param field one of the time field constants.
1168 * @return the smallest value for the specified field.
1170 public int getMinimum(int field)
1172 return minimums[field];
1176 * Gets the biggest value that is allowed for the specified field.
1178 * @param field one of the time field constants.
1179 * @return the biggest value.
1181 public int getMaximum(int field)
1183 return maximums[field];
1187 * Gets the greatest minimum value that is allowed for the specified field.
1188 * This is the largest value returned by the <code>getActualMinimum(int)</code>
1189 * method.
1191 * @param field the time field. One of the time field constants.
1192 * @return the greatest minimum value.
1193 * @see #getActualMinimum(int)
1195 public int getGreatestMinimum(int field)
1197 if (field == WEEK_OF_YEAR)
1198 return 1;
1199 return minimums[field];
1203 * Gets the smallest maximum value that is allowed for the
1204 * specified field. This is the smallest value returned
1205 * by the <code>getActualMaximum(int)</code>. For example,
1206 * this is 28 for DAY_OF_MONTH (as all months have at least
1207 * 28 days).
1209 * @param field the time field. One of the time field constants.
1210 * @return the least maximum value.
1211 * @see #getActualMaximum(int)
1212 * @since 1.2
1214 public int getLeastMaximum(int field)
1216 switch (field)
1218 case WEEK_OF_YEAR:
1219 return 52;
1220 case DAY_OF_MONTH:
1221 return 28;
1222 case DAY_OF_YEAR:
1223 return 365;
1224 case DAY_OF_WEEK_IN_MONTH:
1225 case WEEK_OF_MONTH:
1226 return 4;
1227 default:
1228 return maximums[field];
1233 * Gets the actual minimum value that is allowed for the specified field.
1234 * This value is dependent on the values of the other fields. Note that
1235 * this calls <code>complete()</code> if not enough fields are set. This
1236 * can have ugly side effects. The value given depends on the current
1237 * time used by this instance.
1239 * @param field the time field. One of the time field constants.
1240 * @return the actual minimum value.
1241 * @since 1.2
1243 public int getActualMinimum(int field)
1245 if (field == WEEK_OF_YEAR)
1247 int min = getMinimalDaysInFirstWeek();
1248 if (min == 0)
1249 return 1;
1250 if (! areFieldsSet || ! isSet[ERA] || ! isSet[YEAR])
1251 complete();
1253 int year = fields[ERA] == AD ? fields[YEAR] : 1 - fields[YEAR];
1254 int weekday = getWeekDay(year, min);
1255 if ((7 + weekday - getFirstDayOfWeek()) % 7 >= min - 1)
1256 return 1;
1257 return 0;
1259 return minimums[field];
1263 * Gets the actual maximum value that is allowed for the specified field.
1264 * This value is dependent on the values of the other fields. Note that
1265 * this calls <code>complete()</code> if not enough fields are set. This
1266 * can have ugly side effects. The value given depends on the current time
1267 * used by this instance; thus, leap years have a maximum day of month value of
1268 * 29, rather than 28.
1270 * @param field the time field. One of the time field constants.
1271 * @return the actual maximum value.
1273 public int getActualMaximum(int field)
1275 switch (field)
1277 case WEEK_OF_YEAR:
1279 if (! areFieldsSet || ! isSet[ERA] || ! isSet[YEAR])
1280 complete();
1282 // This is wrong for the year that contains the gregorian change.
1283 // I.e it gives the weeks in the julian year or in the gregorian
1284 // year in that case.
1285 int year = fields[ERA] == AD ? fields[YEAR] : 1 - fields[YEAR];
1286 int lastDay = isLeapYear(year) ? 366 : 365;
1287 int weekday = getWeekDay(year, lastDay);
1288 int week = (lastDay + 6 - (7 + weekday - getFirstDayOfWeek()) % 7) / 7;
1290 int minimalDays = getMinimalDaysInFirstWeek();
1291 int firstWeekday = getWeekDay(year, minimalDays);
1293 * Is there a set of days at the beginning of the year, before the
1294 * first day of the week, equal to or greater than the minimum number
1295 * of days required in the first week?
1297 if (minimalDays - (7 + firstWeekday - getFirstDayOfWeek()) % 7 < 1)
1298 return week + 1; /* Add week 1: firstWeekday through to firstDayOfWeek */
1300 case DAY_OF_MONTH:
1302 if (! areFieldsSet || ! isSet[MONTH])
1303 complete();
1304 int month = fields[MONTH];
1306 // If you change this, you should also change
1307 // SimpleTimeZone.getDaysInMonth();
1308 if (month == FEBRUARY)
1310 if (! isSet[YEAR] || ! isSet[ERA])
1311 complete();
1312 int year = fields[ERA] == AD ? fields[YEAR] : 1 - fields[YEAR];
1313 return isLeapYear(year) ? 29 : 28;
1315 else if (month < AUGUST)
1316 return 31 - (month & 1);
1317 else
1318 return 30 + (month & 1);
1320 case DAY_OF_YEAR:
1322 if (! areFieldsSet || ! isSet[ERA] || ! isSet[YEAR])
1323 complete();
1324 int year = fields[ERA] == AD ? fields[YEAR] : 1 - fields[YEAR];
1325 return isLeapYear(year) ? 366 : 365;
1327 case DAY_OF_WEEK_IN_MONTH:
1329 // This is wrong for the month that contains the gregorian change.
1330 int daysInMonth = getActualMaximum(DAY_OF_MONTH);
1332 // That's black magic, I know
1333 return (daysInMonth - (fields[DAY_OF_MONTH] - 1) % 7 + 6) / 7;
1335 case WEEK_OF_MONTH:
1337 int daysInMonth = getActualMaximum(DAY_OF_MONTH);
1338 int weekday = (daysInMonth - fields[DAY_OF_MONTH]
1339 + fields[DAY_OF_WEEK] - SUNDAY) % 7 + SUNDAY;
1340 return (daysInMonth + 6 - (7 + weekday - getFirstDayOfWeek()) % 7) / 7;
1342 default:
1343 return maximums[field];