GregorianCalendar.java revision d7928577b0cc656c1c6da16bfe281541fdd435ee
1/* 2 * Copyright (C) 2014 The Android Open Source Project 3 * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. Oracle designates this 9 * particular file as subject to the "Classpath" exception as provided 10 * by Oracle in the LICENSE file that accompanied this code. 11 * 12 * This code is distributed in the hope that it will be useful, but WITHOUT 13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 * version 2 for more details (a copy is included in the LICENSE file that 16 * accompanied this code). 17 * 18 * You should have received a copy of the GNU General Public License version 19 * 2 along with this work; if not, write to the Free Software Foundation, 20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 21 * 22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 23 * or visit www.oracle.com if you need additional information or have any 24 * questions. 25 */ 26 27/* 28 * (C) Copyright Taligent, Inc. 1996-1998 - All Rights Reserved 29 * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved 30 * 31 * The original version of this source code and documentation is copyrighted 32 * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These 33 * materials are provided under terms of a License Agreement between Taligent 34 * and Sun. This technology is protected by multiple US and International 35 * patents. This notice and attribution to Taligent may not be removed. 36 * Taligent is a registered trademark of Taligent, Inc. 37 * 38 */ 39 40package java.util; 41 42import java.io.IOException; 43import java.io.ObjectInputStream; 44import java.time.Instant; 45import java.time.ZonedDateTime; 46import java.time.temporal.ChronoField; 47import libcore.util.ZoneInfo; 48import sun.util.calendar.BaseCalendar; 49import sun.util.calendar.CalendarDate; 50import sun.util.calendar.CalendarSystem; 51import sun.util.calendar.CalendarUtils; 52import sun.util.calendar.Era; 53import sun.util.calendar.Gregorian; 54import sun.util.calendar.JulianCalendar; 55 56/** 57 * <code>GregorianCalendar</code> is a concrete subclass of 58 * <code>Calendar</code> and provides the standard calendar system 59 * used by most of the world. 60 * 61 * <p> <code>GregorianCalendar</code> is a hybrid calendar that 62 * supports both the Julian and Gregorian calendar systems with the 63 * support of a single discontinuity, which corresponds by default to 64 * the Gregorian date when the Gregorian calendar was instituted 65 * (October 15, 1582 in some countries, later in others). The cutover 66 * date may be changed by the caller by calling {@link 67 * #setGregorianChange(Date) setGregorianChange()}. 68 * 69 * <p> 70 * Historically, in those countries which adopted the Gregorian calendar first, 71 * October 4, 1582 (Julian) was thus followed by October 15, 1582 (Gregorian). This calendar models 72 * this correctly. Before the Gregorian cutover, <code>GregorianCalendar</code> 73 * implements the Julian calendar. The only difference between the Gregorian 74 * and the Julian calendar is the leap year rule. The Julian calendar specifies 75 * leap years every four years, whereas the Gregorian calendar omits century 76 * years which are not divisible by 400. 77 * 78 * <p> 79 * <code>GregorianCalendar</code> implements <em>proleptic</em> Gregorian and 80 * Julian calendars. That is, dates are computed by extrapolating the current 81 * rules indefinitely far backward and forward in time. As a result, 82 * <code>GregorianCalendar</code> may be used for all years to generate 83 * meaningful and consistent results. However, dates obtained using 84 * <code>GregorianCalendar</code> are historically accurate only from March 1, 4 85 * AD onward, when modern Julian calendar rules were adopted. Before this date, 86 * leap year rules were applied irregularly, and before 45 BC the Julian 87 * calendar did not even exist. 88 * 89 * <p> 90 * Prior to the institution of the Gregorian calendar, New Year's Day was 91 * March 25. To avoid confusion, this calendar always uses January 1. A manual 92 * adjustment may be made if desired for dates that are prior to the Gregorian 93 * changeover and which fall between January 1 and March 24. 94 * 95 * <h3><a name="week_and_year">Week Of Year and Week Year</a></h3> 96 * 97 * <p>Values calculated for the {@link Calendar#WEEK_OF_YEAR 98 * WEEK_OF_YEAR} field range from 1 to 53. The first week of a 99 * calendar year is the earliest seven day period starting on {@link 100 * Calendar#getFirstDayOfWeek() getFirstDayOfWeek()} that contains at 101 * least {@link Calendar#getMinimalDaysInFirstWeek() 102 * getMinimalDaysInFirstWeek()} days from that year. It thus depends 103 * on the values of {@code getMinimalDaysInFirstWeek()}, {@code 104 * getFirstDayOfWeek()}, and the day of the week of January 1. Weeks 105 * between week 1 of one year and week 1 of the following year 106 * (exclusive) are numbered sequentially from 2 to 52 or 53 (except 107 * for year(s) involved in the Julian-Gregorian transition). 108 * 109 * <p>The {@code getFirstDayOfWeek()} and {@code 110 * getMinimalDaysInFirstWeek()} values are initialized using 111 * locale-dependent resources when constructing a {@code 112 * GregorianCalendar}. <a name="iso8601_compatible_setting">The week 113 * determination is compatible</a> with the ISO 8601 standard when {@code 114 * getFirstDayOfWeek()} is {@code MONDAY} and {@code 115 * getMinimalDaysInFirstWeek()} is 4, which values are used in locales 116 * where the standard is preferred. These values can explicitly be set by 117 * calling {@link Calendar#setFirstDayOfWeek(int) setFirstDayOfWeek()} and 118 * {@link Calendar#setMinimalDaysInFirstWeek(int) 119 * setMinimalDaysInFirstWeek()}. 120 * 121 * <p>A <a name="week_year"><em>week year</em></a> is in sync with a 122 * {@code WEEK_OF_YEAR} cycle. All weeks between the first and last 123 * weeks (inclusive) have the same <em>week year</em> value. 124 * Therefore, the first and last days of a week year may have 125 * different calendar year values. 126 * 127 * <p>For example, January 1, 1998 is a Thursday. If {@code 128 * getFirstDayOfWeek()} is {@code MONDAY} and {@code 129 * getMinimalDaysInFirstWeek()} is 4 (ISO 8601 standard compatible 130 * setting), then week 1 of 1998 starts on December 29, 1997, and ends 131 * on January 4, 1998. The week year is 1998 for the last three days 132 * of calendar year 1997. If, however, {@code getFirstDayOfWeek()} is 133 * {@code SUNDAY}, then week 1 of 1998 starts on January 4, 1998, and 134 * ends on January 10, 1998; the first three days of 1998 then are 135 * part of week 53 of 1997 and their week year is 1997. 136 * 137 * <h4>Week Of Month</h4> 138 * 139 * <p>Values calculated for the <code>WEEK_OF_MONTH</code> field range from 0 140 * to 6. Week 1 of a month (the days with <code>WEEK_OF_MONTH = 141 * 1</code>) is the earliest set of at least 142 * <code>getMinimalDaysInFirstWeek()</code> contiguous days in that month, 143 * ending on the day before <code>getFirstDayOfWeek()</code>. Unlike 144 * week 1 of a year, week 1 of a month may be shorter than 7 days, need 145 * not start on <code>getFirstDayOfWeek()</code>, and will not include days of 146 * the previous month. Days of a month before week 1 have a 147 * <code>WEEK_OF_MONTH</code> of 0. 148 * 149 * <p>For example, if <code>getFirstDayOfWeek()</code> is <code>SUNDAY</code> 150 * and <code>getMinimalDaysInFirstWeek()</code> is 4, then the first week of 151 * January 1998 is Sunday, January 4 through Saturday, January 10. These days 152 * have a <code>WEEK_OF_MONTH</code> of 1. Thursday, January 1 through 153 * Saturday, January 3 have a <code>WEEK_OF_MONTH</code> of 0. If 154 * <code>getMinimalDaysInFirstWeek()</code> is changed to 3, then January 1 155 * through January 3 have a <code>WEEK_OF_MONTH</code> of 1. 156 * 157 * <h4>Default Fields Values</h4> 158 * 159 * <p>The <code>clear</code> method sets calendar field(s) 160 * undefined. <code>GregorianCalendar</code> uses the following 161 * default value for each calendar field if its value is undefined. 162 * 163 * <table cellpadding="0" cellspacing="3" border="0" 164 * summary="GregorianCalendar default field values" 165 * style="text-align: left; width: 66%;"> 166 * <tbody> 167 * <tr> 168 * <th style="vertical-align: top; background-color: rgb(204, 204, 255); 169 * text-align: center;">Field<br> 170 * </th> 171 * <th style="vertical-align: top; background-color: rgb(204, 204, 255); 172 * text-align: center;">Default Value<br> 173 * </th> 174 * </tr> 175 * <tr> 176 * <td style="vertical-align: middle;"> 177 * <code>ERA<br></code> 178 * </td> 179 * <td style="vertical-align: middle;"> 180 * <code>AD<br></code> 181 * </td> 182 * </tr> 183 * <tr> 184 * <td style="vertical-align: middle; background-color: rgb(238, 238, 255);"> 185 * <code>YEAR<br></code> 186 * </td> 187 * <td style="vertical-align: middle; background-color: rgb(238, 238, 255);"> 188 * <code>1970<br></code> 189 * </td> 190 * </tr> 191 * <tr> 192 * <td style="vertical-align: middle;"> 193 * <code>MONTH<br></code> 194 * </td> 195 * <td style="vertical-align: middle;"> 196 * <code>JANUARY<br></code> 197 * </td> 198 * </tr> 199 * <tr> 200 * <td style="vertical-align: top; background-color: rgb(238, 238, 255);"> 201 * <code>DAY_OF_MONTH<br></code> 202 * </td> 203 * <td style="vertical-align: top; background-color: rgb(238, 238, 255);"> 204 * <code>1<br></code> 205 * </td> 206 * </tr> 207 * <tr> 208 * <td style="vertical-align: middle;"> 209 * <code>DAY_OF_WEEK<br></code> 210 * </td> 211 * <td style="vertical-align: middle;"> 212 * <code>the first day of week<br></code> 213 * </td> 214 * </tr> 215 * <tr> 216 * <td style="vertical-align: top; background-color: rgb(238, 238, 255);"> 217 * <code>WEEK_OF_MONTH<br></code> 218 * </td> 219 * <td style="vertical-align: top; background-color: rgb(238, 238, 255);"> 220 * <code>0<br></code> 221 * </td> 222 * </tr> 223 * <tr> 224 * <td style="vertical-align: top;"> 225 * <code>DAY_OF_WEEK_IN_MONTH<br></code> 226 * </td> 227 * <td style="vertical-align: top;"> 228 * <code>1<br></code> 229 * </td> 230 * </tr> 231 * <tr> 232 * <td style="vertical-align: middle; background-color: rgb(238, 238, 255);"> 233 * <code>AM_PM<br></code> 234 * </td> 235 * <td style="vertical-align: middle; background-color: rgb(238, 238, 255);"> 236 * <code>AM<br></code> 237 * </td> 238 * </tr> 239 * <tr> 240 * <td style="vertical-align: middle;"> 241 * <code>HOUR, HOUR_OF_DAY, MINUTE, SECOND, MILLISECOND<br></code> 242 * </td> 243 * <td style="vertical-align: middle;"> 244 * <code>0<br></code> 245 * </td> 246 * </tr> 247 * </tbody> 248 * </table> 249 * <br>Default values are not applicable for the fields not listed above. 250 * 251 * <p> 252 * <strong>Example:</strong> 253 * <blockquote> 254 * <pre> 255 * // get the supported ids for GMT-08:00 (Pacific Standard Time) 256 * String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000); 257 * // if no ids were returned, something is wrong. get out. 258 * if (ids.length == 0) 259 * System.exit(0); 260 * 261 * // begin output 262 * System.out.println("Current Time"); 263 * 264 * // create a Pacific Standard Time time zone 265 * SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]); 266 * 267 * // set up rules for Daylight Saving Time 268 * pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); 269 * pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); 270 * 271 * // create a GregorianCalendar with the Pacific Daylight time zone 272 * // and the current date and time 273 * Calendar calendar = new GregorianCalendar(pdt); 274 * Date trialTime = new Date(); 275 * calendar.setTime(trialTime); 276 * 277 * // print out a bunch of interesting things 278 * System.out.println("ERA: " + calendar.get(Calendar.ERA)); 279 * System.out.println("YEAR: " + calendar.get(Calendar.YEAR)); 280 * System.out.println("MONTH: " + calendar.get(Calendar.MONTH)); 281 * System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR)); 282 * System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH)); 283 * System.out.println("DATE: " + calendar.get(Calendar.DATE)); 284 * System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH)); 285 * System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR)); 286 * System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK)); 287 * System.out.println("DAY_OF_WEEK_IN_MONTH: " 288 * + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH)); 289 * System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM)); 290 * System.out.println("HOUR: " + calendar.get(Calendar.HOUR)); 291 * System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY)); 292 * System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE)); 293 * System.out.println("SECOND: " + calendar.get(Calendar.SECOND)); 294 * System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND)); 295 * System.out.println("ZONE_OFFSET: " 296 * + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000))); 297 * System.out.println("DST_OFFSET: " 298 * + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000))); 299 300 * System.out.println("Current Time, with hour reset to 3"); 301 * calendar.clear(Calendar.HOUR_OF_DAY); // so doesn't override 302 * calendar.set(Calendar.HOUR, 3); 303 * System.out.println("ERA: " + calendar.get(Calendar.ERA)); 304 * System.out.println("YEAR: " + calendar.get(Calendar.YEAR)); 305 * System.out.println("MONTH: " + calendar.get(Calendar.MONTH)); 306 * System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR)); 307 * System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH)); 308 * System.out.println("DATE: " + calendar.get(Calendar.DATE)); 309 * System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH)); 310 * System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR)); 311 * System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK)); 312 * System.out.println("DAY_OF_WEEK_IN_MONTH: " 313 * + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH)); 314 * System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM)); 315 * System.out.println("HOUR: " + calendar.get(Calendar.HOUR)); 316 * System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY)); 317 * System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE)); 318 * System.out.println("SECOND: " + calendar.get(Calendar.SECOND)); 319 * System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND)); 320 * System.out.println("ZONE_OFFSET: " 321 * + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000))); // in hours 322 * System.out.println("DST_OFFSET: " 323 * + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000))); // in hours 324 * </pre> 325 * </blockquote> 326 * 327 * @see TimeZone 328 * @author David Goldsmith, Mark Davis, Chen-Lieh Huang, Alan Liu 329 * @since JDK1.1 330 */ 331public class GregorianCalendar extends Calendar { 332 /* 333 * Implementation Notes 334 * 335 * The epoch is the number of days or milliseconds from some defined 336 * starting point. The epoch for java.util.Date is used here; that is, 337 * milliseconds from January 1, 1970 (Gregorian), midnight UTC. Other 338 * epochs which are used are January 1, year 1 (Gregorian), which is day 1 339 * of the Gregorian calendar, and December 30, year 0 (Gregorian), which is 340 * day 1 of the Julian calendar. 341 * 342 * We implement the proleptic Julian and Gregorian calendars. This means we 343 * implement the modern definition of the calendar even though the 344 * historical usage differs. For example, if the Gregorian change is set 345 * to new Date(Long.MIN_VALUE), we have a pure Gregorian calendar which 346 * labels dates preceding the invention of the Gregorian calendar in 1582 as 347 * if the calendar existed then. 348 * 349 * Likewise, with the Julian calendar, we assume a consistent 350 * 4-year leap year rule, even though the historical pattern of 351 * leap years is irregular, being every 3 years from 45 BCE 352 * through 9 BCE, then every 4 years from 8 CE onwards, with no 353 * leap years in-between. Thus date computations and functions 354 * such as isLeapYear() are not intended to be historically 355 * accurate. 356 */ 357 358////////////////// 359// Class Variables 360////////////////// 361 362 /** 363 * Value of the <code>ERA</code> field indicating 364 * the period before the common era (before Christ), also known as BCE. 365 * The sequence of years at the transition from <code>BC</code> to <code>AD</code> is 366 * ..., 2 BC, 1 BC, 1 AD, 2 AD,... 367 * 368 * @see #ERA 369 */ 370 public static final int BC = 0; 371 372 /** 373 * Value of the {@link #ERA} field indicating 374 * the period before the common era, the same value as {@link #BC}. 375 * 376 * @see #CE 377 */ 378 static final int BCE = 0; 379 380 /** 381 * Value of the <code>ERA</code> field indicating 382 * the common era (Anno Domini), also known as CE. 383 * The sequence of years at the transition from <code>BC</code> to <code>AD</code> is 384 * ..., 2 BC, 1 BC, 1 AD, 2 AD,... 385 * 386 * @see #ERA 387 */ 388 public static final int AD = 1; 389 390 /** 391 * Value of the {@link #ERA} field indicating 392 * the common era, the same value as {@link #AD}. 393 * 394 * @see #BCE 395 */ 396 static final int CE = 1; 397 398 private static final int EPOCH_OFFSET = 719163; // Fixed date of January 1, 1970 (Gregorian) 399 private static final int EPOCH_YEAR = 1970; 400 401 static final int MONTH_LENGTH[] 402 = {31,28,31,30,31,30,31,31,30,31,30,31}; // 0-based 403 static final int LEAP_MONTH_LENGTH[] 404 = {31,29,31,30,31,30,31,31,30,31,30,31}; // 0-based 405 406 // Useful millisecond constants. Although ONE_DAY and ONE_WEEK can fit 407 // into ints, they must be longs in order to prevent arithmetic overflow 408 // when performing (bug 4173516). 409 private static final int ONE_SECOND = 1000; 410 private static final int ONE_MINUTE = 60*ONE_SECOND; 411 private static final int ONE_HOUR = 60*ONE_MINUTE; 412 private static final long ONE_DAY = 24*ONE_HOUR; 413 private static final long ONE_WEEK = 7*ONE_DAY; 414 415 /* 416 * <pre> 417 * Greatest Least 418 * Field name Minimum Minimum Maximum Maximum 419 * ---------- ------- ------- ------- ------- 420 * ERA 0 0 1 1 421 * YEAR 1 1 292269054 292278994 422 * MONTH 0 0 11 11 423 * WEEK_OF_YEAR 1 1 52* 53 424 * WEEK_OF_MONTH 0 0 4* 6 425 * DAY_OF_MONTH 1 1 28* 31 426 * DAY_OF_YEAR 1 1 365* 366 427 * DAY_OF_WEEK 1 1 7 7 428 * DAY_OF_WEEK_IN_MONTH -1 -1 4* 6 429 * AM_PM 0 0 1 1 430 * HOUR 0 0 11 11 431 * HOUR_OF_DAY 0 0 23 23 432 * MINUTE 0 0 59 59 433 * SECOND 0 0 59 59 434 * MILLISECOND 0 0 999 999 435 * ZONE_OFFSET -13:00 -13:00 14:00 14:00 436 * DST_OFFSET 0:00 0:00 0:20 2:00 437 * </pre> 438 * *: depends on the Gregorian change date 439 */ 440 static final int MIN_VALUES[] = { 441 BCE, // ERA 442 1, // YEAR 443 JANUARY, // MONTH 444 1, // WEEK_OF_YEAR 445 0, // WEEK_OF_MONTH 446 1, // DAY_OF_MONTH 447 1, // DAY_OF_YEAR 448 SUNDAY, // DAY_OF_WEEK 449 1, // DAY_OF_WEEK_IN_MONTH 450 AM, // AM_PM 451 0, // HOUR 452 0, // HOUR_OF_DAY 453 0, // MINUTE 454 0, // SECOND 455 0, // MILLISECOND 456 -13*ONE_HOUR, // ZONE_OFFSET (UNIX compatibility) 457 0 // DST_OFFSET 458 }; 459 static final int LEAST_MAX_VALUES[] = { 460 CE, // ERA 461 292269054, // YEAR 462 DECEMBER, // MONTH 463 52, // WEEK_OF_YEAR 464 4, // WEEK_OF_MONTH 465 28, // DAY_OF_MONTH 466 365, // DAY_OF_YEAR 467 SATURDAY, // DAY_OF_WEEK 468 4, // DAY_OF_WEEK_IN 469 PM, // AM_PM 470 11, // HOUR 471 23, // HOUR_OF_DAY 472 59, // MINUTE 473 59, // SECOND 474 999, // MILLISECOND 475 14*ONE_HOUR, // ZONE_OFFSET 476 20*ONE_MINUTE // DST_OFFSET (historical least maximum) 477 }; 478 static final int MAX_VALUES[] = { 479 CE, // ERA 480 292278994, // YEAR 481 DECEMBER, // MONTH 482 53, // WEEK_OF_YEAR 483 6, // WEEK_OF_MONTH 484 31, // DAY_OF_MONTH 485 366, // DAY_OF_YEAR 486 SATURDAY, // DAY_OF_WEEK 487 6, // DAY_OF_WEEK_IN 488 PM, // AM_PM 489 11, // HOUR 490 23, // HOUR_OF_DAY 491 59, // MINUTE 492 59, // SECOND 493 999, // MILLISECOND 494 14*ONE_HOUR, // ZONE_OFFSET 495 2*ONE_HOUR // DST_OFFSET (double summer time) 496 }; 497 498 // Proclaim serialization compatibility with JDK 1.1 499 @SuppressWarnings("FieldNameHidesFieldInSuperclass") 500 static final long serialVersionUID = -8125100834729963327L; 501 502 // Reference to the sun.util.calendar.Gregorian instance (singleton). 503 private static final Gregorian gcal = 504 CalendarSystem.getGregorianCalendar(); 505 506 // Reference to the JulianCalendar instance (singleton), set as needed. See 507 // getJulianCalendarSystem(). 508 private static JulianCalendar jcal; 509 510 // JulianCalendar eras. See getJulianCalendarSystem(). 511 private static Era[] jeras; 512 513 // The default value of gregorianCutover. 514 static final long DEFAULT_GREGORIAN_CUTOVER = -12219292800000L; 515 516///////////////////// 517// Instance Variables 518///////////////////// 519 520 /** 521 * The point at which the Gregorian calendar rules are used, measured in 522 * milliseconds from the standard epoch. Default is October 15, 1582 523 * (Gregorian) 00:00:00 UTC or -12219292800000L. For this value, October 4, 524 * 1582 (Julian) is followed by October 15, 1582 (Gregorian). This 525 * corresponds to Julian day number 2299161. 526 * @serial 527 */ 528 private long gregorianCutover = DEFAULT_GREGORIAN_CUTOVER; 529 530 /** 531 * The fixed date of the gregorianCutover. 532 */ 533 private transient long gregorianCutoverDate = 534 (((DEFAULT_GREGORIAN_CUTOVER + 1)/ONE_DAY) - 1) + EPOCH_OFFSET; // == 577736 535 536 /** 537 * The normalized year of the gregorianCutover in Gregorian, with 538 * 0 representing 1 BCE, -1 representing 2 BCE, etc. 539 */ 540 private transient int gregorianCutoverYear = 1582; 541 542 /** 543 * The normalized year of the gregorianCutover in Julian, with 0 544 * representing 1 BCE, -1 representing 2 BCE, etc. 545 */ 546 private transient int gregorianCutoverYearJulian = 1582; 547 548 /** 549 * gdate always has a sun.util.calendar.Gregorian.Date instance to 550 * avoid overhead of creating it. The assumption is that most 551 * applications will need only Gregorian calendar calculations. 552 */ 553 private transient BaseCalendar.Date gdate; 554 555 /** 556 * Reference to either gdate or a JulianCalendar.Date 557 * instance. After calling complete(), this value is guaranteed to 558 * be set. 559 */ 560 private transient BaseCalendar.Date cdate; 561 562 /** 563 * The CalendarSystem used to calculate the date in cdate. After 564 * calling complete(), this value is guaranteed to be set and 565 * consistent with the cdate value. 566 */ 567 private transient BaseCalendar calsys; 568 569 /** 570 * Temporary int[2] to get time zone offsets. zoneOffsets[0] gets 571 * the GMT offset value and zoneOffsets[1] gets the DST saving 572 * value. 573 */ 574 private transient int[] zoneOffsets; 575 576 /** 577 * Temporary storage for saving original fields[] values in 578 * non-lenient mode. 579 */ 580 private transient int[] originalFields; 581 582/////////////// 583// Constructors 584/////////////// 585 586 /** 587 * Constructs a default <code>GregorianCalendar</code> using the current time 588 * in the default time zone with the default 589 * {@link Locale.Category#FORMAT FORMAT} locale. 590 */ 591 public GregorianCalendar() { 592 this(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT)); 593 setZoneShared(true); 594 } 595 596 /** 597 * Constructs a <code>GregorianCalendar</code> based on the current time 598 * in the given time zone with the default 599 * {@link Locale.Category#FORMAT FORMAT} locale. 600 * 601 * @param zone the given time zone. 602 */ 603 public GregorianCalendar(TimeZone zone) { 604 this(zone, Locale.getDefault(Locale.Category.FORMAT)); 605 } 606 607 /** 608 * Constructs a <code>GregorianCalendar</code> based on the current time 609 * in the default time zone with the given locale. 610 * 611 * @param aLocale the given locale. 612 */ 613 public GregorianCalendar(Locale aLocale) { 614 this(TimeZone.getDefaultRef(), aLocale); 615 setZoneShared(true); 616 } 617 618 /** 619 * Constructs a <code>GregorianCalendar</code> based on the current time 620 * in the given time zone with the given locale. 621 * 622 * @param zone the given time zone. 623 * @param aLocale the given locale. 624 */ 625 public GregorianCalendar(TimeZone zone, Locale aLocale) { 626 super(zone, aLocale); 627 gdate = (BaseCalendar.Date) gcal.newCalendarDate(zone); 628 setTimeInMillis(System.currentTimeMillis()); 629 } 630 631 /** 632 * Constructs a <code>GregorianCalendar</code> with the given date set 633 * in the default time zone with the default locale. 634 * 635 * @param year the value used to set the <code>YEAR</code> calendar field in the calendar. 636 * @param month the value used to set the <code>MONTH</code> calendar field in the calendar. 637 * Month value is 0-based. e.g., 0 for January. 638 * @param dayOfMonth the value used to set the <code>DAY_OF_MONTH</code> calendar field in the calendar. 639 */ 640 public GregorianCalendar(int year, int month, int dayOfMonth) { 641 this(year, month, dayOfMonth, 0, 0, 0, 0); 642 } 643 644 /** 645 * Constructs a <code>GregorianCalendar</code> with the given date 646 * and time set for the default time zone with the default locale. 647 * 648 * @param year the value used to set the <code>YEAR</code> calendar field in the calendar. 649 * @param month the value used to set the <code>MONTH</code> calendar field in the calendar. 650 * Month value is 0-based. e.g., 0 for January. 651 * @param dayOfMonth the value used to set the <code>DAY_OF_MONTH</code> calendar field in the calendar. 652 * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field 653 * in the calendar. 654 * @param minute the value used to set the <code>MINUTE</code> calendar field 655 * in the calendar. 656 */ 657 public GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, 658 int minute) { 659 this(year, month, dayOfMonth, hourOfDay, minute, 0, 0); 660 } 661 662 /** 663 * Constructs a GregorianCalendar with the given date 664 * and time set for the default time zone with the default locale. 665 * 666 * @param year the value used to set the <code>YEAR</code> calendar field in the calendar. 667 * @param month the value used to set the <code>MONTH</code> calendar field in the calendar. 668 * Month value is 0-based. e.g., 0 for January. 669 * @param dayOfMonth the value used to set the <code>DAY_OF_MONTH</code> calendar field in the calendar. 670 * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field 671 * in the calendar. 672 * @param minute the value used to set the <code>MINUTE</code> calendar field 673 * in the calendar. 674 * @param second the value used to set the <code>SECOND</code> calendar field 675 * in the calendar. 676 */ 677 public GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, 678 int minute, int second) { 679 this(year, month, dayOfMonth, hourOfDay, minute, second, 0); 680 } 681 682 /** 683 * Constructs a <code>GregorianCalendar</code> with the given date 684 * and time set for the default time zone with the default locale. 685 * 686 * @param year the value used to set the <code>YEAR</code> calendar field in the calendar. 687 * @param month the value used to set the <code>MONTH</code> calendar field in the calendar. 688 * Month value is 0-based. e.g., 0 for January. 689 * @param dayOfMonth the value used to set the <code>DAY_OF_MONTH</code> calendar field in the calendar. 690 * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field 691 * in the calendar. 692 * @param minute the value used to set the <code>MINUTE</code> calendar field 693 * in the calendar. 694 * @param second the value used to set the <code>SECOND</code> calendar field 695 * in the calendar. 696 * @param millis the value used to set the <code>MILLISECOND</code> calendar field 697 */ 698 GregorianCalendar(int year, int month, int dayOfMonth, 699 int hourOfDay, int minute, int second, int millis) { 700 super(); 701 gdate = (BaseCalendar.Date) gcal.newCalendarDate(getZone()); 702 this.set(YEAR, year); 703 this.set(MONTH, month); 704 this.set(DAY_OF_MONTH, dayOfMonth); 705 706 // Set AM_PM and HOUR here to set their stamp values before 707 // setting HOUR_OF_DAY (6178071). 708 if (hourOfDay >= 12 && hourOfDay <= 23) { 709 // If hourOfDay is a valid PM hour, set the correct PM values 710 // so that it won't throw an exception in case it's set to 711 // non-lenient later. 712 this.internalSet(AM_PM, PM); 713 this.internalSet(HOUR, hourOfDay - 12); 714 } else { 715 // The default value for AM_PM is AM. 716 // We don't care any out of range value here for leniency. 717 this.internalSet(HOUR, hourOfDay); 718 } 719 // The stamp values of AM_PM and HOUR must be COMPUTED. (6440854) 720 setFieldsComputed(HOUR_MASK|AM_PM_MASK); 721 722 this.set(HOUR_OF_DAY, hourOfDay); 723 this.set(MINUTE, minute); 724 this.set(SECOND, second); 725 // should be changed to set() when this constructor is made 726 // public. 727 this.internalSet(MILLISECOND, millis); 728 } 729 730 /** 731 * Constructs an empty GregorianCalendar. 732 * 733 * @param zone the given time zone 734 * @param locale the given locale 735 * @param flag the flag requesting an empty instance 736 */ 737 GregorianCalendar(TimeZone zone, Locale locale, boolean flag) { 738 super(zone, locale); 739 gdate = (BaseCalendar.Date) gcal.newCalendarDate(getZone()); 740 } 741 742 GregorianCalendar(long milliseconds) { 743 this(); 744 setTimeInMillis(milliseconds); 745 } 746 747///////////////// 748// Public methods 749///////////////// 750 751 /** 752 * Sets the <code>GregorianCalendar</code> change date. This is the point when the switch 753 * from Julian dates to Gregorian dates occurred. Default is October 15, 754 * 1582 (Gregorian). Previous to this, dates will be in the Julian calendar. 755 * <p> 756 * To obtain a pure Julian calendar, set the change date to 757 * <code>Date(Long.MAX_VALUE)</code>. To obtain a pure Gregorian calendar, 758 * set the change date to <code>Date(Long.MIN_VALUE)</code>. 759 * 760 * @param date the given Gregorian cutover date. 761 */ 762 public void setGregorianChange(Date date) { 763 long cutoverTime = date.getTime(); 764 if (cutoverTime == gregorianCutover) { 765 return; 766 } 767 // Before changing the cutover date, make sure to have the 768 // time of this calendar. 769 complete(); 770 setGregorianChange(cutoverTime); 771 } 772 773 private void setGregorianChange(long cutoverTime) { 774 gregorianCutover = cutoverTime; 775 gregorianCutoverDate = CalendarUtils.floorDivide(cutoverTime, ONE_DAY) 776 + EPOCH_OFFSET; 777 778 // To provide the "pure" Julian calendar as advertised. 779 // Strictly speaking, the last millisecond should be a 780 // Gregorian date. However, the API doc specifies that setting 781 // the cutover date to Long.MAX_VALUE will make this calendar 782 // a pure Julian calendar. (See 4167995) 783 if (cutoverTime == Long.MAX_VALUE) { 784 gregorianCutoverDate++; 785 } 786 787 BaseCalendar.Date d = getGregorianCutoverDate(); 788 789 // Set the cutover year (in the Gregorian year numbering) 790 gregorianCutoverYear = d.getYear(); 791 792 BaseCalendar julianCal = getJulianCalendarSystem(); 793 d = (BaseCalendar.Date) julianCal.newCalendarDate(TimeZone.NO_TIMEZONE); 794 julianCal.getCalendarDateFromFixedDate(d, gregorianCutoverDate - 1); 795 gregorianCutoverYearJulian = d.getNormalizedYear(); 796 797 if (time < gregorianCutover) { 798 // The field values are no longer valid under the new 799 // cutover date. 800 setUnnormalized(); 801 } 802 } 803 804 /** 805 * Gets the Gregorian Calendar change date. This is the point when the 806 * switch from Julian dates to Gregorian dates occurred. Default is 807 * October 15, 1582 (Gregorian). Previous to this, dates will be in the Julian 808 * calendar. 809 * 810 * @return the Gregorian cutover date for this <code>GregorianCalendar</code> object. 811 */ 812 public final Date getGregorianChange() { 813 return new Date(gregorianCutover); 814 } 815 816 /** 817 * Determines if the given year is a leap year. Returns <code>true</code> if 818 * the given year is a leap year. To specify BC year numbers, 819 * <code>1 - year number</code> must be given. For example, year BC 4 is 820 * specified as -3. 821 * 822 * @param year the given year. 823 * @return <code>true</code> if the given year is a leap year; <code>false</code> otherwise. 824 */ 825 public boolean isLeapYear(int year) { 826 if ((year & 3) != 0) { 827 return false; 828 } 829 830 if (year > gregorianCutoverYear) { 831 return (year%100 != 0) || (year%400 == 0); // Gregorian 832 } 833 if (year < gregorianCutoverYearJulian) { 834 return true; // Julian 835 } 836 boolean gregorian; 837 // If the given year is the Gregorian cutover year, we need to 838 // determine which calendar system to be applied to February in the year. 839 if (gregorianCutoverYear == gregorianCutoverYearJulian) { 840 BaseCalendar.Date d = getCalendarDate(gregorianCutoverDate); // Gregorian 841 gregorian = d.getMonth() < BaseCalendar.MARCH; 842 } else { 843 gregorian = year == gregorianCutoverYear; 844 } 845 return gregorian ? (year%100 != 0) || (year%400 == 0) : true; 846 } 847 848 /** 849 * Returns {@code "gregory"} as the calendar type. 850 * 851 * @return {@code "gregory"} 852 * @since 1.8 853 */ 854 @Override 855 public String getCalendarType() { 856 return "gregory"; 857 } 858 859 /** 860 * Compares this <code>GregorianCalendar</code> to the specified 861 * <code>Object</code>. The result is <code>true</code> if and 862 * only if the argument is a <code>GregorianCalendar</code> object 863 * that represents the same time value (millisecond offset from 864 * the <a href="Calendar.html#Epoch">Epoch</a>) under the same 865 * <code>Calendar</code> parameters and Gregorian change date as 866 * this object. 867 * 868 * @param obj the object to compare with. 869 * @return <code>true</code> if this object is equal to <code>obj</code>; 870 * <code>false</code> otherwise. 871 * @see Calendar#compareTo(Calendar) 872 */ 873 @Override 874 public boolean equals(Object obj) { 875 return obj instanceof GregorianCalendar && 876 super.equals(obj) && 877 gregorianCutover == ((GregorianCalendar)obj).gregorianCutover; 878 } 879 880 /** 881 * Generates the hash code for this <code>GregorianCalendar</code> object. 882 */ 883 @Override 884 public int hashCode() { 885 return super.hashCode() ^ (int)gregorianCutoverDate; 886 } 887 888 /** 889 * Adds the specified (signed) amount of time to the given calendar field, 890 * based on the calendar's rules. 891 * 892 * <p><em>Add rule 1</em>. The value of <code>field</code> 893 * after the call minus the value of <code>field</code> before the 894 * call is <code>amount</code>, modulo any overflow that has occurred in 895 * <code>field</code>. Overflow occurs when a field value exceeds its 896 * range and, as a result, the next larger field is incremented or 897 * decremented and the field value is adjusted back into its range.</p> 898 * 899 * <p><em>Add rule 2</em>. If a smaller field is expected to be 900 * invariant, but it is impossible for it to be equal to its 901 * prior value because of changes in its minimum or maximum after 902 * <code>field</code> is changed, then its value is adjusted to be as close 903 * as possible to its expected value. A smaller field represents a 904 * smaller unit of time. <code>HOUR</code> is a smaller field than 905 * <code>DAY_OF_MONTH</code>. No adjustment is made to smaller fields 906 * that are not expected to be invariant. The calendar system 907 * determines what fields are expected to be invariant.</p> 908 * 909 * @param field the calendar field. 910 * @param amount the amount of date or time to be added to the field. 911 * @exception IllegalArgumentException if <code>field</code> is 912 * <code>ZONE_OFFSET</code>, <code>DST_OFFSET</code>, or unknown, 913 * or if any calendar fields have out-of-range values in 914 * non-lenient mode. 915 */ 916 @Override 917 public void add(int field, int amount) { 918 // If amount == 0, do nothing even the given field is out of 919 // range. This is tested by JCK. 920 if (amount == 0) { 921 return; // Do nothing! 922 } 923 924 if (field < 0 || field >= ZONE_OFFSET) { 925 throw new IllegalArgumentException(); 926 } 927 928 // Sync the time and calendar fields. 929 complete(); 930 931 if (field == YEAR) { 932 int year = internalGet(YEAR); 933 if (internalGetEra() == CE) { 934 year += amount; 935 if (year > 0) { 936 set(YEAR, year); 937 } else { // year <= 0 938 set(YEAR, 1 - year); 939 // if year == 0, you get 1 BCE. 940 set(ERA, BCE); 941 } 942 } 943 else { // era == BCE 944 year -= amount; 945 if (year > 0) { 946 set(YEAR, year); 947 } else { // year <= 0 948 set(YEAR, 1 - year); 949 // if year == 0, you get 1 CE 950 set(ERA, CE); 951 } 952 } 953 pinDayOfMonth(); 954 } else if (field == MONTH) { 955 int month = internalGet(MONTH) + amount; 956 int year = internalGet(YEAR); 957 int y_amount; 958 959 if (month >= 0) { 960 y_amount = month/12; 961 } else { 962 y_amount = (month+1)/12 - 1; 963 } 964 if (y_amount != 0) { 965 if (internalGetEra() == CE) { 966 year += y_amount; 967 if (year > 0) { 968 set(YEAR, year); 969 } else { // year <= 0 970 set(YEAR, 1 - year); 971 // if year == 0, you get 1 BCE 972 set(ERA, BCE); 973 } 974 } 975 else { // era == BCE 976 year -= y_amount; 977 if (year > 0) { 978 set(YEAR, year); 979 } else { // year <= 0 980 set(YEAR, 1 - year); 981 // if year == 0, you get 1 CE 982 set(ERA, CE); 983 } 984 } 985 } 986 987 if (month >= 0) { 988 set(MONTH, month % 12); 989 } else { 990 // month < 0 991 month %= 12; 992 if (month < 0) { 993 month += 12; 994 } 995 set(MONTH, JANUARY + month); 996 } 997 pinDayOfMonth(); 998 } else if (field == ERA) { 999 int era = internalGet(ERA) + amount; 1000 if (era < 0) { 1001 era = 0; 1002 } 1003 if (era > 1) { 1004 era = 1; 1005 } 1006 set(ERA, era); 1007 } else { 1008 long delta = amount; 1009 long timeOfDay = 0; 1010 switch (field) { 1011 // Handle the time fields here. Convert the given 1012 // amount to milliseconds and call setTimeInMillis. 1013 case HOUR: 1014 case HOUR_OF_DAY: 1015 delta *= 60 * 60 * 1000; // hours to minutes 1016 break; 1017 1018 case MINUTE: 1019 delta *= 60 * 1000; // minutes to seconds 1020 break; 1021 1022 case SECOND: 1023 delta *= 1000; // seconds to milliseconds 1024 break; 1025 1026 case MILLISECOND: 1027 break; 1028 1029 // Handle week, day and AM_PM fields which involves 1030 // time zone offset change adjustment. Convert the 1031 // given amount to the number of days. 1032 case WEEK_OF_YEAR: 1033 case WEEK_OF_MONTH: 1034 case DAY_OF_WEEK_IN_MONTH: 1035 delta *= 7; 1036 break; 1037 1038 case DAY_OF_MONTH: // synonym of DATE 1039 case DAY_OF_YEAR: 1040 case DAY_OF_WEEK: 1041 break; 1042 1043 case AM_PM: 1044 // Convert the amount to the number of days (delta) 1045 // and +12 or -12 hours (timeOfDay). 1046 delta = amount / 2; 1047 timeOfDay = 12 * (amount % 2); 1048 break; 1049 } 1050 1051 // The time fields don't require time zone offset change 1052 // adjustment. 1053 if (field >= HOUR) { 1054 setTimeInMillis(time + delta); 1055 return; 1056 } 1057 1058 // The rest of the fields (week, day or AM_PM fields) 1059 // require time zone offset (both GMT and DST) change 1060 // adjustment. 1061 1062 // Translate the current time to the fixed date and time 1063 // of the day. 1064 long fd = getCurrentFixedDate(); 1065 timeOfDay += internalGet(HOUR_OF_DAY); 1066 timeOfDay *= 60; 1067 timeOfDay += internalGet(MINUTE); 1068 timeOfDay *= 60; 1069 timeOfDay += internalGet(SECOND); 1070 timeOfDay *= 1000; 1071 timeOfDay += internalGet(MILLISECOND); 1072 if (timeOfDay >= ONE_DAY) { 1073 fd++; 1074 timeOfDay -= ONE_DAY; 1075 } else if (timeOfDay < 0) { 1076 fd--; 1077 timeOfDay += ONE_DAY; 1078 } 1079 1080 fd += delta; // fd is the expected fixed date after the calculation 1081 1082 // Android changed: move time zone related calculation to separate method. 1083 // Calculate the time in the UTC time zone. 1084 long utcTime = (fd - EPOCH_OFFSET) * ONE_DAY + timeOfDay; 1085 1086 // Neither of the time zone related fields are relevant because they have not been 1087 // set since the call to complete() above. 1088 int tzMask = 0; 1089 1090 // Adjust the time to account for zone and daylight savings time offset. 1091 long millis = adjustForZoneAndDaylightSavingsTime(tzMask, utcTime, getZone()); 1092 1093 // Update the time and recompute the fields. 1094 setTimeInMillis(millis); 1095 } 1096 } 1097 1098 /** 1099 * Adds or subtracts (up/down) a single unit of time on the given time 1100 * field without changing larger fields. 1101 * <p> 1102 * <em>Example</em>: Consider a <code>GregorianCalendar</code> 1103 * originally set to December 31, 1999. Calling {@link #roll(int,boolean) roll(Calendar.MONTH, true)} 1104 * sets the calendar to January 31, 1999. The <code>YEAR</code> field is unchanged 1105 * because it is a larger field than <code>MONTH</code>.</p> 1106 * 1107 * @param up indicates if the value of the specified calendar field is to be 1108 * rolled up or rolled down. Use <code>true</code> if rolling up, <code>false</code> otherwise. 1109 * @exception IllegalArgumentException if <code>field</code> is 1110 * <code>ZONE_OFFSET</code>, <code>DST_OFFSET</code>, or unknown, 1111 * or if any calendar fields have out-of-range values in 1112 * non-lenient mode. 1113 * @see #add(int,int) 1114 * @see #set(int,int) 1115 */ 1116 @Override 1117 public void roll(int field, boolean up) { 1118 roll(field, up ? +1 : -1); 1119 } 1120 1121 /** 1122 * Adds a signed amount to the specified calendar field without changing larger fields. 1123 * A negative roll amount means to subtract from field without changing 1124 * larger fields. If the specified amount is 0, this method performs nothing. 1125 * 1126 * <p>This method calls {@link #complete()} before adding the 1127 * amount so that all the calendar fields are normalized. If there 1128 * is any calendar field having an out-of-range value in non-lenient mode, then an 1129 * <code>IllegalArgumentException</code> is thrown. 1130 * 1131 * <p> 1132 * <em>Example</em>: Consider a <code>GregorianCalendar</code> 1133 * originally set to August 31, 1999. Calling <code>roll(Calendar.MONTH, 1134 * 8)</code> sets the calendar to April 30, <strong>1999</strong>. Using a 1135 * <code>GregorianCalendar</code>, the <code>DAY_OF_MONTH</code> field cannot 1136 * be 31 in the month April. <code>DAY_OF_MONTH</code> is set to the closest possible 1137 * value, 30. The <code>YEAR</code> field maintains the value of 1999 because it 1138 * is a larger field than <code>MONTH</code>. 1139 * <p> 1140 * <em>Example</em>: Consider a <code>GregorianCalendar</code> 1141 * originally set to Sunday June 6, 1999. Calling 1142 * <code>roll(Calendar.WEEK_OF_MONTH, -1)</code> sets the calendar to 1143 * Tuesday June 1, 1999, whereas calling 1144 * <code>add(Calendar.WEEK_OF_MONTH, -1)</code> sets the calendar to 1145 * Sunday May 30, 1999. This is because the roll rule imposes an 1146 * additional constraint: The <code>MONTH</code> must not change when the 1147 * <code>WEEK_OF_MONTH</code> is rolled. Taken together with add rule 1, 1148 * the resultant date must be between Tuesday June 1 and Saturday June 1149 * 5. According to add rule 2, the <code>DAY_OF_WEEK</code>, an invariant 1150 * when changing the <code>WEEK_OF_MONTH</code>, is set to Tuesday, the 1151 * closest possible value to Sunday (where Sunday is the first day of the 1152 * week).</p> 1153 * 1154 * @param field the calendar field. 1155 * @param amount the signed amount to add to <code>field</code>. 1156 * @exception IllegalArgumentException if <code>field</code> is 1157 * <code>ZONE_OFFSET</code>, <code>DST_OFFSET</code>, or unknown, 1158 * or if any calendar fields have out-of-range values in 1159 * non-lenient mode. 1160 * @see #roll(int,boolean) 1161 * @see #add(int,int) 1162 * @see #set(int,int) 1163 * @since 1.2 1164 */ 1165 @Override 1166 public void roll(int field, int amount) { 1167 // If amount == 0, do nothing even the given field is out of 1168 // range. This is tested by JCK. 1169 if (amount == 0) { 1170 return; 1171 } 1172 1173 if (field < 0 || field >= ZONE_OFFSET) { 1174 throw new IllegalArgumentException(); 1175 } 1176 1177 // Sync the time and calendar fields. 1178 complete(); 1179 1180 int min = getMinimum(field); 1181 int max = getMaximum(field); 1182 1183 switch (field) { 1184 case AM_PM: 1185 case ERA: 1186 case YEAR: 1187 case MINUTE: 1188 case SECOND: 1189 case MILLISECOND: 1190 // These fields are handled simply, since they have fixed minima 1191 // and maxima. The field DAY_OF_MONTH is almost as simple. Other 1192 // fields are complicated, since the range within they must roll 1193 // varies depending on the date. 1194 break; 1195 1196 case HOUR: 1197 case HOUR_OF_DAY: 1198 { 1199 int unit = max + 1; // 12 or 24 hours 1200 int h = internalGet(field); 1201 int nh = (h + amount) % unit; 1202 if (nh < 0) { 1203 nh += unit; 1204 } 1205 time += ONE_HOUR * (nh - h); 1206 1207 // The day might have changed, which could happen if 1208 // the daylight saving time transition brings it to 1209 // the next day, although it's very unlikely. But we 1210 // have to make sure not to change the larger fields. 1211 CalendarDate d = calsys.getCalendarDate(time, getZone()); 1212 if (internalGet(DAY_OF_MONTH) != d.getDayOfMonth()) { 1213 d.setDate(internalGet(YEAR), 1214 internalGet(MONTH) + 1, 1215 internalGet(DAY_OF_MONTH)); 1216 if (field == HOUR) { 1217 assert (internalGet(AM_PM) == PM); 1218 d.addHours(+12); // restore PM 1219 } 1220 time = calsys.getTime(d); 1221 } 1222 int hourOfDay = d.getHours(); 1223 internalSet(field, hourOfDay % unit); 1224 if (field == HOUR) { 1225 internalSet(HOUR_OF_DAY, hourOfDay); 1226 } else { 1227 internalSet(AM_PM, hourOfDay / 12); 1228 internalSet(HOUR, hourOfDay % 12); 1229 } 1230 1231 // Time zone offset and/or daylight saving might have changed. 1232 int zoneOffset = d.getZoneOffset(); 1233 int saving = d.getDaylightSaving(); 1234 internalSet(ZONE_OFFSET, zoneOffset - saving); 1235 internalSet(DST_OFFSET, saving); 1236 return; 1237 } 1238 1239 case MONTH: 1240 // Rolling the month involves both pinning the final value to [0, 11] 1241 // and adjusting the DAY_OF_MONTH if necessary. We only adjust the 1242 // DAY_OF_MONTH if, after updating the MONTH field, it is illegal. 1243 // E.g., <jan31>.roll(MONTH, 1) -> <feb28> or <feb29>. 1244 { 1245 if (!isCutoverYear(cdate.getNormalizedYear())) { 1246 int mon = (internalGet(MONTH) + amount) % 12; 1247 if (mon < 0) { 1248 mon += 12; 1249 } 1250 set(MONTH, mon); 1251 1252 // Keep the day of month in the range. We don't want to spill over 1253 // into the next month; e.g., we don't want jan31 + 1 mo -> feb31 -> 1254 // mar3. 1255 int monthLen = monthLength(mon); 1256 if (internalGet(DAY_OF_MONTH) > monthLen) { 1257 set(DAY_OF_MONTH, monthLen); 1258 } 1259 } else { 1260 // We need to take care of different lengths in 1261 // year and month due to the cutover. 1262 int yearLength = getActualMaximum(MONTH) + 1; 1263 int mon = (internalGet(MONTH) + amount) % yearLength; 1264 if (mon < 0) { 1265 mon += yearLength; 1266 } 1267 set(MONTH, mon); 1268 int monthLen = getActualMaximum(DAY_OF_MONTH); 1269 if (internalGet(DAY_OF_MONTH) > monthLen) { 1270 set(DAY_OF_MONTH, monthLen); 1271 } 1272 } 1273 return; 1274 } 1275 1276 case WEEK_OF_YEAR: 1277 { 1278 int y = cdate.getNormalizedYear(); 1279 max = getActualMaximum(WEEK_OF_YEAR); 1280 set(DAY_OF_WEEK, internalGet(DAY_OF_WEEK)); 1281 int woy = internalGet(WEEK_OF_YEAR); 1282 int value = woy + amount; 1283 if (!isCutoverYear(y)) { 1284 int weekYear = getWeekYear(); 1285 if (weekYear == y) { 1286 // If the new value is in between min and max 1287 // (exclusive), then we can use the value. 1288 if (value > min && value < max) { 1289 set(WEEK_OF_YEAR, value); 1290 return; 1291 } 1292 long fd = getCurrentFixedDate(); 1293 // Make sure that the min week has the current DAY_OF_WEEK 1294 // in the calendar year 1295 long day1 = fd - (7 * (woy - min)); 1296 if (calsys.getYearFromFixedDate(day1) != y) { 1297 min++; 1298 } 1299 1300 // Make sure the same thing for the max week 1301 fd += 7 * (max - internalGet(WEEK_OF_YEAR)); 1302 if (calsys.getYearFromFixedDate(fd) != y) { 1303 max--; 1304 } 1305 } else { 1306 // When WEEK_OF_YEAR and YEAR are out of sync, 1307 // adjust woy and amount to stay in the calendar year. 1308 if (weekYear > y) { 1309 if (amount < 0) { 1310 amount++; 1311 } 1312 woy = max; 1313 } else { 1314 if (amount > 0) { 1315 amount -= woy - max; 1316 } 1317 woy = min; 1318 } 1319 } 1320 set(field, getRolledValue(woy, amount, min, max)); 1321 return; 1322 } 1323 1324 // Handle cutover here. 1325 long fd = getCurrentFixedDate(); 1326 BaseCalendar cal; 1327 if (gregorianCutoverYear == gregorianCutoverYearJulian) { 1328 cal = getCutoverCalendarSystem(); 1329 } else if (y == gregorianCutoverYear) { 1330 cal = gcal; 1331 } else { 1332 cal = getJulianCalendarSystem(); 1333 } 1334 long day1 = fd - (7 * (woy - min)); 1335 // Make sure that the min week has the current DAY_OF_WEEK 1336 if (cal.getYearFromFixedDate(day1) != y) { 1337 min++; 1338 } 1339 1340 // Make sure the same thing for the max week 1341 fd += 7 * (max - woy); 1342 cal = (fd >= gregorianCutoverDate) ? gcal : getJulianCalendarSystem(); 1343 if (cal.getYearFromFixedDate(fd) != y) { 1344 max--; 1345 } 1346 // value: the new WEEK_OF_YEAR which must be converted 1347 // to month and day of month. 1348 value = getRolledValue(woy, amount, min, max) - 1; 1349 BaseCalendar.Date d = getCalendarDate(day1 + value * 7); 1350 set(MONTH, d.getMonth() - 1); 1351 set(DAY_OF_MONTH, d.getDayOfMonth()); 1352 return; 1353 } 1354 1355 case WEEK_OF_MONTH: 1356 { 1357 boolean isCutoverYear = isCutoverYear(cdate.getNormalizedYear()); 1358 // dow: relative day of week from first day of week 1359 int dow = internalGet(DAY_OF_WEEK) - getFirstDayOfWeek(); 1360 if (dow < 0) { 1361 dow += 7; 1362 } 1363 1364 long fd = getCurrentFixedDate(); 1365 long month1; // fixed date of the first day (usually 1) of the month 1366 int monthLength; // actual month length 1367 if (isCutoverYear) { 1368 month1 = getFixedDateMonth1(cdate, fd); 1369 monthLength = actualMonthLength(); 1370 } else { 1371 month1 = fd - internalGet(DAY_OF_MONTH) + 1; 1372 monthLength = calsys.getMonthLength(cdate); 1373 } 1374 1375 // the first day of week of the month. 1376 long monthDay1st = BaseCalendar.getDayOfWeekDateOnOrBefore(month1 + 6, 1377 getFirstDayOfWeek()); 1378 // if the week has enough days to form a week, the 1379 // week starts from the previous month. 1380 if ((int)(monthDay1st - month1) >= getMinimalDaysInFirstWeek()) { 1381 monthDay1st -= 7; 1382 } 1383 max = getActualMaximum(field); 1384 1385 // value: the new WEEK_OF_MONTH value 1386 int value = getRolledValue(internalGet(field), amount, 1, max) - 1; 1387 1388 // nfd: fixed date of the rolled date 1389 long nfd = monthDay1st + value * 7 + dow; 1390 1391 // Unlike WEEK_OF_YEAR, we need to change day of week if the 1392 // nfd is out of the month. 1393 if (nfd < month1) { 1394 nfd = month1; 1395 } else if (nfd >= (month1 + monthLength)) { 1396 nfd = month1 + monthLength - 1; 1397 } 1398 int dayOfMonth; 1399 if (isCutoverYear) { 1400 // If we are in the cutover year, convert nfd to 1401 // its calendar date and use dayOfMonth. 1402 BaseCalendar.Date d = getCalendarDate(nfd); 1403 dayOfMonth = d.getDayOfMonth(); 1404 } else { 1405 dayOfMonth = (int)(nfd - month1) + 1; 1406 } 1407 set(DAY_OF_MONTH, dayOfMonth); 1408 return; 1409 } 1410 1411 case DAY_OF_MONTH: 1412 { 1413 if (!isCutoverYear(cdate.getNormalizedYear())) { 1414 max = calsys.getMonthLength(cdate); 1415 break; 1416 } 1417 1418 // Cutover year handling 1419 long fd = getCurrentFixedDate(); 1420 long month1 = getFixedDateMonth1(cdate, fd); 1421 // It may not be a regular month. Convert the date and range to 1422 // the relative values, perform the roll, and 1423 // convert the result back to the rolled date. 1424 int value = getRolledValue((int)(fd - month1), amount, 0, actualMonthLength() - 1); 1425 BaseCalendar.Date d = getCalendarDate(month1 + value); 1426 assert d.getMonth()-1 == internalGet(MONTH); 1427 set(DAY_OF_MONTH, d.getDayOfMonth()); 1428 return; 1429 } 1430 1431 case DAY_OF_YEAR: 1432 { 1433 max = getActualMaximum(field); 1434 if (!isCutoverYear(cdate.getNormalizedYear())) { 1435 break; 1436 } 1437 1438 // Handle cutover here. 1439 long fd = getCurrentFixedDate(); 1440 long jan1 = fd - internalGet(DAY_OF_YEAR) + 1; 1441 int value = getRolledValue((int)(fd - jan1) + 1, amount, min, max); 1442 BaseCalendar.Date d = getCalendarDate(jan1 + value - 1); 1443 set(MONTH, d.getMonth() - 1); 1444 set(DAY_OF_MONTH, d.getDayOfMonth()); 1445 return; 1446 } 1447 1448 case DAY_OF_WEEK: 1449 { 1450 if (!isCutoverYear(cdate.getNormalizedYear())) { 1451 // If the week of year is in the same year, we can 1452 // just change DAY_OF_WEEK. 1453 int weekOfYear = internalGet(WEEK_OF_YEAR); 1454 if (weekOfYear > 1 && weekOfYear < 52) { 1455 set(WEEK_OF_YEAR, weekOfYear); // update stamp[WEEK_OF_YEAR] 1456 max = SATURDAY; 1457 break; 1458 } 1459 } 1460 1461 // We need to handle it in a different way around year 1462 // boundaries and in the cutover year. Note that 1463 // changing era and year values violates the roll 1464 // rule: not changing larger calendar fields... 1465 amount %= 7; 1466 if (amount == 0) { 1467 return; 1468 } 1469 long fd = getCurrentFixedDate(); 1470 long dowFirst = BaseCalendar.getDayOfWeekDateOnOrBefore(fd, getFirstDayOfWeek()); 1471 fd += amount; 1472 if (fd < dowFirst) { 1473 fd += 7; 1474 } else if (fd >= dowFirst + 7) { 1475 fd -= 7; 1476 } 1477 BaseCalendar.Date d = getCalendarDate(fd); 1478 set(ERA, (d.getNormalizedYear() <= 0 ? BCE : CE)); 1479 set(d.getYear(), d.getMonth() - 1, d.getDayOfMonth()); 1480 return; 1481 } 1482 1483 case DAY_OF_WEEK_IN_MONTH: 1484 { 1485 min = 1; // after normalized, min should be 1. 1486 if (!isCutoverYear(cdate.getNormalizedYear())) { 1487 int dom = internalGet(DAY_OF_MONTH); 1488 int monthLength = calsys.getMonthLength(cdate); 1489 int lastDays = monthLength % 7; 1490 max = monthLength / 7; 1491 int x = (dom - 1) % 7; 1492 if (x < lastDays) { 1493 max++; 1494 } 1495 set(DAY_OF_WEEK, internalGet(DAY_OF_WEEK)); 1496 break; 1497 } 1498 1499 // Cutover year handling 1500 long fd = getCurrentFixedDate(); 1501 long month1 = getFixedDateMonth1(cdate, fd); 1502 int monthLength = actualMonthLength(); 1503 int lastDays = monthLength % 7; 1504 max = monthLength / 7; 1505 int x = (int)(fd - month1) % 7; 1506 if (x < lastDays) { 1507 max++; 1508 } 1509 int value = getRolledValue(internalGet(field), amount, min, max) - 1; 1510 fd = month1 + value * 7 + x; 1511 BaseCalendar cal = (fd >= gregorianCutoverDate) ? gcal : getJulianCalendarSystem(); 1512 BaseCalendar.Date d = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.NO_TIMEZONE); 1513 cal.getCalendarDateFromFixedDate(d, fd); 1514 set(DAY_OF_MONTH, d.getDayOfMonth()); 1515 return; 1516 } 1517 } 1518 1519 set(field, getRolledValue(internalGet(field), amount, min, max)); 1520 } 1521 1522 /** 1523 * Returns the minimum value for the given calendar field of this 1524 * <code>GregorianCalendar</code> instance. The minimum value is 1525 * defined as the smallest value returned by the {@link 1526 * Calendar#get(int) get} method for any possible time value, 1527 * taking into consideration the current values of the 1528 * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek}, 1529 * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek}, 1530 * {@link #getGregorianChange() getGregorianChange} and 1531 * {@link Calendar#getTimeZone() getTimeZone} methods. 1532 * 1533 * @param field the calendar field. 1534 * @return the minimum value for the given calendar field. 1535 * @see #getMaximum(int) 1536 * @see #getGreatestMinimum(int) 1537 * @see #getLeastMaximum(int) 1538 * @see #getActualMinimum(int) 1539 * @see #getActualMaximum(int) 1540 */ 1541 @Override 1542 public int getMinimum(int field) { 1543 return MIN_VALUES[field]; 1544 } 1545 1546 /** 1547 * Returns the maximum value for the given calendar field of this 1548 * <code>GregorianCalendar</code> instance. The maximum value is 1549 * defined as the largest value returned by the {@link 1550 * Calendar#get(int) get} method for any possible time value, 1551 * taking into consideration the current values of the 1552 * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek}, 1553 * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek}, 1554 * {@link #getGregorianChange() getGregorianChange} and 1555 * {@link Calendar#getTimeZone() getTimeZone} methods. 1556 * 1557 * @param field the calendar field. 1558 * @return the maximum value for the given calendar field. 1559 * @see #getMinimum(int) 1560 * @see #getGreatestMinimum(int) 1561 * @see #getLeastMaximum(int) 1562 * @see #getActualMinimum(int) 1563 * @see #getActualMaximum(int) 1564 */ 1565 @Override 1566 public int getMaximum(int field) { 1567 switch (field) { 1568 case MONTH: 1569 case DAY_OF_MONTH: 1570 case DAY_OF_YEAR: 1571 case WEEK_OF_YEAR: 1572 case WEEK_OF_MONTH: 1573 case DAY_OF_WEEK_IN_MONTH: 1574 case YEAR: 1575 { 1576 // On or after Gregorian 200-3-1, Julian and Gregorian 1577 // calendar dates are the same or Gregorian dates are 1578 // larger (i.e., there is a "gap") after 300-3-1. 1579 if (gregorianCutoverYear > 200) { 1580 break; 1581 } 1582 // There might be "overlapping" dates. 1583 GregorianCalendar gc = (GregorianCalendar) clone(); 1584 gc.setLenient(true); 1585 gc.setTimeInMillis(gregorianCutover); 1586 int v1 = gc.getActualMaximum(field); 1587 gc.setTimeInMillis(gregorianCutover-1); 1588 int v2 = gc.getActualMaximum(field); 1589 return Math.max(MAX_VALUES[field], Math.max(v1, v2)); 1590 } 1591 } 1592 return MAX_VALUES[field]; 1593 } 1594 1595 /** 1596 * Returns the highest minimum value for the given calendar field 1597 * of this <code>GregorianCalendar</code> instance. The highest 1598 * minimum value is defined as the largest value returned by 1599 * {@link #getActualMinimum(int)} for any possible time value, 1600 * taking into consideration the current values of the 1601 * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek}, 1602 * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek}, 1603 * {@link #getGregorianChange() getGregorianChange} and 1604 * {@link Calendar#getTimeZone() getTimeZone} methods. 1605 * 1606 * @param field the calendar field. 1607 * @return the highest minimum value for the given calendar field. 1608 * @see #getMinimum(int) 1609 * @see #getMaximum(int) 1610 * @see #getLeastMaximum(int) 1611 * @see #getActualMinimum(int) 1612 * @see #getActualMaximum(int) 1613 */ 1614 @Override 1615 public int getGreatestMinimum(int field) { 1616 if (field == DAY_OF_MONTH) { 1617 BaseCalendar.Date d = getGregorianCutoverDate(); 1618 long mon1 = getFixedDateMonth1(d, gregorianCutoverDate); 1619 d = getCalendarDate(mon1); 1620 return Math.max(MIN_VALUES[field], d.getDayOfMonth()); 1621 } 1622 return MIN_VALUES[field]; 1623 } 1624 1625 /** 1626 * Returns the lowest maximum value for the given calendar field 1627 * of this <code>GregorianCalendar</code> instance. The lowest 1628 * maximum value is defined as the smallest value returned by 1629 * {@link #getActualMaximum(int)} for any possible time value, 1630 * taking into consideration the current values of the 1631 * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek}, 1632 * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek}, 1633 * {@link #getGregorianChange() getGregorianChange} and 1634 * {@link Calendar#getTimeZone() getTimeZone} methods. 1635 * 1636 * @param field the calendar field 1637 * @return the lowest maximum value for the given calendar field. 1638 * @see #getMinimum(int) 1639 * @see #getMaximum(int) 1640 * @see #getGreatestMinimum(int) 1641 * @see #getActualMinimum(int) 1642 * @see #getActualMaximum(int) 1643 */ 1644 @Override 1645 public int getLeastMaximum(int field) { 1646 switch (field) { 1647 case MONTH: 1648 case DAY_OF_MONTH: 1649 case DAY_OF_YEAR: 1650 case WEEK_OF_YEAR: 1651 case WEEK_OF_MONTH: 1652 case DAY_OF_WEEK_IN_MONTH: 1653 case YEAR: 1654 { 1655 GregorianCalendar gc = (GregorianCalendar) clone(); 1656 gc.setLenient(true); 1657 gc.setTimeInMillis(gregorianCutover); 1658 int v1 = gc.getActualMaximum(field); 1659 gc.setTimeInMillis(gregorianCutover-1); 1660 int v2 = gc.getActualMaximum(field); 1661 return Math.min(LEAST_MAX_VALUES[field], Math.min(v1, v2)); 1662 } 1663 } 1664 return LEAST_MAX_VALUES[field]; 1665 } 1666 1667 /** 1668 * Returns the minimum value that this calendar field could have, 1669 * taking into consideration the given time value and the current 1670 * values of the 1671 * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek}, 1672 * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek}, 1673 * {@link #getGregorianChange() getGregorianChange} and 1674 * {@link Calendar#getTimeZone() getTimeZone} methods. 1675 * 1676 * <p>For example, if the Gregorian change date is January 10, 1677 * 1970 and the date of this <code>GregorianCalendar</code> is 1678 * January 20, 1970, the actual minimum value of the 1679 * <code>DAY_OF_MONTH</code> field is 10 because the previous date 1680 * of January 10, 1970 is December 27, 1996 (in the Julian 1681 * calendar). Therefore, December 28, 1969 to January 9, 1970 1682 * don't exist. 1683 * 1684 * @param field the calendar field 1685 * @return the minimum of the given field for the time value of 1686 * this <code>GregorianCalendar</code> 1687 * @see #getMinimum(int) 1688 * @see #getMaximum(int) 1689 * @see #getGreatestMinimum(int) 1690 * @see #getLeastMaximum(int) 1691 * @see #getActualMaximum(int) 1692 * @since 1.2 1693 */ 1694 @Override 1695 public int getActualMinimum(int field) { 1696 if (field == DAY_OF_MONTH) { 1697 GregorianCalendar gc = getNormalizedCalendar(); 1698 int year = gc.cdate.getNormalizedYear(); 1699 if (year == gregorianCutoverYear || year == gregorianCutoverYearJulian) { 1700 long month1 = getFixedDateMonth1(gc.cdate, gc.calsys.getFixedDate(gc.cdate)); 1701 BaseCalendar.Date d = getCalendarDate(month1); 1702 return d.getDayOfMonth(); 1703 } 1704 } 1705 return getMinimum(field); 1706 } 1707 1708 /** 1709 * Returns the maximum value that this calendar field could have, 1710 * taking into consideration the given time value and the current 1711 * values of the 1712 * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek}, 1713 * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek}, 1714 * {@link #getGregorianChange() getGregorianChange} and 1715 * {@link Calendar#getTimeZone() getTimeZone} methods. 1716 * For example, if the date of this instance is February 1, 2004, 1717 * the actual maximum value of the <code>DAY_OF_MONTH</code> field 1718 * is 29 because 2004 is a leap year, and if the date of this 1719 * instance is February 1, 2005, it's 28. 1720 * 1721 * <p>This method calculates the maximum value of {@link 1722 * Calendar#WEEK_OF_YEAR WEEK_OF_YEAR} based on the {@link 1723 * Calendar#YEAR YEAR} (calendar year) value, not the <a 1724 * href="#week_year">week year</a>. Call {@link 1725 * #getWeeksInWeekYear()} to get the maximum value of {@code 1726 * WEEK_OF_YEAR} in the week year of this {@code GregorianCalendar}. 1727 * 1728 * @param field the calendar field 1729 * @return the maximum of the given field for the time value of 1730 * this <code>GregorianCalendar</code> 1731 * @see #getMinimum(int) 1732 * @see #getMaximum(int) 1733 * @see #getGreatestMinimum(int) 1734 * @see #getLeastMaximum(int) 1735 * @see #getActualMinimum(int) 1736 * @since 1.2 1737 */ 1738 @Override 1739 public int getActualMaximum(int field) { 1740 final int fieldsForFixedMax = ERA_MASK|DAY_OF_WEEK_MASK|HOUR_MASK|AM_PM_MASK| 1741 HOUR_OF_DAY_MASK|MINUTE_MASK|SECOND_MASK|MILLISECOND_MASK| 1742 ZONE_OFFSET_MASK|DST_OFFSET_MASK; 1743 if ((fieldsForFixedMax & (1<<field)) != 0) { 1744 return getMaximum(field); 1745 } 1746 1747 GregorianCalendar gc = getNormalizedCalendar(); 1748 BaseCalendar.Date date = gc.cdate; 1749 BaseCalendar cal = gc.calsys; 1750 int normalizedYear = date.getNormalizedYear(); 1751 1752 int value = -1; 1753 switch (field) { 1754 case MONTH: 1755 { 1756 if (!gc.isCutoverYear(normalizedYear)) { 1757 value = DECEMBER; 1758 break; 1759 } 1760 1761 // January 1 of the next year may or may not exist. 1762 long nextJan1; 1763 do { 1764 nextJan1 = gcal.getFixedDate(++normalizedYear, BaseCalendar.JANUARY, 1, null); 1765 } while (nextJan1 < gregorianCutoverDate); 1766 BaseCalendar.Date d = (BaseCalendar.Date) date.clone(); 1767 cal.getCalendarDateFromFixedDate(d, nextJan1 - 1); 1768 value = d.getMonth() - 1; 1769 } 1770 break; 1771 1772 case DAY_OF_MONTH: 1773 { 1774 value = cal.getMonthLength(date); 1775 if (!gc.isCutoverYear(normalizedYear) || date.getDayOfMonth() == value) { 1776 break; 1777 } 1778 1779 // Handle cutover year. 1780 long fd = gc.getCurrentFixedDate(); 1781 if (fd >= gregorianCutoverDate) { 1782 break; 1783 } 1784 int monthLength = gc.actualMonthLength(); 1785 long monthEnd = gc.getFixedDateMonth1(gc.cdate, fd) + monthLength - 1; 1786 // Convert the fixed date to its calendar date. 1787 BaseCalendar.Date d = gc.getCalendarDate(monthEnd); 1788 value = d.getDayOfMonth(); 1789 } 1790 break; 1791 1792 case DAY_OF_YEAR: 1793 { 1794 if (!gc.isCutoverYear(normalizedYear)) { 1795 value = cal.getYearLength(date); 1796 break; 1797 } 1798 1799 // Handle cutover year. 1800 long jan1; 1801 if (gregorianCutoverYear == gregorianCutoverYearJulian) { 1802 BaseCalendar cocal = gc.getCutoverCalendarSystem(); 1803 jan1 = cocal.getFixedDate(normalizedYear, 1, 1, null); 1804 } else if (normalizedYear == gregorianCutoverYearJulian) { 1805 jan1 = cal.getFixedDate(normalizedYear, 1, 1, null); 1806 } else { 1807 jan1 = gregorianCutoverDate; 1808 } 1809 // January 1 of the next year may or may not exist. 1810 long nextJan1 = gcal.getFixedDate(++normalizedYear, 1, 1, null); 1811 if (nextJan1 < gregorianCutoverDate) { 1812 nextJan1 = gregorianCutoverDate; 1813 } 1814 assert jan1 <= cal.getFixedDate(date.getNormalizedYear(), date.getMonth(), 1815 date.getDayOfMonth(), date); 1816 assert nextJan1 >= cal.getFixedDate(date.getNormalizedYear(), date.getMonth(), 1817 date.getDayOfMonth(), date); 1818 value = (int)(nextJan1 - jan1); 1819 } 1820 break; 1821 1822 case WEEK_OF_YEAR: 1823 { 1824 if (!gc.isCutoverYear(normalizedYear)) { 1825 // Get the day of week of January 1 of the year 1826 CalendarDate d = cal.newCalendarDate(TimeZone.NO_TIMEZONE); 1827 d.setDate(date.getYear(), BaseCalendar.JANUARY, 1); 1828 int dayOfWeek = cal.getDayOfWeek(d); 1829 // Normalize the day of week with the firstDayOfWeek value 1830 dayOfWeek -= getFirstDayOfWeek(); 1831 if (dayOfWeek < 0) { 1832 dayOfWeek += 7; 1833 } 1834 value = 52; 1835 int magic = dayOfWeek + getMinimalDaysInFirstWeek() - 1; 1836 if ((magic == 6) || 1837 (date.isLeapYear() && (magic == 5 || magic == 12))) { 1838 value++; 1839 } 1840 break; 1841 } 1842 1843 if (gc == this) { 1844 gc = (GregorianCalendar) gc.clone(); 1845 } 1846 int maxDayOfYear = getActualMaximum(DAY_OF_YEAR); 1847 gc.set(DAY_OF_YEAR, maxDayOfYear); 1848 value = gc.get(WEEK_OF_YEAR); 1849 if (internalGet(YEAR) != gc.getWeekYear()) { 1850 gc.set(DAY_OF_YEAR, maxDayOfYear - 7); 1851 value = gc.get(WEEK_OF_YEAR); 1852 } 1853 } 1854 break; 1855 1856 case WEEK_OF_MONTH: 1857 { 1858 if (!gc.isCutoverYear(normalizedYear)) { 1859 CalendarDate d = cal.newCalendarDate(null); 1860 d.setDate(date.getYear(), date.getMonth(), 1); 1861 int dayOfWeek = cal.getDayOfWeek(d); 1862 int monthLength = cal.getMonthLength(d); 1863 dayOfWeek -= getFirstDayOfWeek(); 1864 if (dayOfWeek < 0) { 1865 dayOfWeek += 7; 1866 } 1867 int nDaysFirstWeek = 7 - dayOfWeek; // # of days in the first week 1868 value = 3; 1869 if (nDaysFirstWeek >= getMinimalDaysInFirstWeek()) { 1870 value++; 1871 } 1872 monthLength -= nDaysFirstWeek + 7 * 3; 1873 if (monthLength > 0) { 1874 value++; 1875 if (monthLength > 7) { 1876 value++; 1877 } 1878 } 1879 break; 1880 } 1881 1882 // Cutover year handling 1883 if (gc == this) { 1884 gc = (GregorianCalendar) gc.clone(); 1885 } 1886 int y = gc.internalGet(YEAR); 1887 int m = gc.internalGet(MONTH); 1888 do { 1889 value = gc.get(WEEK_OF_MONTH); 1890 gc.add(WEEK_OF_MONTH, +1); 1891 } while (gc.get(YEAR) == y && gc.get(MONTH) == m); 1892 } 1893 break; 1894 1895 case DAY_OF_WEEK_IN_MONTH: 1896 { 1897 // may be in the Gregorian cutover month 1898 int ndays, dow1; 1899 int dow = date.getDayOfWeek(); 1900 if (!gc.isCutoverYear(normalizedYear)) { 1901 BaseCalendar.Date d = (BaseCalendar.Date) date.clone(); 1902 ndays = cal.getMonthLength(d); 1903 d.setDayOfMonth(1); 1904 cal.normalize(d); 1905 dow1 = d.getDayOfWeek(); 1906 } else { 1907 // Let a cloned GregorianCalendar take care of the cutover cases. 1908 if (gc == this) { 1909 gc = (GregorianCalendar) clone(); 1910 } 1911 ndays = gc.actualMonthLength(); 1912 gc.set(DAY_OF_MONTH, gc.getActualMinimum(DAY_OF_MONTH)); 1913 dow1 = gc.get(DAY_OF_WEEK); 1914 } 1915 int x = dow - dow1; 1916 if (x < 0) { 1917 x += 7; 1918 } 1919 ndays -= x; 1920 value = (ndays + 6) / 7; 1921 } 1922 break; 1923 1924 case YEAR: 1925 /* The year computation is no different, in principle, from the 1926 * others, however, the range of possible maxima is large. In 1927 * addition, the way we know we've exceeded the range is different. 1928 * For these reasons, we use the special case code below to handle 1929 * this field. 1930 * 1931 * The actual maxima for YEAR depend on the type of calendar: 1932 * 1933 * Gregorian = May 17, 292275056 BCE - Aug 17, 292278994 CE 1934 * Julian = Dec 2, 292269055 BCE - Jan 3, 292272993 CE 1935 * Hybrid = Dec 2, 292269055 BCE - Aug 17, 292278994 CE 1936 * 1937 * We know we've exceeded the maximum when either the month, date, 1938 * time, or era changes in response to setting the year. We don't 1939 * check for month, date, and time here because the year and era are 1940 * sufficient to detect an invalid year setting. NOTE: If code is 1941 * added to check the month and date in the future for some reason, 1942 * Feb 29 must be allowed to shift to Mar 1 when setting the year. 1943 */ 1944 { 1945 if (gc == this) { 1946 gc = (GregorianCalendar) clone(); 1947 } 1948 1949 // Calculate the millisecond offset from the beginning 1950 // of the year of this calendar and adjust the max 1951 // year value if we are beyond the limit in the max 1952 // year. 1953 long current = gc.getYearOffsetInMillis(); 1954 1955 if (gc.internalGetEra() == CE) { 1956 gc.setTimeInMillis(Long.MAX_VALUE); 1957 value = gc.get(YEAR); 1958 long maxEnd = gc.getYearOffsetInMillis(); 1959 if (current > maxEnd) { 1960 value--; 1961 } 1962 } else { 1963 CalendarSystem mincal = gc.getTimeInMillis() >= gregorianCutover ? 1964 gcal : getJulianCalendarSystem(); 1965 CalendarDate d = mincal.getCalendarDate(Long.MIN_VALUE, getZone()); 1966 long maxEnd = (cal.getDayOfYear(d) - 1) * 24 + d.getHours(); 1967 maxEnd *= 60; 1968 maxEnd += d.getMinutes(); 1969 maxEnd *= 60; 1970 maxEnd += d.getSeconds(); 1971 maxEnd *= 1000; 1972 maxEnd += d.getMillis(); 1973 value = d.getYear(); 1974 if (value <= 0) { 1975 assert mincal == gcal; 1976 value = 1 - value; 1977 } 1978 if (current < maxEnd) { 1979 value--; 1980 } 1981 } 1982 } 1983 break; 1984 1985 default: 1986 throw new ArrayIndexOutOfBoundsException(field); 1987 } 1988 return value; 1989 } 1990 1991 /** 1992 * Returns the millisecond offset from the beginning of this 1993 * year. This Calendar object must have been normalized. 1994 */ 1995 private long getYearOffsetInMillis() { 1996 long t = (internalGet(DAY_OF_YEAR) - 1) * 24; 1997 t += internalGet(HOUR_OF_DAY); 1998 t *= 60; 1999 t += internalGet(MINUTE); 2000 t *= 60; 2001 t += internalGet(SECOND); 2002 t *= 1000; 2003 return t + internalGet(MILLISECOND) - 2004 (internalGet(ZONE_OFFSET) + internalGet(DST_OFFSET)); 2005 } 2006 2007 @Override 2008 public Object clone() 2009 { 2010 GregorianCalendar other = (GregorianCalendar) super.clone(); 2011 2012 other.gdate = (BaseCalendar.Date) gdate.clone(); 2013 if (cdate != null) { 2014 if (cdate != gdate) { 2015 other.cdate = (BaseCalendar.Date) cdate.clone(); 2016 } else { 2017 other.cdate = other.gdate; 2018 } 2019 } 2020 other.originalFields = null; 2021 other.zoneOffsets = null; 2022 return other; 2023 } 2024 2025 @Override 2026 public TimeZone getTimeZone() { 2027 TimeZone zone = super.getTimeZone(); 2028 // To share the zone by CalendarDates 2029 gdate.setZone(zone); 2030 if (cdate != null && cdate != gdate) { 2031 cdate.setZone(zone); 2032 } 2033 return zone; 2034 } 2035 2036 @Override 2037 public void setTimeZone(TimeZone zone) { 2038 super.setTimeZone(zone); 2039 // To share the zone by CalendarDates 2040 gdate.setZone(zone); 2041 if (cdate != null && cdate != gdate) { 2042 cdate.setZone(zone); 2043 } 2044 } 2045 2046 /** 2047 * Returns {@code true} indicating this {@code GregorianCalendar} 2048 * supports week dates. 2049 * 2050 * @return {@code true} (always) 2051 * @see #getWeekYear() 2052 * @see #setWeekDate(int,int,int) 2053 * @see #getWeeksInWeekYear() 2054 * @since 1.7 2055 */ 2056 @Override 2057 public final boolean isWeekDateSupported() { 2058 return true; 2059 } 2060 2061 /** 2062 * Returns the <a href="#week_year">week year</a> represented by this 2063 * {@code GregorianCalendar}. The dates in the weeks between 1 and the 2064 * maximum week number of the week year have the same week year value 2065 * that may be one year before or after the {@link Calendar#YEAR YEAR} 2066 * (calendar year) value. 2067 * 2068 * <p>This method calls {@link Calendar#complete()} before 2069 * calculating the week year. 2070 * 2071 * @return the week year represented by this {@code GregorianCalendar}. 2072 * If the {@link Calendar#ERA ERA} value is {@link #BC}, the year is 2073 * represented by 0 or a negative number: BC 1 is 0, BC 2 2074 * is -1, BC 3 is -2, and so on. 2075 * @throws IllegalArgumentException 2076 * if any of the calendar fields is invalid in non-lenient mode. 2077 * @see #isWeekDateSupported() 2078 * @see #getWeeksInWeekYear() 2079 * @see Calendar#getFirstDayOfWeek() 2080 * @see Calendar#getMinimalDaysInFirstWeek() 2081 * @since 1.7 2082 */ 2083 @Override 2084 public int getWeekYear() { 2085 int year = get(YEAR); // implicitly calls complete() 2086 if (internalGetEra() == BCE) { 2087 year = 1 - year; 2088 } 2089 2090 // Fast path for the Gregorian calendar years that are never 2091 // affected by the Julian-Gregorian transition 2092 if (year > gregorianCutoverYear + 1) { 2093 int weekOfYear = internalGet(WEEK_OF_YEAR); 2094 if (internalGet(MONTH) == JANUARY) { 2095 if (weekOfYear >= 52) { 2096 --year; 2097 } 2098 } else { 2099 if (weekOfYear == 1) { 2100 ++year; 2101 } 2102 } 2103 return year; 2104 } 2105 2106 // General (slow) path 2107 int dayOfYear = internalGet(DAY_OF_YEAR); 2108 int maxDayOfYear = getActualMaximum(DAY_OF_YEAR); 2109 int minimalDays = getMinimalDaysInFirstWeek(); 2110 2111 // Quickly check the possibility of year adjustments before 2112 // cloning this GregorianCalendar. 2113 if (dayOfYear > minimalDays && dayOfYear < (maxDayOfYear - 6)) { 2114 return year; 2115 } 2116 2117 // Create a clone to work on the calculation 2118 GregorianCalendar cal = (GregorianCalendar) clone(); 2119 cal.setLenient(true); 2120 // Use GMT so that intermediate date calculations won't 2121 // affect the time of day fields. 2122 cal.setTimeZone(TimeZone.getTimeZone("GMT")); 2123 // Go to the first day of the year, which is usually January 1. 2124 cal.set(DAY_OF_YEAR, 1); 2125 cal.complete(); 2126 2127 // Get the first day of the first day-of-week in the year. 2128 int delta = getFirstDayOfWeek() - cal.get(DAY_OF_WEEK); 2129 if (delta != 0) { 2130 if (delta < 0) { 2131 delta += 7; 2132 } 2133 cal.add(DAY_OF_YEAR, delta); 2134 } 2135 int minDayOfYear = cal.get(DAY_OF_YEAR); 2136 if (dayOfYear < minDayOfYear) { 2137 if (minDayOfYear <= minimalDays) { 2138 --year; 2139 } 2140 } else { 2141 cal.set(YEAR, year + 1); 2142 cal.set(DAY_OF_YEAR, 1); 2143 cal.complete(); 2144 int del = getFirstDayOfWeek() - cal.get(DAY_OF_WEEK); 2145 if (del != 0) { 2146 if (del < 0) { 2147 del += 7; 2148 } 2149 cal.add(DAY_OF_YEAR, del); 2150 } 2151 minDayOfYear = cal.get(DAY_OF_YEAR) - 1; 2152 if (minDayOfYear == 0) { 2153 minDayOfYear = 7; 2154 } 2155 if (minDayOfYear >= minimalDays) { 2156 int days = maxDayOfYear - dayOfYear + 1; 2157 if (days <= (7 - minDayOfYear)) { 2158 ++year; 2159 } 2160 } 2161 } 2162 return year; 2163 } 2164 2165 /** 2166 * Sets this {@code GregorianCalendar} to the date given by the 2167 * date specifiers - <a href="#week_year">{@code weekYear}</a>, 2168 * {@code weekOfYear}, and {@code dayOfWeek}. {@code weekOfYear} 2169 * follows the <a href="#week_and_year">{@code WEEK_OF_YEAR} 2170 * numbering</a>. The {@code dayOfWeek} value must be one of the 2171 * {@link Calendar#DAY_OF_WEEK DAY_OF_WEEK} values: {@link 2172 * Calendar#SUNDAY SUNDAY} to {@link Calendar#SATURDAY SATURDAY}. 2173 * 2174 * <p>Note that the numeric day-of-week representation differs from 2175 * the ISO 8601 standard, and that the {@code weekOfYear} 2176 * numbering is compatible with the standard when {@code 2177 * getFirstDayOfWeek()} is {@code MONDAY} and {@code 2178 * getMinimalDaysInFirstWeek()} is 4. 2179 * 2180 * <p>Unlike the {@code set} method, all of the calendar fields 2181 * and the instant of time value are calculated upon return. 2182 * 2183 * <p>If {@code weekOfYear} is out of the valid week-of-year 2184 * range in {@code weekYear}, the {@code weekYear} 2185 * and {@code weekOfYear} values are adjusted in lenient 2186 * mode, or an {@code IllegalArgumentException} is thrown in 2187 * non-lenient mode. 2188 * 2189 * @param weekYear the week year 2190 * @param weekOfYear the week number based on {@code weekYear} 2191 * @param dayOfWeek the day of week value: one of the constants 2192 * for the {@link #DAY_OF_WEEK DAY_OF_WEEK} field: 2193 * {@link Calendar#SUNDAY SUNDAY}, ..., 2194 * {@link Calendar#SATURDAY SATURDAY}. 2195 * @exception IllegalArgumentException 2196 * if any of the given date specifiers is invalid, 2197 * or if any of the calendar fields are inconsistent 2198 * with the given date specifiers in non-lenient mode 2199 * @see GregorianCalendar#isWeekDateSupported() 2200 * @see Calendar#getFirstDayOfWeek() 2201 * @see Calendar#getMinimalDaysInFirstWeek() 2202 * @since 1.7 2203 */ 2204 @Override 2205 public void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) { 2206 if (dayOfWeek < SUNDAY || dayOfWeek > SATURDAY) { 2207 throw new IllegalArgumentException("invalid dayOfWeek: " + dayOfWeek); 2208 } 2209 2210 // To avoid changing the time of day fields by date 2211 // calculations, use a clone with the GMT time zone. 2212 GregorianCalendar gc = (GregorianCalendar) clone(); 2213 gc.setLenient(true); 2214 int era = gc.get(ERA); 2215 gc.clear(); 2216 gc.setTimeZone(TimeZone.getTimeZone("GMT")); 2217 gc.set(ERA, era); 2218 gc.set(YEAR, weekYear); 2219 gc.set(WEEK_OF_YEAR, 1); 2220 gc.set(DAY_OF_WEEK, getFirstDayOfWeek()); 2221 int days = dayOfWeek - getFirstDayOfWeek(); 2222 if (days < 0) { 2223 days += 7; 2224 } 2225 days += 7 * (weekOfYear - 1); 2226 if (days != 0) { 2227 gc.add(DAY_OF_YEAR, days); 2228 } else { 2229 gc.complete(); 2230 } 2231 2232 if (!isLenient() && 2233 (gc.getWeekYear() != weekYear 2234 || gc.internalGet(WEEK_OF_YEAR) != weekOfYear 2235 || gc.internalGet(DAY_OF_WEEK) != dayOfWeek)) { 2236 throw new IllegalArgumentException(); 2237 } 2238 2239 set(ERA, gc.internalGet(ERA)); 2240 set(YEAR, gc.internalGet(YEAR)); 2241 set(MONTH, gc.internalGet(MONTH)); 2242 set(DAY_OF_MONTH, gc.internalGet(DAY_OF_MONTH)); 2243 2244 // to avoid throwing an IllegalArgumentException in 2245 // non-lenient, set WEEK_OF_YEAR internally 2246 internalSet(WEEK_OF_YEAR, weekOfYear); 2247 complete(); 2248 } 2249 2250 /** 2251 * Returns the number of weeks in the <a href="#week_year">week year</a> 2252 * represented by this {@code GregorianCalendar}. 2253 * 2254 * <p>For example, if this {@code GregorianCalendar}'s date is 2255 * December 31, 2008 with <a href="#iso8601_compatible_setting">the ISO 2256 * 8601 compatible setting</a>, this method will return 53 for the 2257 * period: December 29, 2008 to January 3, 2010 while {@link 2258 * #getActualMaximum(int) getActualMaximum(WEEK_OF_YEAR)} will return 2259 * 52 for the period: December 31, 2007 to December 28, 2008. 2260 * 2261 * @return the number of weeks in the week year. 2262 * @see Calendar#WEEK_OF_YEAR 2263 * @see #getWeekYear() 2264 * @see #getActualMaximum(int) 2265 * @since 1.7 2266 */ 2267 @Override 2268 public int getWeeksInWeekYear() { 2269 GregorianCalendar gc = getNormalizedCalendar(); 2270 int weekYear = gc.getWeekYear(); 2271 if (weekYear == gc.internalGet(YEAR)) { 2272 return gc.getActualMaximum(WEEK_OF_YEAR); 2273 } 2274 2275 // Use the 2nd week for calculating the max of WEEK_OF_YEAR 2276 if (gc == this) { 2277 gc = (GregorianCalendar) gc.clone(); 2278 } 2279 gc.setWeekDate(weekYear, 2, internalGet(DAY_OF_WEEK)); 2280 return gc.getActualMaximum(WEEK_OF_YEAR); 2281 } 2282 2283///////////////////////////// 2284// Time => Fields computation 2285///////////////////////////// 2286 2287 /** 2288 * The fixed date corresponding to gdate. If the value is 2289 * Long.MIN_VALUE, the fixed date value is unknown. Currently, 2290 * Julian calendar dates are not cached. 2291 */ 2292 transient private long cachedFixedDate = Long.MIN_VALUE; 2293 2294 /** 2295 * Converts the time value (millisecond offset from the <a 2296 * href="Calendar.html#Epoch">Epoch</a>) to calendar field values. 2297 * The time is <em>not</em> 2298 * recomputed first; to recompute the time, then the fields, call the 2299 * <code>complete</code> method. 2300 * 2301 * @see Calendar#complete 2302 */ 2303 @Override 2304 protected void computeFields() { 2305 int mask; 2306 if (isPartiallyNormalized()) { 2307 // Determine which calendar fields need to be computed. 2308 mask = getSetStateFields(); 2309 int fieldMask = ~mask & ALL_FIELDS; 2310 // We have to call computTime in case calsys == null in 2311 // order to set calsys and cdate. (6263644) 2312 if (fieldMask != 0 || calsys == null) { 2313 mask |= computeFields(fieldMask, 2314 mask & (ZONE_OFFSET_MASK|DST_OFFSET_MASK)); 2315 assert mask == ALL_FIELDS; 2316 } 2317 } else { 2318 mask = ALL_FIELDS; 2319 computeFields(mask, 0); 2320 } 2321 // After computing all the fields, set the field state to `COMPUTED'. 2322 setFieldsComputed(mask); 2323 } 2324 2325 /** 2326 * This computeFields implements the conversion from UTC 2327 * (millisecond offset from the Epoch) to calendar 2328 * field values. fieldMask specifies which fields to change the 2329 * setting state to COMPUTED, although all fields are set to 2330 * the correct values. This is required to fix 4685354. 2331 * 2332 * @param fieldMask a bit mask to specify which fields to change 2333 * the setting state. 2334 * @param tzMask a bit mask to specify which time zone offset 2335 * fields to be used for time calculations 2336 * @return a new field mask that indicates what field values have 2337 * actually been set. 2338 */ 2339 private int computeFields(int fieldMask, int tzMask) { 2340 int zoneOffset = 0; 2341 TimeZone tz = getZone(); 2342 if (zoneOffsets == null) { 2343 zoneOffsets = new int[2]; 2344 } 2345 if (tzMask != (ZONE_OFFSET_MASK|DST_OFFSET_MASK)) { 2346 if (tz instanceof ZoneInfo) { 2347 // Android changed: libcore ZoneInfo uses different method to get offsets. 2348 ZoneInfo zoneInfo = (ZoneInfo) tz; 2349 zoneOffset = zoneInfo.getOffsetsByUtcTime(time, zoneOffsets); 2350 } else { 2351 zoneOffset = tz.getOffset(time); 2352 zoneOffsets[0] = tz.getRawOffset(); 2353 zoneOffsets[1] = zoneOffset - zoneOffsets[0]; 2354 } 2355 } 2356 if (tzMask != 0) { 2357 if (isFieldSet(tzMask, ZONE_OFFSET)) { 2358 zoneOffsets[0] = internalGet(ZONE_OFFSET); 2359 } 2360 if (isFieldSet(tzMask, DST_OFFSET)) { 2361 zoneOffsets[1] = internalGet(DST_OFFSET); 2362 } 2363 zoneOffset = zoneOffsets[0] + zoneOffsets[1]; 2364 } 2365 2366 // By computing time and zoneOffset separately, we can take 2367 // the wider range of time+zoneOffset than the previous 2368 // implementation. 2369 long fixedDate = zoneOffset / ONE_DAY; 2370 int timeOfDay = zoneOffset % (int)ONE_DAY; 2371 fixedDate += time / ONE_DAY; 2372 timeOfDay += (int) (time % ONE_DAY); 2373 if (timeOfDay >= ONE_DAY) { 2374 timeOfDay -= ONE_DAY; 2375 ++fixedDate; 2376 } else { 2377 while (timeOfDay < 0) { 2378 timeOfDay += ONE_DAY; 2379 --fixedDate; 2380 } 2381 } 2382 fixedDate += EPOCH_OFFSET; 2383 2384 int era = CE; 2385 int year; 2386 if (fixedDate >= gregorianCutoverDate) { 2387 // Handle Gregorian dates. 2388 assert cachedFixedDate == Long.MIN_VALUE || gdate.isNormalized() 2389 : "cache control: not normalized"; 2390 assert cachedFixedDate == Long.MIN_VALUE || 2391 gcal.getFixedDate(gdate.getNormalizedYear(), 2392 gdate.getMonth(), 2393 gdate.getDayOfMonth(), gdate) 2394 == cachedFixedDate 2395 : "cache control: inconsictency" + 2396 ", cachedFixedDate=" + cachedFixedDate + 2397 ", computed=" + 2398 gcal.getFixedDate(gdate.getNormalizedYear(), 2399 gdate.getMonth(), 2400 gdate.getDayOfMonth(), 2401 gdate) + 2402 ", date=" + gdate; 2403 2404 // See if we can use gdate to avoid date calculation. 2405 if (fixedDate != cachedFixedDate) { 2406 gcal.getCalendarDateFromFixedDate(gdate, fixedDate); 2407 cachedFixedDate = fixedDate; 2408 } 2409 2410 year = gdate.getYear(); 2411 if (year <= 0) { 2412 year = 1 - year; 2413 era = BCE; 2414 } 2415 calsys = gcal; 2416 cdate = gdate; 2417 assert cdate.getDayOfWeek() > 0 : "dow="+cdate.getDayOfWeek()+", date="+cdate; 2418 } else { 2419 // Handle Julian calendar dates. 2420 calsys = getJulianCalendarSystem(); 2421 cdate = (BaseCalendar.Date) jcal.newCalendarDate(getZone()); 2422 jcal.getCalendarDateFromFixedDate(cdate, fixedDate); 2423 Era e = cdate.getEra(); 2424 if (e == jeras[0]) { 2425 era = BCE; 2426 } 2427 year = cdate.getYear(); 2428 } 2429 2430 // Always set the ERA and YEAR values. 2431 internalSet(ERA, era); 2432 internalSet(YEAR, year); 2433 int mask = fieldMask | (ERA_MASK|YEAR_MASK); 2434 2435 int month = cdate.getMonth() - 1; // 0-based 2436 int dayOfMonth = cdate.getDayOfMonth(); 2437 2438 // Set the basic date fields. 2439 if ((fieldMask & (MONTH_MASK|DAY_OF_MONTH_MASK|DAY_OF_WEEK_MASK)) 2440 != 0) { 2441 internalSet(MONTH, month); 2442 internalSet(DAY_OF_MONTH, dayOfMonth); 2443 internalSet(DAY_OF_WEEK, cdate.getDayOfWeek()); 2444 mask |= MONTH_MASK|DAY_OF_MONTH_MASK|DAY_OF_WEEK_MASK; 2445 } 2446 2447 if ((fieldMask & (HOUR_OF_DAY_MASK|AM_PM_MASK|HOUR_MASK 2448 |MINUTE_MASK|SECOND_MASK|MILLISECOND_MASK)) != 0) { 2449 if (timeOfDay != 0) { 2450 int hours = timeOfDay / ONE_HOUR; 2451 internalSet(HOUR_OF_DAY, hours); 2452 internalSet(AM_PM, hours / 12); // Assume AM == 0 2453 internalSet(HOUR, hours % 12); 2454 int r = timeOfDay % ONE_HOUR; 2455 internalSet(MINUTE, r / ONE_MINUTE); 2456 r %= ONE_MINUTE; 2457 internalSet(SECOND, r / ONE_SECOND); 2458 internalSet(MILLISECOND, r % ONE_SECOND); 2459 } else { 2460 internalSet(HOUR_OF_DAY, 0); 2461 internalSet(AM_PM, AM); 2462 internalSet(HOUR, 0); 2463 internalSet(MINUTE, 0); 2464 internalSet(SECOND, 0); 2465 internalSet(MILLISECOND, 0); 2466 } 2467 mask |= (HOUR_OF_DAY_MASK|AM_PM_MASK|HOUR_MASK 2468 |MINUTE_MASK|SECOND_MASK|MILLISECOND_MASK); 2469 } 2470 2471 if ((fieldMask & (ZONE_OFFSET_MASK|DST_OFFSET_MASK)) != 0) { 2472 internalSet(ZONE_OFFSET, zoneOffsets[0]); 2473 internalSet(DST_OFFSET, zoneOffsets[1]); 2474 mask |= (ZONE_OFFSET_MASK|DST_OFFSET_MASK); 2475 } 2476 2477 if ((fieldMask & (DAY_OF_YEAR_MASK|WEEK_OF_YEAR_MASK|WEEK_OF_MONTH_MASK|DAY_OF_WEEK_IN_MONTH_MASK)) != 0) { 2478 int normalizedYear = cdate.getNormalizedYear(); 2479 long fixedDateJan1 = calsys.getFixedDate(normalizedYear, 1, 1, cdate); 2480 int dayOfYear = (int)(fixedDate - fixedDateJan1) + 1; 2481 long fixedDateMonth1 = fixedDate - dayOfMonth + 1; 2482 int cutoverGap = 0; 2483 int cutoverYear = (calsys == gcal) ? gregorianCutoverYear : gregorianCutoverYearJulian; 2484 int relativeDayOfMonth = dayOfMonth - 1; 2485 2486 // If we are in the cutover year, we need some special handling. 2487 if (normalizedYear == cutoverYear) { 2488 // Need to take care of the "missing" days. 2489 if (gregorianCutoverYearJulian <= gregorianCutoverYear) { 2490 // We need to find out where we are. The cutover 2491 // gap could even be more than one year. (One 2492 // year difference in ~48667 years.) 2493 fixedDateJan1 = getFixedDateJan1(cdate, fixedDate); 2494 if (fixedDate >= gregorianCutoverDate) { 2495 fixedDateMonth1 = getFixedDateMonth1(cdate, fixedDate); 2496 } 2497 } 2498 int realDayOfYear = (int)(fixedDate - fixedDateJan1) + 1; 2499 cutoverGap = dayOfYear - realDayOfYear; 2500 dayOfYear = realDayOfYear; 2501 relativeDayOfMonth = (int)(fixedDate - fixedDateMonth1); 2502 } 2503 internalSet(DAY_OF_YEAR, dayOfYear); 2504 internalSet(DAY_OF_WEEK_IN_MONTH, relativeDayOfMonth / 7 + 1); 2505 2506 int weekOfYear = getWeekNumber(fixedDateJan1, fixedDate); 2507 2508 // The spec is to calculate WEEK_OF_YEAR in the 2509 // ISO8601-style. This creates problems, though. 2510 if (weekOfYear == 0) { 2511 // If the date belongs to the last week of the 2512 // previous year, use the week number of "12/31" of 2513 // the "previous" year. Again, if the previous year is 2514 // the Gregorian cutover year, we need to take care of 2515 // it. Usually the previous day of January 1 is 2516 // December 31, which is not always true in 2517 // GregorianCalendar. 2518 long fixedDec31 = fixedDateJan1 - 1; 2519 long prevJan1 = fixedDateJan1 - 365; 2520 if (normalizedYear > (cutoverYear + 1)) { 2521 if (CalendarUtils.isGregorianLeapYear(normalizedYear - 1)) { 2522 --prevJan1; 2523 } 2524 } else if (normalizedYear <= gregorianCutoverYearJulian) { 2525 if (CalendarUtils.isJulianLeapYear(normalizedYear - 1)) { 2526 --prevJan1; 2527 } 2528 } else { 2529 BaseCalendar calForJan1 = calsys; 2530 //int prevYear = normalizedYear - 1; 2531 int prevYear = getCalendarDate(fixedDec31).getNormalizedYear(); 2532 if (prevYear == gregorianCutoverYear) { 2533 calForJan1 = getCutoverCalendarSystem(); 2534 if (calForJan1 == jcal) { 2535 prevJan1 = calForJan1.getFixedDate(prevYear, 2536 BaseCalendar.JANUARY, 2537 1, 2538 null); 2539 } else { 2540 prevJan1 = gregorianCutoverDate; 2541 calForJan1 = gcal; 2542 } 2543 } else if (prevYear <= gregorianCutoverYearJulian) { 2544 calForJan1 = getJulianCalendarSystem(); 2545 prevJan1 = calForJan1.getFixedDate(prevYear, 2546 BaseCalendar.JANUARY, 2547 1, 2548 null); 2549 } 2550 } 2551 weekOfYear = getWeekNumber(prevJan1, fixedDec31); 2552 } else { 2553 if (normalizedYear > gregorianCutoverYear || 2554 normalizedYear < (gregorianCutoverYearJulian - 1)) { 2555 // Regular years 2556 if (weekOfYear >= 52) { 2557 long nextJan1 = fixedDateJan1 + 365; 2558 if (cdate.isLeapYear()) { 2559 nextJan1++; 2560 } 2561 long nextJan1st = BaseCalendar.getDayOfWeekDateOnOrBefore(nextJan1 + 6, 2562 getFirstDayOfWeek()); 2563 int ndays = (int)(nextJan1st - nextJan1); 2564 if (ndays >= getMinimalDaysInFirstWeek() && fixedDate >= (nextJan1st - 7)) { 2565 // The first days forms a week in which the date is included. 2566 weekOfYear = 1; 2567 } 2568 } 2569 } else { 2570 BaseCalendar calForJan1 = calsys; 2571 int nextYear = normalizedYear + 1; 2572 if (nextYear == (gregorianCutoverYearJulian + 1) && 2573 nextYear < gregorianCutoverYear) { 2574 // In case the gap is more than one year. 2575 nextYear = gregorianCutoverYear; 2576 } 2577 if (nextYear == gregorianCutoverYear) { 2578 calForJan1 = getCutoverCalendarSystem(); 2579 } 2580 2581 long nextJan1; 2582 if (nextYear > gregorianCutoverYear 2583 || gregorianCutoverYearJulian == gregorianCutoverYear 2584 || nextYear == gregorianCutoverYearJulian) { 2585 nextJan1 = calForJan1.getFixedDate(nextYear, 2586 BaseCalendar.JANUARY, 2587 1, 2588 null); 2589 } else { 2590 nextJan1 = gregorianCutoverDate; 2591 calForJan1 = gcal; 2592 } 2593 2594 long nextJan1st = BaseCalendar.getDayOfWeekDateOnOrBefore(nextJan1 + 6, 2595 getFirstDayOfWeek()); 2596 int ndays = (int)(nextJan1st - nextJan1); 2597 if (ndays >= getMinimalDaysInFirstWeek() && fixedDate >= (nextJan1st - 7)) { 2598 // The first days forms a week in which the date is included. 2599 weekOfYear = 1; 2600 } 2601 } 2602 } 2603 internalSet(WEEK_OF_YEAR, weekOfYear); 2604 internalSet(WEEK_OF_MONTH, getWeekNumber(fixedDateMonth1, fixedDate)); 2605 mask |= (DAY_OF_YEAR_MASK|WEEK_OF_YEAR_MASK|WEEK_OF_MONTH_MASK|DAY_OF_WEEK_IN_MONTH_MASK); 2606 } 2607 return mask; 2608 } 2609 2610 /** 2611 * Returns the number of weeks in a period between fixedDay1 and 2612 * fixedDate. The getFirstDayOfWeek-getMinimalDaysInFirstWeek rule 2613 * is applied to calculate the number of weeks. 2614 * 2615 * @param fixedDay1 the fixed date of the first day of the period 2616 * @param fixedDate the fixed date of the last day of the period 2617 * @return the number of weeks of the given period 2618 */ 2619 private int getWeekNumber(long fixedDay1, long fixedDate) { 2620 // We can always use `gcal' since Julian and Gregorian are the 2621 // same thing for this calculation. 2622 long fixedDay1st = Gregorian.getDayOfWeekDateOnOrBefore(fixedDay1 + 6, 2623 getFirstDayOfWeek()); 2624 int ndays = (int)(fixedDay1st - fixedDay1); 2625 assert ndays <= 7; 2626 if (ndays >= getMinimalDaysInFirstWeek()) { 2627 fixedDay1st -= 7; 2628 } 2629 int normalizedDayOfPeriod = (int)(fixedDate - fixedDay1st); 2630 if (normalizedDayOfPeriod >= 0) { 2631 return normalizedDayOfPeriod / 7 + 1; 2632 } 2633 return CalendarUtils.floorDivide(normalizedDayOfPeriod, 7) + 1; 2634 } 2635 2636 /** 2637 * Converts calendar field values to the time value (millisecond 2638 * offset from the <a href="Calendar.html#Epoch">Epoch</a>). 2639 * 2640 * @exception IllegalArgumentException if any calendar fields are invalid. 2641 */ 2642 @Override 2643 protected void computeTime() { 2644 // In non-lenient mode, perform brief checking of calendar 2645 // fields which have been set externally. Through this 2646 // checking, the field values are stored in originalFields[] 2647 // to see if any of them are normalized later. 2648 if (!isLenient()) { 2649 if (originalFields == null) { 2650 originalFields = new int[FIELD_COUNT]; 2651 } 2652 for (int field = 0; field < FIELD_COUNT; field++) { 2653 int value = internalGet(field); 2654 if (isExternallySet(field)) { 2655 // Quick validation for any out of range values 2656 if (value < getMinimum(field) || value > getMaximum(field)) { 2657 throw new IllegalArgumentException(getFieldName(field)); 2658 } 2659 } 2660 originalFields[field] = value; 2661 } 2662 } 2663 2664 // Let the super class determine which calendar fields to be 2665 // used to calculate the time. 2666 int fieldMask = selectFields(); 2667 2668 // The year defaults to the epoch start. We don't check 2669 // fieldMask for YEAR because YEAR is a mandatory field to 2670 // determine the date. 2671 int year = isSet(YEAR) ? internalGet(YEAR) : EPOCH_YEAR; 2672 2673 int era = internalGetEra(); 2674 if (era == BCE) { 2675 year = 1 - year; 2676 } else if (era != CE) { 2677 // Even in lenient mode we disallow ERA values other than CE & BCE. 2678 // (The same normalization rule as add()/roll() could be 2679 // applied here in lenient mode. But this checking is kept 2680 // unchanged for compatibility as of 1.5.) 2681 throw new IllegalArgumentException("Invalid era"); 2682 } 2683 2684 // If year is 0 or negative, we need to set the ERA value later. 2685 if (year <= 0 && !isSet(ERA)) { 2686 fieldMask |= ERA_MASK; 2687 setFieldsComputed(ERA_MASK); 2688 } 2689 2690 // Calculate the time of day. We rely on the convention that 2691 // an UNSET field has 0. 2692 long timeOfDay = 0; 2693 if (isFieldSet(fieldMask, HOUR_OF_DAY)) { 2694 timeOfDay += (long) internalGet(HOUR_OF_DAY); 2695 } else { 2696 timeOfDay += internalGet(HOUR); 2697 // The default value of AM_PM is 0 which designates AM. 2698 if (isFieldSet(fieldMask, AM_PM)) { 2699 timeOfDay += 12 * internalGet(AM_PM); 2700 } 2701 } 2702 timeOfDay *= 60; 2703 timeOfDay += internalGet(MINUTE); 2704 timeOfDay *= 60; 2705 timeOfDay += internalGet(SECOND); 2706 timeOfDay *= 1000; 2707 timeOfDay += internalGet(MILLISECOND); 2708 2709 // Convert the time of day to the number of days and the 2710 // millisecond offset from midnight. 2711 long fixedDate = timeOfDay / ONE_DAY; 2712 timeOfDay %= ONE_DAY; 2713 while (timeOfDay < 0) { 2714 timeOfDay += ONE_DAY; 2715 --fixedDate; 2716 } 2717 2718 // Calculate the fixed date since January 1, 1 (Gregorian). 2719 calculateFixedDate: { 2720 long gfd, jfd; 2721 if (year > gregorianCutoverYear && year > gregorianCutoverYearJulian) { 2722 gfd = fixedDate + getFixedDate(gcal, year, fieldMask); 2723 if (gfd >= gregorianCutoverDate) { 2724 fixedDate = gfd; 2725 break calculateFixedDate; 2726 } 2727 jfd = fixedDate + getFixedDate(getJulianCalendarSystem(), year, fieldMask); 2728 } else if (year < gregorianCutoverYear && year < gregorianCutoverYearJulian) { 2729 jfd = fixedDate + getFixedDate(getJulianCalendarSystem(), year, fieldMask); 2730 if (jfd < gregorianCutoverDate) { 2731 fixedDate = jfd; 2732 break calculateFixedDate; 2733 } 2734 gfd = jfd; 2735 } else { 2736 jfd = fixedDate + getFixedDate(getJulianCalendarSystem(), year, fieldMask); 2737 gfd = fixedDate + getFixedDate(gcal, year, fieldMask); 2738 } 2739 2740 // Now we have to determine which calendar date it is. 2741 2742 // If the date is relative from the beginning of the year 2743 // in the Julian calendar, then use jfd; 2744 if (isFieldSet(fieldMask, DAY_OF_YEAR) || isFieldSet(fieldMask, WEEK_OF_YEAR)) { 2745 if (gregorianCutoverYear == gregorianCutoverYearJulian) { 2746 fixedDate = jfd; 2747 break calculateFixedDate; 2748 } else if (year == gregorianCutoverYear) { 2749 fixedDate = gfd; 2750 break calculateFixedDate; 2751 } 2752 } 2753 2754 if (gfd >= gregorianCutoverDate) { 2755 if (jfd >= gregorianCutoverDate) { 2756 fixedDate = gfd; 2757 } else { 2758 // The date is in an "overlapping" period. No way 2759 // to disambiguate it. Determine it using the 2760 // previous date calculation. 2761 if (calsys == gcal || calsys == null) { 2762 fixedDate = gfd; 2763 } else { 2764 fixedDate = jfd; 2765 } 2766 } 2767 } else { 2768 if (jfd < gregorianCutoverDate) { 2769 fixedDate = jfd; 2770 } else { 2771 // The date is in a "missing" period. 2772 if (!isLenient()) { 2773 throw new IllegalArgumentException("the specified date doesn't exist"); 2774 } 2775 // Take the Julian date for compatibility, which 2776 // will produce a Gregorian date. 2777 fixedDate = jfd; 2778 } 2779 } 2780 } 2781 2782 // millis represents local wall-clock time in milliseconds. 2783 long millis = (fixedDate - EPOCH_OFFSET) * ONE_DAY + timeOfDay; 2784 2785 // Compute the time zone offset and DST offset. There are two potential 2786 // ambiguities here. We'll assume a 2:00 am (wall time) switchover time 2787 // for discussion purposes here. 2788 // 1. The transition into DST. Here, a designated time of 2:00 am - 2:59 am 2789 // can be in standard or in DST depending. However, 2:00 am is an invalid 2790 // representation (the representation jumps from 1:59:59 am Std to 3:00:00 am DST). 2791 // We assume standard time. 2792 // 2. The transition out of DST. Here, a designated time of 1:00 am - 1:59 am 2793 // can be in standard or DST. Both are valid representations (the rep 2794 // jumps from 1:59:59 DST to 1:00:00 Std). 2795 // Again, we assume standard time. 2796 // We use the TimeZone object, unless the user has explicitly set the ZONE_OFFSET 2797 // or DST_OFFSET fields; then we use those fields. 2798 TimeZone zone = getZone(); 2799 // Android changed: move time zone related calculation to separate method. 2800 2801 int tzMask = fieldMask & (ZONE_OFFSET_MASK|DST_OFFSET_MASK); 2802 2803 millis = adjustForZoneAndDaylightSavingsTime(tzMask, millis, zone); 2804 2805 // Set this calendar's time in milliseconds 2806 time = millis; 2807 2808 int mask = computeFields(fieldMask | getSetStateFields(), tzMask); 2809 2810 if (!isLenient()) { 2811 for (int field = 0; field < FIELD_COUNT; field++) { 2812 if (!isExternallySet(field)) { 2813 continue; 2814 } 2815 if (originalFields[field] != internalGet(field)) { 2816 String s = originalFields[field] + " -> " + internalGet(field); 2817 // Restore the original field values 2818 System.arraycopy(originalFields, 0, fields, 0, fields.length); 2819 throw new IllegalArgumentException(getFieldName(field) + ": " + s); 2820 } 2821 } 2822 } 2823 setFieldsNormalized(mask); 2824 } 2825 2826 /** 2827 * Calculates the time in milliseconds that this calendar represents using the UTC time, 2828 * timezone information (specifically Daylight Savings Time (DST) rules, if any) and knowledge 2829 * of what fields were explicitly set on the calendar. 2830 * 2831 * <p>A time is represented as the number of milliseconds since 2832 * <i>1st January 1970 00:00:00.000 UTC</i>. 2833 * 2834 * <p>This uses the terms {@link SimpleTimeZone#STANDARD_TIME standard time}, 2835 * {@link SimpleTimeZone#WALL_TIME} wall time} and {@link SimpleTimeZone#UTC_TIME UTC time} as 2836 * used in {@link SimpleTimeZone}. Specifically: 2837 * 2838 * <dl> 2839 * <dt><b>UTC time</b></dt> 2840 * <dd>This is the time within the UTC time zone. UTC does not support DST so the UTC time, 2841 * standard time and wall time are all identical within the UTC time zone.</dd> 2842 * <dt><b>standard time</b></dt> 2843 * <dd>This is the local time within the time zone and is not affected by DST.</dd> 2844 * <dt><b>wall time</b></dt> 2845 * <dd>This is the local time within the time zone as shown on a wall clock. If the time zone 2846 * supports DST then it will be the same as <b>standard time</b> when outside DST and it will 2847 * differ (usually be an hour later) when inside DST. This is what the fields on the Calendar 2848 * represent.</dd> 2849 * </dl> 2850 * 2851 * <p>The {@code utcTimeInMillis} value supplied was calculated as if the fields represented 2852 * a standard time in the {@code UTC} time zone. It is the value that would be returned by 2853 * {@link #getTimeInMillis()} when called on this calendar if it was in UTC time zone. e.g. If 2854 * the calendar was set to say <i>2014 March 19th 13:27.53 -08:00</i> then the value of 2855 * {@code utcTimeInMillis} would be the value of {@link #getTimeInMillis()} when called on a 2856 * calendar set to <i>2014 March 19th 13:27.53 -00:00</i>, note the time zone offset is set to 2857 * 0. 2858 * 2859 * <p>To adjust from a UTC time in millis to the standard time in millis we must 2860 * <em>subtract</em> the offset from UTC. e.g. given an offset of UTC-08:00, to convert 2861 * "14:00 UTC" to "14:00 UTC-08:00" we must subtract -08:00 (i.e. add 8 hours). Another way to 2862 * think about it is that 8 hours has to elapse after 14:00 UTC before it is 14:00 UTC-08:00. 2863 * 2864 * <p>As the zone offset can depend on the time and we cannot calculate the time properly until 2865 * we know the time there is a bit of a catch-22. So, what this does is use the 2866 * {@link TimeZone#getRawOffset() raw offset} to calculate a ballpark standard time and then 2867 * uses that value to retrieve the appropriate zone and DST offsets from the time zone. They 2868 * are then used to make the final wall time calculation. 2869 * 2870 * <p>The DST offset will need clearing if the standard time is not a valid wall clock. See 2871 * {@link #adjustDstOffsetForInvalidWallClock(long, TimeZone, int)} for more information. 2872 * 2873 * @param tzMask the set of time zone related fields, i.e. {@link #ZONE_OFFSET_MASK} and 2874 * {@link #DST_OFFSET_MASK} 2875 * @param utcTimeInMillis the time in millis, calculated assuming the time zone was GMT. 2876 * @param zone the actual time zone. 2877 * @return the UTC time in millis after adjusting for zone and DST offset. 2878 */ 2879 private long adjustForZoneAndDaylightSavingsTime( 2880 int tzMask, long utcTimeInMillis, TimeZone zone) { 2881 2882 // The following don't actually need to be initialized because they are always set before 2883 // they are used but the compiler cannot detect that. 2884 int zoneOffset = 0; 2885 int dstOffset = 0; 2886 2887 // If either of the ZONE_OFFSET or DST_OFFSET fields are not set then get the information 2888 // from the TimeZone. 2889 if (tzMask != (ZONE_OFFSET_MASK|DST_OFFSET_MASK)) { 2890 if (zoneOffsets == null) { 2891 zoneOffsets = new int[2]; 2892 } 2893 int gmtOffset = isFieldSet(tzMask, ZONE_OFFSET) ? 2894 internalGet(ZONE_OFFSET) : zone.getRawOffset(); 2895 2896 // Calculate the standard time (no DST) in the supplied zone. This is a ballpark figure 2897 // and not used in the final calculation as the offset used here may not be the same as 2898 // the actual offset the time zone requires be used for this time. This is to handle 2899 // situations like Honolulu, where its raw offset changed from GMT-10:30 to GMT-10:00 2900 // in 1947. The TimeZone always uses a raw offset of -10:00 but will return -10:30 2901 // for dates before the change over. 2902 long standardTimeInZone = utcTimeInMillis - gmtOffset; 2903 2904 // Retrieve the correct zone and DST offsets from the time zone. 2905 if (zone instanceof ZoneInfo) { 2906 // Android changed: libcore ZoneInfo uses different method to get offsets. 2907 ZoneInfo zoneInfo = (ZoneInfo) zone; 2908 zoneInfo.getOffsetsByUtcTime(standardTimeInZone, zoneOffsets); 2909 } else { 2910 zone.getOffsets(standardTimeInZone, zoneOffsets); 2911 } 2912 zoneOffset = zoneOffsets[0]; 2913 dstOffset = zoneOffsets[1]; 2914 2915 // If necessary adjust the DST offset to handle an invalid wall clock sensibly. 2916 dstOffset = adjustDstOffsetForInvalidWallClock(standardTimeInZone, zone, dstOffset); 2917 } 2918 2919 // If either ZONE_OFFSET of DST_OFFSET fields are set then get the information from the 2920 // fields, potentially overriding information from the TimeZone. 2921 if (tzMask != 0) { 2922 if (isFieldSet(tzMask, ZONE_OFFSET)) { 2923 zoneOffset = internalGet(ZONE_OFFSET); 2924 } 2925 if (isFieldSet(tzMask, DST_OFFSET)) { 2926 dstOffset = internalGet(DST_OFFSET); 2927 } 2928 } 2929 2930 // Adjust the time zone offset values to get the UTC time. 2931 long standardTimeInZone = utcTimeInMillis - zoneOffset; 2932 return standardTimeInZone - dstOffset; 2933 } 2934 2935 /** 2936 * If the supplied millis is in daylight savings time (DST) and is the result of an invalid 2937 * wall clock then adjust the DST offset to ensure sensible behavior. 2938 * 2939 * <p>When transitioning into DST, i.e. when the clocks spring forward (usually by one hour) 2940 * there is a wall clock period that is invalid, it literally doesn't exist. e.g. If clocks 2941 * go forward one hour at 02:00 on 9th March 2014 (standard time) then the wall time of 2942 * 02:00-02:59:59.999 is not a valid. The wall clock jumps straight from 01:59:59.999 to 2943 * 03:00. The following table shows the relationship between the time in millis, the standard 2944 * time and the wall time at the point of transitioning into DST. As can be seen there is no 2945 * 02:00 in the wall time. 2946 * 2947 * <pre> 2948 * Time In Millis - ...... x+1h ..... x+2h ..... x+3h 2949 * Standard Time - ...... 01:00 ..... 02:00 ..... 03:00 ..... 2950 * Wall Time - ...... 01:00 ..... 03:00 ..... 04:00 ..... 2951 * ^ 2952 * 02:00 missing 2953 * </pre> 2954 * 2955 * <p>The calendar fields represent wall time. If the user sets the fields on the calendar so 2956 * that it is in that invalid period then this code attempts to do something sensible. It 2957 * treats 02:MM:SS.SSS as if it is {@code 01:MM:SS.SSS + 1 hour}. That makes sense from both 2958 * the input calendar fields perspective and from the time in millis perspective. Of course the 2959 * result of that is that when the time is formatted in that time zone that the time is 2960 * actually 03:MM:SS.SSS. 2961 * 2962 * <pre> 2963 * Wall Time - ...... 01:00 ..... <b>02:00 .....</b> 03:00 ..... 04:00 ..... 2964 * Time In Millis - ...... x+1h ..... <b> x+2h .....</b> x+2h ..... x+3h ..... 2965 * </pre> 2966 * 2967 * <p>The way that works is as follows. First the standard time is calculated and the DST 2968 * offset is determined. Then if the time is in DST (the DST offset is not 0) but it was not in 2969 * DST an hour earlier (or however long the DST offset is) then it must be in that invalid 2970 * period, in which case set the DST offset to 0. That is then subtracted from the time in 2971 * millis to produce the correct result. The following diagram illustrates the process. 2972 * 2973 * <pre> 2974 * Standard Time - ...... 01:00 ..... 02:00 ..... 03:00 ..... 04:00 ..... 2975 * Time In Millis - ...... x+1h ..... x+2h ..... x+3h ..... x+4h ..... 2976 * DST Offset - ...... 0h ..... 1h ..... 1h ..... 1h ..... 2977 * Adjusted DST - ...... 0h ..... <b>0h</b> ..... 1h ..... 1h ..... 2978 * Adjusted Time - ...... x+1h ..... x+2h ..... <b>x+2h</b> ..... <b>x+3h</b> ..... 2979 * </pre> 2980 * 2981 * @return the adjusted DST offset. 2982 */ 2983 private int adjustDstOffsetForInvalidWallClock( 2984 long standardTimeInZone, TimeZone zone, int dstOffset) { 2985 2986 if (dstOffset != 0) { 2987 // If applying the DST offset produces a time that is outside DST then it must be 2988 // an invalid wall clock so clear the DST offset to avoid that happening. 2989 if (!zone.inDaylightTime(new Date(standardTimeInZone - dstOffset))) { 2990 dstOffset = 0; 2991 } 2992 } 2993 return dstOffset; 2994 } 2995 2996 /** 2997 * Computes the fixed date under either the Gregorian or the 2998 * Julian calendar, using the given year and the specified calendar fields. 2999 * 3000 * @param cal the CalendarSystem to be used for the date calculation 3001 * @param year the normalized year number, with 0 indicating the 3002 * year 1 BCE, -1 indicating 2 BCE, etc. 3003 * @param fieldMask the calendar fields to be used for the date calculation 3004 * @return the fixed date 3005 * @see Calendar#selectFields 3006 */ 3007 private long getFixedDate(BaseCalendar cal, int year, int fieldMask) { 3008 int month = JANUARY; 3009 if (isFieldSet(fieldMask, MONTH)) { 3010 // No need to check if MONTH has been set (no isSet(MONTH) 3011 // call) since its unset value happens to be JANUARY (0). 3012 month = internalGet(MONTH); 3013 3014 // If the month is out of range, adjust it into range 3015 if (month > DECEMBER) { 3016 year += month / 12; 3017 month %= 12; 3018 } else if (month < JANUARY) { 3019 int[] rem = new int[1]; 3020 year += CalendarUtils.floorDivide(month, 12, rem); 3021 month = rem[0]; 3022 } 3023 } 3024 3025 // Get the fixed date since Jan 1, 1 (Gregorian). We are on 3026 // the first day of either `month' or January in 'year'. 3027 long fixedDate = cal.getFixedDate(year, month + 1, 1, 3028 cal == gcal ? gdate : null); 3029 if (isFieldSet(fieldMask, MONTH)) { 3030 // Month-based calculations 3031 if (isFieldSet(fieldMask, DAY_OF_MONTH)) { 3032 // We are on the first day of the month. Just add the 3033 // offset if DAY_OF_MONTH is set. If the isSet call 3034 // returns false, that means DAY_OF_MONTH has been 3035 // selected just because of the selected 3036 // combination. We don't need to add any since the 3037 // default value is the 1st. 3038 if (isSet(DAY_OF_MONTH)) { 3039 // To avoid underflow with DAY_OF_MONTH-1, add 3040 // DAY_OF_MONTH, then subtract 1. 3041 fixedDate += internalGet(DAY_OF_MONTH); 3042 fixedDate--; 3043 } 3044 } else { 3045 if (isFieldSet(fieldMask, WEEK_OF_MONTH)) { 3046 long firstDayOfWeek = BaseCalendar.getDayOfWeekDateOnOrBefore(fixedDate + 6, 3047 getFirstDayOfWeek()); 3048 // If we have enough days in the first week, then 3049 // move to the previous week. 3050 if ((firstDayOfWeek - fixedDate) >= getMinimalDaysInFirstWeek()) { 3051 firstDayOfWeek -= 7; 3052 } 3053 if (isFieldSet(fieldMask, DAY_OF_WEEK)) { 3054 firstDayOfWeek = BaseCalendar.getDayOfWeekDateOnOrBefore(firstDayOfWeek + 6, 3055 internalGet(DAY_OF_WEEK)); 3056 } 3057 // In lenient mode, we treat days of the previous 3058 // months as a part of the specified 3059 // WEEK_OF_MONTH. See 4633646. 3060 fixedDate = firstDayOfWeek + 7 * (internalGet(WEEK_OF_MONTH) - 1); 3061 } else { 3062 int dayOfWeek; 3063 if (isFieldSet(fieldMask, DAY_OF_WEEK)) { 3064 dayOfWeek = internalGet(DAY_OF_WEEK); 3065 } else { 3066 dayOfWeek = getFirstDayOfWeek(); 3067 } 3068 // We are basing this on the day-of-week-in-month. The only 3069 // trickiness occurs if the day-of-week-in-month is 3070 // negative. 3071 int dowim; 3072 if (isFieldSet(fieldMask, DAY_OF_WEEK_IN_MONTH)) { 3073 dowim = internalGet(DAY_OF_WEEK_IN_MONTH); 3074 } else { 3075 dowim = 1; 3076 } 3077 if (dowim >= 0) { 3078 fixedDate = BaseCalendar.getDayOfWeekDateOnOrBefore(fixedDate + (7 * dowim) - 1, 3079 dayOfWeek); 3080 } else { 3081 // Go to the first day of the next week of 3082 // the specified week boundary. 3083 int lastDate = monthLength(month, year) + (7 * (dowim + 1)); 3084 // Then, get the day of week date on or before the last date. 3085 fixedDate = BaseCalendar.getDayOfWeekDateOnOrBefore(fixedDate + lastDate - 1, 3086 dayOfWeek); 3087 } 3088 } 3089 } 3090 } else { 3091 if (year == gregorianCutoverYear && cal == gcal 3092 && fixedDate < gregorianCutoverDate 3093 && gregorianCutoverYear != gregorianCutoverYearJulian) { 3094 // January 1 of the year doesn't exist. Use 3095 // gregorianCutoverDate as the first day of the 3096 // year. 3097 fixedDate = gregorianCutoverDate; 3098 } 3099 // We are on the first day of the year. 3100 if (isFieldSet(fieldMask, DAY_OF_YEAR)) { 3101 // Add the offset, then subtract 1. (Make sure to avoid underflow.) 3102 fixedDate += internalGet(DAY_OF_YEAR); 3103 fixedDate--; 3104 } else { 3105 long firstDayOfWeek = BaseCalendar.getDayOfWeekDateOnOrBefore(fixedDate + 6, 3106 getFirstDayOfWeek()); 3107 // If we have enough days in the first week, then move 3108 // to the previous week. 3109 if ((firstDayOfWeek - fixedDate) >= getMinimalDaysInFirstWeek()) { 3110 firstDayOfWeek -= 7; 3111 } 3112 if (isFieldSet(fieldMask, DAY_OF_WEEK)) { 3113 int dayOfWeek = internalGet(DAY_OF_WEEK); 3114 if (dayOfWeek != getFirstDayOfWeek()) { 3115 firstDayOfWeek = BaseCalendar.getDayOfWeekDateOnOrBefore(firstDayOfWeek + 6, 3116 dayOfWeek); 3117 } 3118 } 3119 fixedDate = firstDayOfWeek + 7 * ((long)internalGet(WEEK_OF_YEAR) - 1); 3120 } 3121 } 3122 3123 return fixedDate; 3124 } 3125 3126 /** 3127 * Returns this object if it's normalized (all fields and time are 3128 * in sync). Otherwise, a cloned object is returned after calling 3129 * complete() in lenient mode. 3130 */ 3131 private GregorianCalendar getNormalizedCalendar() { 3132 GregorianCalendar gc; 3133 if (isFullyNormalized()) { 3134 gc = this; 3135 } else { 3136 // Create a clone and normalize the calendar fields 3137 gc = (GregorianCalendar) this.clone(); 3138 gc.setLenient(true); 3139 gc.complete(); 3140 } 3141 return gc; 3142 } 3143 3144 /** 3145 * Returns the Julian calendar system instance (singleton). 'jcal' 3146 * and 'jeras' are set upon the return. 3147 */ 3148 private static synchronized BaseCalendar getJulianCalendarSystem() { 3149 if (jcal == null) { 3150 jcal = (JulianCalendar) CalendarSystem.forName("julian"); 3151 jeras = jcal.getEras(); 3152 } 3153 return jcal; 3154 } 3155 3156 /** 3157 * Returns the calendar system for dates before the cutover date 3158 * in the cutover year. If the cutover date is January 1, the 3159 * method returns Gregorian. Otherwise, Julian. 3160 */ 3161 private BaseCalendar getCutoverCalendarSystem() { 3162 if (gregorianCutoverYearJulian < gregorianCutoverYear) { 3163 return gcal; 3164 } 3165 return getJulianCalendarSystem(); 3166 } 3167 3168 /** 3169 * Determines if the specified year (normalized) is the Gregorian 3170 * cutover year. This object must have been normalized. 3171 */ 3172 private boolean isCutoverYear(int normalizedYear) { 3173 int cutoverYear = (calsys == gcal) ? gregorianCutoverYear : gregorianCutoverYearJulian; 3174 return normalizedYear == cutoverYear; 3175 } 3176 3177 /** 3178 * Returns the fixed date of the first day of the year (usually 3179 * January 1) before the specified date. 3180 * 3181 * @param date the date for which the first day of the year is 3182 * calculated. The date has to be in the cut-over year (Gregorian 3183 * or Julian). 3184 * @param fixedDate the fixed date representation of the date 3185 */ 3186 private long getFixedDateJan1(BaseCalendar.Date date, long fixedDate) { 3187 assert date.getNormalizedYear() == gregorianCutoverYear || 3188 date.getNormalizedYear() == gregorianCutoverYearJulian; 3189 if (gregorianCutoverYear != gregorianCutoverYearJulian) { 3190 if (fixedDate >= gregorianCutoverDate) { 3191 // Dates before the cutover date don't exist 3192 // in the same (Gregorian) year. So, no 3193 // January 1 exists in the year. Use the 3194 // cutover date as the first day of the year. 3195 return gregorianCutoverDate; 3196 } 3197 } 3198 // January 1 of the normalized year should exist. 3199 BaseCalendar juliancal = getJulianCalendarSystem(); 3200 return juliancal.getFixedDate(date.getNormalizedYear(), BaseCalendar.JANUARY, 1, null); 3201 } 3202 3203 /** 3204 * Returns the fixed date of the first date of the month (usually 3205 * the 1st of the month) before the specified date. 3206 * 3207 * @param date the date for which the first day of the month is 3208 * calculated. The date has to be in the cut-over year (Gregorian 3209 * or Julian). 3210 * @param fixedDate the fixed date representation of the date 3211 */ 3212 private long getFixedDateMonth1(BaseCalendar.Date date, long fixedDate) { 3213 assert date.getNormalizedYear() == gregorianCutoverYear || 3214 date.getNormalizedYear() == gregorianCutoverYearJulian; 3215 BaseCalendar.Date gCutover = getGregorianCutoverDate(); 3216 if (gCutover.getMonth() == BaseCalendar.JANUARY 3217 && gCutover.getDayOfMonth() == 1) { 3218 // The cutover happened on January 1. 3219 return fixedDate - date.getDayOfMonth() + 1; 3220 } 3221 3222 long fixedDateMonth1; 3223 // The cutover happened sometime during the year. 3224 if (date.getMonth() == gCutover.getMonth()) { 3225 // The cutover happened in the month. 3226 BaseCalendar.Date jLastDate = getLastJulianDate(); 3227 if (gregorianCutoverYear == gregorianCutoverYearJulian 3228 && gCutover.getMonth() == jLastDate.getMonth()) { 3229 // The "gap" fits in the same month. 3230 fixedDateMonth1 = jcal.getFixedDate(date.getNormalizedYear(), 3231 date.getMonth(), 3232 1, 3233 null); 3234 } else { 3235 // Use the cutover date as the first day of the month. 3236 fixedDateMonth1 = gregorianCutoverDate; 3237 } 3238 } else { 3239 // The cutover happened before the month. 3240 fixedDateMonth1 = fixedDate - date.getDayOfMonth() + 1; 3241 } 3242 3243 return fixedDateMonth1; 3244 } 3245 3246 /** 3247 * Returns a CalendarDate produced from the specified fixed date. 3248 * 3249 * @param fd the fixed date 3250 */ 3251 private BaseCalendar.Date getCalendarDate(long fd) { 3252 BaseCalendar cal = (fd >= gregorianCutoverDate) ? gcal : getJulianCalendarSystem(); 3253 BaseCalendar.Date d = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.NO_TIMEZONE); 3254 cal.getCalendarDateFromFixedDate(d, fd); 3255 return d; 3256 } 3257 3258 /** 3259 * Returns the Gregorian cutover date as a BaseCalendar.Date. The 3260 * date is a Gregorian date. 3261 */ 3262 private BaseCalendar.Date getGregorianCutoverDate() { 3263 return getCalendarDate(gregorianCutoverDate); 3264 } 3265 3266 /** 3267 * Returns the day before the Gregorian cutover date as a 3268 * BaseCalendar.Date. The date is a Julian date. 3269 */ 3270 private BaseCalendar.Date getLastJulianDate() { 3271 return getCalendarDate(gregorianCutoverDate - 1); 3272 } 3273 3274 /** 3275 * Returns the length of the specified month in the specified 3276 * year. The year number must be normalized. 3277 * 3278 * @see #isLeapYear(int) 3279 */ 3280 private int monthLength(int month, int year) { 3281 return isLeapYear(year) ? LEAP_MONTH_LENGTH[month] : MONTH_LENGTH[month]; 3282 } 3283 3284 /** 3285 * Returns the length of the specified month in the year provided 3286 * by internalGet(YEAR). 3287 * 3288 * @see #isLeapYear(int) 3289 */ 3290 private int monthLength(int month) { 3291 int year = internalGet(YEAR); 3292 if (internalGetEra() == BCE) { 3293 year = 1 - year; 3294 } 3295 return monthLength(month, year); 3296 } 3297 3298 private int actualMonthLength() { 3299 int year = cdate.getNormalizedYear(); 3300 if (year != gregorianCutoverYear && year != gregorianCutoverYearJulian) { 3301 return calsys.getMonthLength(cdate); 3302 } 3303 BaseCalendar.Date date = (BaseCalendar.Date) cdate.clone(); 3304 long fd = calsys.getFixedDate(date); 3305 long month1 = getFixedDateMonth1(date, fd); 3306 long next1 = month1 + calsys.getMonthLength(date); 3307 if (next1 < gregorianCutoverDate) { 3308 return (int)(next1 - month1); 3309 } 3310 if (cdate != gdate) { 3311 date = (BaseCalendar.Date) gcal.newCalendarDate(TimeZone.NO_TIMEZONE); 3312 } 3313 gcal.getCalendarDateFromFixedDate(date, next1); 3314 next1 = getFixedDateMonth1(date, next1); 3315 return (int)(next1 - month1); 3316 } 3317 3318 /** 3319 * Returns the length (in days) of the specified year. The year 3320 * must be normalized. 3321 */ 3322 private int yearLength(int year) { 3323 return isLeapYear(year) ? 366 : 365; 3324 } 3325 3326 /** 3327 * Returns the length (in days) of the year provided by 3328 * internalGet(YEAR). 3329 */ 3330 private int yearLength() { 3331 int year = internalGet(YEAR); 3332 if (internalGetEra() == BCE) { 3333 year = 1 - year; 3334 } 3335 return yearLength(year); 3336 } 3337 3338 /** 3339 * After adjustments such as add(MONTH), add(YEAR), we don't want the 3340 * month to jump around. E.g., we don't want Jan 31 + 1 month to go to Mar 3341 * 3, we want it to go to Feb 28. Adjustments which might run into this 3342 * problem call this method to retain the proper month. 3343 */ 3344 private void pinDayOfMonth() { 3345 int year = internalGet(YEAR); 3346 int monthLen; 3347 if (year > gregorianCutoverYear || year < gregorianCutoverYearJulian) { 3348 monthLen = monthLength(internalGet(MONTH)); 3349 } else { 3350 GregorianCalendar gc = getNormalizedCalendar(); 3351 monthLen = gc.getActualMaximum(DAY_OF_MONTH); 3352 } 3353 int dom = internalGet(DAY_OF_MONTH); 3354 if (dom > monthLen) { 3355 set(DAY_OF_MONTH, monthLen); 3356 } 3357 } 3358 3359 /** 3360 * Returns the fixed date value of this object. The time value and 3361 * calendar fields must be in synch. 3362 */ 3363 private long getCurrentFixedDate() { 3364 return (calsys == gcal) ? cachedFixedDate : calsys.getFixedDate(cdate); 3365 } 3366 3367 /** 3368 * Returns the new value after 'roll'ing the specified value and amount. 3369 */ 3370 private static int getRolledValue(int value, int amount, int min, int max) { 3371 assert value >= min && value <= max; 3372 int range = max - min + 1; 3373 amount %= range; 3374 int n = value + amount; 3375 if (n > max) { 3376 n -= range; 3377 } else if (n < min) { 3378 n += range; 3379 } 3380 assert n >= min && n <= max; 3381 return n; 3382 } 3383 3384 /** 3385 * Returns the ERA. We need a special method for this because the 3386 * default ERA is CE, but a zero (unset) ERA is BCE. 3387 */ 3388 private int internalGetEra() { 3389 return isSet(ERA) ? internalGet(ERA) : CE; 3390 } 3391 3392 /** 3393 * Updates internal state. 3394 */ 3395 private void readObject(ObjectInputStream stream) 3396 throws IOException, ClassNotFoundException { 3397 stream.defaultReadObject(); 3398 if (gdate == null) { 3399 gdate = (BaseCalendar.Date) gcal.newCalendarDate(getZone()); 3400 cachedFixedDate = Long.MIN_VALUE; 3401 } 3402 setGregorianChange(gregorianCutover); 3403 } 3404 3405 /** 3406 * Converts this object to a {@code ZonedDateTime} that represents 3407 * the same point on the time-line as this {@code GregorianCalendar}. 3408 * <p> 3409 * Since this object supports a Julian-Gregorian cutover date and 3410 * {@code ZonedDateTime} does not, it is possible that the resulting year, 3411 * month and day will have different values. The result will represent the 3412 * correct date in the ISO calendar system, which will also be the same value 3413 * for Modified Julian Days. 3414 * 3415 * @return a zoned date-time representing the same point on the time-line 3416 * as this gregorian calendar 3417 * @since 1.8 3418 */ 3419 public ZonedDateTime toZonedDateTime() { 3420 return ZonedDateTime.ofInstant(Instant.ofEpochMilli(getTimeInMillis()), 3421 getTimeZone().toZoneId()); 3422 } 3423 3424 /** 3425 * Obtains an instance of {@code GregorianCalendar} with the default locale 3426 * from a {@code ZonedDateTime} object. 3427 * <p> 3428 * Since {@code ZonedDateTime} does not support a Julian-Gregorian cutover 3429 * date and uses ISO calendar system, the return GregorianCalendar is a pure 3430 * Gregorian calendar and uses ISO 8601 standard for week definitions, 3431 * which has {@code MONDAY} as the {@link Calendar#getFirstDayOfWeek() 3432 * FirstDayOfWeek} and {@code 4} as the value of the 3433 * {@link Calendar#getMinimalDaysInFirstWeek() MinimalDaysInFirstWeek}. 3434 * <p> 3435 * {@code ZoneDateTime} can store points on the time-line further in the 3436 * future and further in the past than {@code GregorianCalendar}. In this 3437 * scenario, this method will throw an {@code IllegalArgumentException} 3438 * exception. 3439 * 3440 * @param zdt the zoned date-time object to convert 3441 * @return the gregorian calendar representing the same point on the 3442 * time-line as the zoned date-time provided 3443 * @exception NullPointerException if {@code zdt} is null 3444 * @exception IllegalArgumentException if the zoned date-time is too 3445 * large to represent as a {@code GregorianCalendar} 3446 * @since 1.8 3447 */ 3448 public static GregorianCalendar from(ZonedDateTime zdt) { 3449 GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone(zdt.getZone())); 3450 cal.setGregorianChange(new Date(Long.MIN_VALUE)); 3451 cal.setFirstDayOfWeek(MONDAY); 3452 cal.setMinimalDaysInFirstWeek(4); 3453 try { 3454 cal.setTimeInMillis(Math.addExact(Math.multiplyExact(zdt.toEpochSecond(), 1000), 3455 zdt.get(ChronoField.MILLI_OF_SECOND))); 3456 } catch (ArithmeticException ex) { 3457 throw new IllegalArgumentException(ex); 3458 } 3459 return cal; 3460 } 3461} 3462