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