1 /* 2 * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 /* 27 * (C) Copyright Taligent, Inc. 1996-1998 - All Rights Reserved 28 * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved 29 * 30 * The original version of this source code and documentation is copyrighted 31 * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These 32 * materials are provided under terms of a License Agreement between Taligent 33 * and Sun. This technology is protected by multiple US and International 34 * patents. This notice and attribution to Taligent may not be removed. 35 * Taligent is a registered trademark of Taligent, Inc. 36 * 37 */ 38 39 package java.util; 40 41 import java.io.IOException; 42 import java.io.ObjectInputStream; 43 import java.io.ObjectOutputStream; 44 import java.io.OptionalDataException; 45 import java.io.Serializable; 46 import java.security.AccessControlContext; 47 import java.security.AccessController; 48 import java.security.PermissionCollection; 49 import java.security.PrivilegedActionException; 50 import java.security.PrivilegedExceptionAction; 51 import java.security.ProtectionDomain; 52 import java.text.DateFormat; 53 import java.text.DateFormatSymbols; 54 import java.time.Instant; 55 import java.util.concurrent.ConcurrentHashMap; 56 import java.util.concurrent.ConcurrentMap; 57 import sun.util.BuddhistCalendar; 58 import sun.util.calendar.ZoneInfo; 59 import sun.util.locale.provider.CalendarDataUtility; 60 import sun.util.locale.provider.LocaleProviderAdapter; 61 import sun.util.spi.CalendarProvider; 62 63 /** 64 * The <code>Calendar</code> class is an abstract class that provides methods 65 * for converting between a specific instant in time and a set of {@link 66 * #fields calendar fields} such as <code>YEAR</code>, <code>MONTH</code>, 67 * <code>DAY_OF_MONTH</code>, <code>HOUR</code>, and so on, and for 68 * manipulating the calendar fields, such as getting the date of the next 69 * week. An instant in time can be represented by a millisecond value that is 70 * an offset from the <a name="Epoch"><em>Epoch</em></a>, January 1, 1970 71 * 00:00:00.000 GMT (Gregorian). 72 * 73 * <p>The class also provides additional fields and methods for 74 * implementing a concrete calendar system outside the package. Those 75 * fields and methods are defined as <code>protected</code>. 76 * 77 * <p> 78 * Like other locale-sensitive classes, <code>Calendar</code> provides a 79 * class method, <code>getInstance</code>, for getting a generally useful 80 * object of this type. <code>Calendar</code>'s <code>getInstance</code> method 81 * returns a <code>Calendar</code> object whose 82 * calendar fields have been initialized with the current date and time: 83 * <blockquote> 84 * <pre> 85 * Calendar rightNow = Calendar.getInstance(); 86 * </pre> 87 * </blockquote> 88 * 89 * <p>A <code>Calendar</code> object can produce all the calendar field values 90 * needed to implement the date-time formatting for a particular language and 91 * calendar style (for example, Japanese-Gregorian, Japanese-Traditional). 92 * <code>Calendar</code> defines the range of values returned by 93 * certain calendar fields, as well as their meaning. For example, 94 * the first month of the calendar system has value <code>MONTH == 95 * JANUARY</code> for all calendars. Other values are defined by the 96 * concrete subclass, such as <code>ERA</code>. See individual field 97 * documentation and subclass documentation for details. 98 * 99 * <h4>Getting and Setting Calendar Field Values</h4> 100 * 101 * <p>The calendar field values can be set by calling the <code>set</code> 102 * methods. Any field values set in a <code>Calendar</code> will not be 103 * interpreted until it needs to calculate its time value (milliseconds from 104 * the Epoch) or values of the calendar fields. Calling the 105 * <code>get</code>, <code>getTimeInMillis</code>, <code>getTime</code>, 106 * <code>add</code> and <code>roll</code> involves such calculation. 107 * 108 * <h4>Leniency</h4> 109 * 110 * <p><code>Calendar</code> has two modes for interpreting the calendar 111 * fields, <em>lenient</em> and <em>non-lenient</em>. When a 112 * <code>Calendar</code> is in lenient mode, it accepts a wider range of 113 * calendar field values than it produces. When a <code>Calendar</code> 114 * recomputes calendar field values for return by <code>get()</code>, all of 115 * the calendar fields are normalized. For example, a lenient 116 * <code>GregorianCalendar</code> interprets <code>MONTH == JANUARY</code>, 117 * <code>DAY_OF_MONTH == 32</code> as February 1. 118 119 * <p>When a <code>Calendar</code> is in non-lenient mode, it throws an 120 * exception if there is any inconsistency in its calendar fields. For 121 * example, a <code>GregorianCalendar</code> always produces 122 * <code>DAY_OF_MONTH</code> values between 1 and the length of the month. A 123 * non-lenient <code>GregorianCalendar</code> throws an exception upon 124 * calculating its time or calendar field values if any out-of-range field 125 * value has been set. 126 * 127 * <h4><a name="first_week">First Week</a></h4> 128 * 129 * <code>Calendar</code> defines a locale-specific seven day week using two 130 * parameters: the first day of the week and the minimal days in first week 131 * (from 1 to 7). These numbers are taken from the locale resource data when a 132 * <code>Calendar</code> is constructed. They may also be specified explicitly 133 * through the methods for setting their values. 134 * 135 * <p>When setting or getting the <code>WEEK_OF_MONTH</code> or 136 * <code>WEEK_OF_YEAR</code> fields, <code>Calendar</code> must determine the 137 * first week of the month or year as a reference point. The first week of a 138 * month or year is defined as the earliest seven day period beginning on 139 * <code>getFirstDayOfWeek()</code> and containing at least 140 * <code>getMinimalDaysInFirstWeek()</code> days of that month or year. Weeks 141 * numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow 142 * it. Note that the normalized numbering returned by <code>get()</code> may be 143 * different. For example, a specific <code>Calendar</code> subclass may 144 * designate the week before week 1 of a year as week <code><i>n</i></code> of 145 * the previous year. 146 * 147 * <h4>Calendar Fields Resolution</h4> 148 * 149 * When computing a date and time from the calendar fields, there 150 * may be insufficient information for the computation (such as only 151 * year and month with no day of month), or there may be inconsistent 152 * information (such as Tuesday, July 15, 1996 (Gregorian) -- July 15, 153 * 1996 is actually a Monday). <code>Calendar</code> will resolve 154 * calendar field values to determine the date and time in the 155 * following way. 156 * 157 * <p><a name="resolution">If there is any conflict in calendar field values, 158 * <code>Calendar</code> gives priorities to calendar fields that have been set 159 * more recently.</a> The following are the default combinations of the 160 * calendar fields. The most recent combination, as determined by the 161 * most recently set single field, will be used. 162 * 163 * <p><a name="date_resolution">For the date fields</a>: 164 * <blockquote> 165 * <pre> 166 * YEAR + MONTH + DAY_OF_MONTH 167 * YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK 168 * YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK 169 * YEAR + DAY_OF_YEAR 170 * YEAR + DAY_OF_WEEK + WEEK_OF_YEAR 171 * </pre></blockquote> 172 * 173 * <a name="time_resolution">For the time of day fields</a>: 174 * <blockquote> 175 * <pre> 176 * HOUR_OF_DAY 177 * AM_PM + HOUR 178 * </pre></blockquote> 179 * 180 * <p>If there are any calendar fields whose values haven't been set in the selected 181 * field combination, <code>Calendar</code> uses their default values. The default 182 * value of each field may vary by concrete calendar systems. For example, in 183 * <code>GregorianCalendar</code>, the default of a field is the same as that 184 * of the start of the Epoch: i.e., <code>YEAR = 1970</code>, <code>MONTH = 185 * JANUARY</code>, <code>DAY_OF_MONTH = 1</code>, etc. 186 * 187 * <p> 188 * <strong>Note:</strong> There are certain possible ambiguities in 189 * interpretation of certain singular times, which are resolved in the 190 * following ways: 191 * <ol> 192 * <li> 23:59 is the last minute of the day and 00:00 is the first 193 * minute of the next day. Thus, 23:59 on Dec 31, 1999 < 00:00 on 194 * Jan 1, 2000 < 00:01 on Jan 1, 2000. 195 * 196 * <li> Although historically not precise, midnight also belongs to "am", 197 * and noon belongs to "pm", so on the same day, 198 * 12:00 am (midnight) < 12:01 am, and 12:00 pm (noon) < 12:01 pm 199 * </ol> 200 * 201 * <p> 202 * The date or time format strings are not part of the definition of a 203 * calendar, as those must be modifiable or overridable by the user at 204 * runtime. Use {@link DateFormat} 205 * to format dates. 206 * 207 * <h4>Field Manipulation</h4> 208 * 209 * The calendar fields can be changed using three methods: 210 * <code>set()</code>, <code>add()</code>, and <code>roll()</code>.</p> 211 * 212 * <p><strong><code>set(f, value)</code></strong> changes calendar field 213 * <code>f</code> to <code>value</code>. In addition, it sets an 214 * internal member variable to indicate that calendar field <code>f</code> has 215 * been changed. Although calendar field <code>f</code> is changed immediately, 216 * the calendar's time value in milliseconds is not recomputed until the next call to 217 * <code>get()</code>, <code>getTime()</code>, <code>getTimeInMillis()</code>, 218 * <code>add()</code>, or <code>roll()</code> is made. Thus, multiple calls to 219 * <code>set()</code> do not trigger multiple, unnecessary 220 * computations. As a result of changing a calendar field using 221 * <code>set()</code>, other calendar fields may also change, depending on the 222 * calendar field, the calendar field value, and the calendar system. In addition, 223 * <code>get(f)</code> will not necessarily return <code>value</code> set by 224 * the call to the <code>set</code> method 225 * after the calendar fields have been recomputed. The specifics are determined by 226 * the concrete calendar class.</p> 227 * 228 * <p><em>Example</em>: Consider a <code>GregorianCalendar</code> 229 * originally set to August 31, 1999. Calling <code>set(Calendar.MONTH, 230 * Calendar.SEPTEMBER)</code> sets the date to September 31, 231 * 1999. This is a temporary internal representation that resolves to 232 * October 1, 1999 if <code>getTime()</code>is then called. However, a 233 * call to <code>set(Calendar.DAY_OF_MONTH, 30)</code> before the call to 234 * <code>getTime()</code> sets the date to September 30, 1999, since 235 * no recomputation occurs after <code>set()</code> itself.</p> 236 * 237 * <p><strong><code>add(f, delta)</code></strong> adds <code>delta</code> 238 * to field <code>f</code>. This is equivalent to calling <code>set(f, 239 * get(f) + delta)</code> with two adjustments:</p> 240 * 241 * <blockquote> 242 * <p><strong>Add rule 1</strong>. The value of field <code>f</code> 243 * after the call minus the value of field <code>f</code> before the 244 * call is <code>delta</code>, modulo any overflow that has occurred in 245 * field <code>f</code>. Overflow occurs when a field value exceeds its 246 * range and, as a result, the next larger field is incremented or 247 * decremented and the field value is adjusted back into its range.</p> 248 * 249 * <p><strong>Add rule 2</strong>. If a smaller field is expected to be 250 * invariant, but it is impossible for it to be equal to its 251 * prior value because of changes in its minimum or maximum after field 252 * <code>f</code> is changed or other constraints, such as time zone 253 * offset changes, then its value is adjusted to be as close 254 * as possible to its expected value. A smaller field represents a 255 * smaller unit of time. <code>HOUR</code> is a smaller field than 256 * <code>DAY_OF_MONTH</code>. No adjustment is made to smaller fields 257 * that are not expected to be invariant. The calendar system 258 * determines what fields are expected to be invariant.</p> 259 * </blockquote> 260 * 261 * <p>In addition, unlike <code>set()</code>, <code>add()</code> forces 262 * an immediate recomputation of the calendar's milliseconds and all 263 * fields.</p> 264 * 265 * <p><em>Example</em>: Consider a <code>GregorianCalendar</code> 266 * originally set to August 31, 1999. Calling <code>add(Calendar.MONTH, 267 * 13)</code> sets the calendar to September 30, 2000. <strong>Add rule 268 * 1</strong> sets the <code>MONTH</code> field to September, since 269 * adding 13 months to August gives September of the next year. Since 270 * <code>DAY_OF_MONTH</code> cannot be 31 in September in a 271 * <code>GregorianCalendar</code>, <strong>add rule 2</strong> sets the 272 * <code>DAY_OF_MONTH</code> to 30, the closest possible value. Although 273 * it is a smaller field, <code>DAY_OF_WEEK</code> is not adjusted by 274 * rule 2, since it is expected to change when the month changes in a 275 * <code>GregorianCalendar</code>.</p> 276 * 277 * <p><strong><code>roll(f, delta)</code></strong> adds 278 * <code>delta</code> to field <code>f</code> without changing larger 279 * fields. This is equivalent to calling <code>add(f, delta)</code> with 280 * the following adjustment:</p> 281 * 282 * <blockquote> 283 * <p><strong>Roll rule</strong>. Larger fields are unchanged after the 284 * call. A larger field represents a larger unit of 285 * time. <code>DAY_OF_MONTH</code> is a larger field than 286 * <code>HOUR</code>.</p> 287 * </blockquote> 288 * 289 * <p><em>Example</em>: See {@link java.util.GregorianCalendar#roll(int, int)}. 290 * 291 * <p><strong>Usage model</strong>. To motivate the behavior of 292 * <code>add()</code> and <code>roll()</code>, consider a user interface 293 * component with increment and decrement buttons for the month, day, and 294 * year, and an underlying <code>GregorianCalendar</code>. If the 295 * interface reads January 31, 1999 and the user presses the month 296 * increment button, what should it read? If the underlying 297 * implementation uses <code>set()</code>, it might read March 3, 1999. A 298 * better result would be February 28, 1999. Furthermore, if the user 299 * presses the month increment button again, it should read March 31, 300 * 1999, not March 28, 1999. By saving the original date and using either 301 * <code>add()</code> or <code>roll()</code>, depending on whether larger 302 * fields should be affected, the user interface can behave as most users 303 * will intuitively expect.</p> 304 * 305 * @see java.lang.System#currentTimeMillis() 306 * @see Date 307 * @see GregorianCalendar 308 * @see TimeZone 309 * @see java.text.DateFormat 310 * @author Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu 311 * @since JDK1.1 312 */ 313 public abstract class Calendar implements Serializable, Cloneable, Comparable<Calendar> { 314 315 // Data flow in Calendar 316 // --------------------- 317 318 // The current time is represented in two ways by Calendar: as UTC 319 // milliseconds from the epoch (1 January 1970 0:00 UTC), and as local 320 // fields such as MONTH, HOUR, AM_PM, etc. It is possible to compute the 321 // millis from the fields, and vice versa. The data needed to do this 322 // conversion is encapsulated by a TimeZone object owned by the Calendar. 323 // The data provided by the TimeZone object may also be overridden if the 324 // user sets the ZONE_OFFSET and/or DST_OFFSET fields directly. The class 325 // keeps track of what information was most recently set by the caller, and 326 // uses that to compute any other information as needed. 327 328 // If the user sets the fields using set(), the data flow is as follows. 329 // This is implemented by the Calendar subclass's computeTime() method. 330 // During this process, certain fields may be ignored. The disambiguation 331 // algorithm for resolving which fields to pay attention to is described 332 // in the class documentation. 333 334 // local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.) 335 // | 336 // | Using Calendar-specific algorithm 337 // V 338 // local standard millis 339 // | 340 // | Using TimeZone or user-set ZONE_OFFSET / DST_OFFSET 341 // V 342 // UTC millis (in time data member) 343 344 // If the user sets the UTC millis using setTime() or setTimeInMillis(), 345 // the data flow is as follows. This is implemented by the Calendar 346 // subclass's computeFields() method. 347 348 // UTC millis (in time data member) 349 // | 350 // | Using TimeZone getOffset() 351 // V 352 // local standard millis 353 // | 354 // | Using Calendar-specific algorithm 355 // V 356 // local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.) 357 358 // In general, a round trip from fields, through local and UTC millis, and 359 // back out to fields is made when necessary. This is implemented by the 360 // complete() method. Resolving a partial set of fields into a UTC millis 361 // value allows all remaining fields to be generated from that value. If 362 // the Calendar is lenient, the fields are also renormalized to standard 363 // ranges when they are regenerated. 364 365 /** 366 * Field number for <code>get</code> and <code>set</code> indicating the 367 * era, e.g., AD or BC in the Julian calendar. This is a calendar-specific 368 * value; see subclass documentation. 369 * 370 * @see GregorianCalendar#AD 371 * @see GregorianCalendar#BC 372 */ 373 public final static int ERA = 0; 374 375 /** 376 * Field number for <code>get</code> and <code>set</code> indicating the 377 * year. This is a calendar-specific value; see subclass documentation. 378 */ 379 public final static int YEAR = 1; 380 381 /** 382 * Field number for <code>get</code> and <code>set</code> indicating the 383 * month. This is a calendar-specific value. The first month of 384 * the year in the Gregorian and Julian calendars is 385 * <code>JANUARY</code> which is 0; the last depends on the number 386 * of months in a year. 387 * 388 * @see #JANUARY 389 * @see #FEBRUARY 390 * @see #MARCH 391 * @see #APRIL 392 * @see #MAY 393 * @see #JUNE 394 * @see #JULY 395 * @see #AUGUST 396 * @see #SEPTEMBER 397 * @see #OCTOBER 398 * @see #NOVEMBER 399 * @see #DECEMBER 400 * @see #UNDECIMBER 401 */ 402 public final static int MONTH = 2; 403 404 /** 405 * Field number for <code>get</code> and <code>set</code> indicating the 406 * week number within the current year. The first week of the year, as 407 * defined by <code>getFirstDayOfWeek()</code> and 408 * <code>getMinimalDaysInFirstWeek()</code>, has value 1. Subclasses define 409 * the value of <code>WEEK_OF_YEAR</code> for days before the first week of 410 * the year. 411 * 412 * @see #getFirstDayOfWeek 413 * @see #getMinimalDaysInFirstWeek 414 */ 415 public final static int WEEK_OF_YEAR = 3; 416 417 /** 418 * Field number for <code>get</code> and <code>set</code> indicating the 419 * week number within the current month. The first week of the month, as 420 * defined by <code>getFirstDayOfWeek()</code> and 421 * <code>getMinimalDaysInFirstWeek()</code>, has value 1. Subclasses define 422 * the value of <code>WEEK_OF_MONTH</code> for days before the first week of 423 * the month. 424 * 425 * @see #getFirstDayOfWeek 426 * @see #getMinimalDaysInFirstWeek 427 */ 428 public final static int WEEK_OF_MONTH = 4; 429 430 /** 431 * Field number for <code>get</code> and <code>set</code> indicating the 432 * day of the month. This is a synonym for <code>DAY_OF_MONTH</code>. 433 * The first day of the month has value 1. 434 * 435 * @see #DAY_OF_MONTH 436 */ 437 public final static int DATE = 5; 438 439 /** 440 * Field number for <code>get</code> and <code>set</code> indicating the 441 * day of the month. This is a synonym for <code>DATE</code>. 442 * The first day of the month has value 1. 443 * 444 * @see #DATE 445 */ 446 public final static int DAY_OF_MONTH = 5; 447 448 /** 449 * Field number for <code>get</code> and <code>set</code> indicating the day 450 * number within the current year. The first day of the year has value 1. 451 */ 452 public final static int DAY_OF_YEAR = 6; 453 454 /** 455 * Field number for <code>get</code> and <code>set</code> indicating the day 456 * of the week. This field takes values <code>SUNDAY</code>, 457 * <code>MONDAY</code>, <code>TUESDAY</code>, <code>WEDNESDAY</code>, 458 * <code>THURSDAY</code>, <code>FRIDAY</code>, and <code>SATURDAY</code>. 459 * 460 * @see #SUNDAY 461 * @see #MONDAY 462 * @see #TUESDAY 463 * @see #WEDNESDAY 464 * @see #THURSDAY 465 * @see #FRIDAY 466 * @see #SATURDAY 467 */ 468 public final static int DAY_OF_WEEK = 7; 469 470 /** 471 * Field number for <code>get</code> and <code>set</code> indicating the 472 * ordinal number of the day of the week within the current month. Together 473 * with the <code>DAY_OF_WEEK</code> field, this uniquely specifies a day 474 * within a month. Unlike <code>WEEK_OF_MONTH</code> and 475 * <code>WEEK_OF_YEAR</code>, this field's value does <em>not</em> depend on 476 * <code>getFirstDayOfWeek()</code> or 477 * <code>getMinimalDaysInFirstWeek()</code>. <code>DAY_OF_MONTH 1</code> 478 * through <code>7</code> always correspond to <code>DAY_OF_WEEK_IN_MONTH 479 * 1</code>; <code>8</code> through <code>14</code> correspond to 480 * <code>DAY_OF_WEEK_IN_MONTH 2</code>, and so on. 481 * <code>DAY_OF_WEEK_IN_MONTH 0</code> indicates the week before 482 * <code>DAY_OF_WEEK_IN_MONTH 1</code>. Negative values count back from the 483 * end of the month, so the last Sunday of a month is specified as 484 * <code>DAY_OF_WEEK = SUNDAY, DAY_OF_WEEK_IN_MONTH = -1</code>. Because 485 * negative values count backward they will usually be aligned differently 486 * within the month than positive values. For example, if a month has 31 487 * days, <code>DAY_OF_WEEK_IN_MONTH -1</code> will overlap 488 * <code>DAY_OF_WEEK_IN_MONTH 5</code> and the end of <code>4</code>. 489 * 490 * @see #DAY_OF_WEEK 491 * @see #WEEK_OF_MONTH 492 */ 493 public final static int DAY_OF_WEEK_IN_MONTH = 8; 494 495 /** 496 * Field number for <code>get</code> and <code>set</code> indicating 497 * whether the <code>HOUR</code> is before or after noon. 498 * E.g., at 10:04:15.250 PM the <code>AM_PM</code> is <code>PM</code>. 499 * 500 * @see #AM 501 * @see #PM 502 * @see #HOUR 503 */ 504 public final static int AM_PM = 9; 505 506 /** 507 * Field number for <code>get</code> and <code>set</code> indicating the 508 * hour of the morning or afternoon. <code>HOUR</code> is used for the 509 * 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12. 510 * E.g., at 10:04:15.250 PM the <code>HOUR</code> is 10. 511 * 512 * @see #AM_PM 513 * @see #HOUR_OF_DAY 514 */ 515 public final static int HOUR = 10; 516 517 /** 518 * Field number for <code>get</code> and <code>set</code> indicating the 519 * hour of the day. <code>HOUR_OF_DAY</code> is used for the 24-hour clock. 520 * E.g., at 10:04:15.250 PM the <code>HOUR_OF_DAY</code> is 22. 521 * 522 * @see #HOUR 523 */ 524 public final static int HOUR_OF_DAY = 11; 525 526 /** 527 * Field number for <code>get</code> and <code>set</code> indicating the 528 * minute within the hour. 529 * E.g., at 10:04:15.250 PM the <code>MINUTE</code> is 4. 530 */ 531 public final static int MINUTE = 12; 532 533 /** 534 * Field number for <code>get</code> and <code>set</code> indicating the 535 * second within the minute. 536 * E.g., at 10:04:15.250 PM the <code>SECOND</code> is 15. 537 */ 538 public final static int SECOND = 13; 539 540 /** 541 * Field number for <code>get</code> and <code>set</code> indicating the 542 * millisecond within the second. 543 * E.g., at 10:04:15.250 PM the <code>MILLISECOND</code> is 250. 544 */ 545 public final static int MILLISECOND = 14; 546 547 /** 548 * Field number for <code>get</code> and <code>set</code> 549 * indicating the raw offset from GMT in milliseconds. 550 * <p> 551 * This field reflects the correct GMT offset value of the time 552 * zone of this <code>Calendar</code> if the 553 * <code>TimeZone</code> implementation subclass supports 554 * historical GMT offset changes. 555 */ 556 public final static int ZONE_OFFSET = 15; 557 558 /** 559 * Field number for <code>get</code> and <code>set</code> indicating the 560 * daylight saving offset in milliseconds. 561 * <p> 562 * This field reflects the correct daylight saving offset value of 563 * the time zone of this <code>Calendar</code> if the 564 * <code>TimeZone</code> implementation subclass supports 565 * historical Daylight Saving Time schedule changes. 566 */ 567 public final static int DST_OFFSET = 16; 568 569 /** 570 * The number of distinct fields recognized by <code>get</code> and <code>set</code>. 571 * Field numbers range from <code>0..FIELD_COUNT-1</code>. 572 */ 573 public final static int FIELD_COUNT = 17; 574 575 /** 576 * Value of the {@link #DAY_OF_WEEK} field indicating 577 * Sunday. 578 */ 579 public final static int SUNDAY = 1; 580 581 /** 582 * Value of the {@link #DAY_OF_WEEK} field indicating 583 * Monday. 584 */ 585 public final static int MONDAY = 2; 586 587 /** 588 * Value of the {@link #DAY_OF_WEEK} field indicating 589 * Tuesday. 590 */ 591 public final static int TUESDAY = 3; 592 593 /** 594 * Value of the {@link #DAY_OF_WEEK} field indicating 595 * Wednesday. 596 */ 597 public final static int WEDNESDAY = 4; 598 599 /** 600 * Value of the {@link #DAY_OF_WEEK} field indicating 601 * Thursday. 602 */ 603 public final static int THURSDAY = 5; 604 605 /** 606 * Value of the {@link #DAY_OF_WEEK} field indicating 607 * Friday. 608 */ 609 public final static int FRIDAY = 6; 610 611 /** 612 * Value of the {@link #DAY_OF_WEEK} field indicating 613 * Saturday. 614 */ 615 public final static int SATURDAY = 7; 616 617 /** 618 * Value of the {@link #MONTH} field indicating the 619 * first month of the year in the Gregorian and Julian calendars. 620 */ 621 public final static int JANUARY = 0; 622 623 /** 624 * Value of the {@link #MONTH} field indicating the 625 * second month of the year in the Gregorian and Julian calendars. 626 */ 627 public final static int FEBRUARY = 1; 628 629 /** 630 * Value of the {@link #MONTH} field indicating the 631 * third month of the year in the Gregorian and Julian calendars. 632 */ 633 public final static int MARCH = 2; 634 635 /** 636 * Value of the {@link #MONTH} field indicating the 637 * fourth month of the year in the Gregorian and Julian calendars. 638 */ 639 public final static int APRIL = 3; 640 641 /** 642 * Value of the {@link #MONTH} field indicating the 643 * fifth month of the year in the Gregorian and Julian calendars. 644 */ 645 public final static int MAY = 4; 646 647 /** 648 * Value of the {@link #MONTH} field indicating the 649 * sixth month of the year in the Gregorian and Julian calendars. 650 */ 651 public final static int JUNE = 5; 652 653 /** 654 * Value of the {@link #MONTH} field indicating the 655 * seventh month of the year in the Gregorian and Julian calendars. 656 */ 657 public final static int JULY = 6; 658 659 /** 660 * Value of the {@link #MONTH} field indicating the 661 * eighth month of the year in the Gregorian and Julian calendars. 662 */ 663 public final static int AUGUST = 7; 664 665 /** 666 * Value of the {@link #MONTH} field indicating the 667 * ninth month of the year in the Gregorian and Julian calendars. 668 */ 669 public final static int SEPTEMBER = 8; 670 671 /** 672 * Value of the {@link #MONTH} field indicating the 673 * tenth month of the year in the Gregorian and Julian calendars. 674 */ 675 public final static int OCTOBER = 9; 676 677 /** 678 * Value of the {@link #MONTH} field indicating the 679 * eleventh month of the year in the Gregorian and Julian calendars. 680 */ 681 public final static int NOVEMBER = 10; 682 683 /** 684 * Value of the {@link #MONTH} field indicating the 685 * twelfth month of the year in the Gregorian and Julian calendars. 686 */ 687 public final static int DECEMBER = 11; 688 689 /** 690 * Value of the {@link #MONTH} field indicating the 691 * thirteenth month of the year. Although <code>GregorianCalendar</code> 692 * does not use this value, lunar calendars do. 693 */ 694 public final static int UNDECIMBER = 12; 695 696 /** 697 * Value of the {@link #AM_PM} field indicating the 698 * period of the day from midnight to just before noon. 699 */ 700 public final static int AM = 0; 701 702 /** 703 * Value of the {@link #AM_PM} field indicating the 704 * period of the day from noon to just before midnight. 705 */ 706 public final static int PM = 1; 707 708 /** 709 * A style specifier for {@link #getDisplayNames(int, int, Locale) 710 * getDisplayNames} indicating names in all styles, such as 711 * "January" and "Jan". 712 * 713 * @see #SHORT_FORMAT 714 * @see #LONG_FORMAT 715 * @see #SHORT_STANDALONE 716 * @see #LONG_STANDALONE 717 * @see #SHORT 718 * @see #LONG 719 * @since 1.6 720 */ 721 public static final int ALL_STYLES = 0; 722 723 static final int STANDALONE_MASK = 0x8000; 724 725 /** 726 * A style specifier for {@link #getDisplayName(int, int, Locale) 727 * getDisplayName} and {@link #getDisplayNames(int, int, Locale) 728 * getDisplayNames} equivalent to {@link #SHORT_FORMAT}. 729 * 730 * @see #SHORT_STANDALONE 731 * @see #LONG 732 * @since 1.6 733 */ 734 public static final int SHORT = 1; 735 736 /** 737 * A style specifier for {@link #getDisplayName(int, int, Locale) 738 * getDisplayName} and {@link #getDisplayNames(int, int, Locale) 739 * getDisplayNames} equivalent to {@link #LONG_FORMAT}. 740 * 741 * @see #LONG_STANDALONE 742 * @see #SHORT 743 * @since 1.6 744 */ 745 public static final int LONG = 2; 746 747 /** 748 * A style specifier for {@link #getDisplayName(int, int, Locale) 749 * getDisplayName} and {@link #getDisplayNames(int, int, Locale) 750 * getDisplayNames} indicating a narrow name used for format. Narrow names 751 * are typically single character strings, such as "M" for Monday. 752 * 753 * @see #NARROW_STANDALONE 754 * @see #SHORT_FORMAT 755 * @see #LONG_FORMAT 756 * @since 1.8 757 */ 758 public static final int NARROW_FORMAT = 4; 759 760 /** 761 * A style specifier for {@link #getDisplayName(int, int, Locale) 762 * getDisplayName} and {@link #getDisplayNames(int, int, Locale) 763 * getDisplayNames} indicating a narrow name independently. Narrow names 764 * are typically single character strings, such as "M" for Monday. 765 * 766 * @see #NARROW_FORMAT 767 * @see #SHORT_STANDALONE 768 * @see #LONG_STANDALONE 769 * @since 1.8 770 */ 771 public static final int NARROW_STANDALONE = NARROW_FORMAT | STANDALONE_MASK; 772 773 /** 774 * A style specifier for {@link #getDisplayName(int, int, Locale) 775 * getDisplayName} and {@link #getDisplayNames(int, int, Locale) 776 * getDisplayNames} indicating a short name used for format. 777 * 778 * @see #SHORT_STANDALONE 779 * @see #LONG_FORMAT 780 * @see #LONG_STANDALONE 781 * @since 1.8 782 */ 783 public static final int SHORT_FORMAT = 1; 784 785 /** 786 * A style specifier for {@link #getDisplayName(int, int, Locale) 787 * getDisplayName} and {@link #getDisplayNames(int, int, Locale) 788 * getDisplayNames} indicating a long name used for format. 789 * 790 * @see #LONG_STANDALONE 791 * @see #SHORT_FORMAT 792 * @see #SHORT_STANDALONE 793 * @since 1.8 794 */ 795 public static final int LONG_FORMAT = 2; 796 797 /** 798 * A style specifier for {@link #getDisplayName(int, int, Locale) 799 * getDisplayName} and {@link #getDisplayNames(int, int, Locale) 800 * getDisplayNames} indicating a short name used independently, 801 * such as a month abbreviation as calendar headers. 802 * 803 * @see #SHORT_FORMAT 804 * @see #LONG_FORMAT 805 * @see #LONG_STANDALONE 806 * @since 1.8 807 */ 808 public static final int SHORT_STANDALONE = SHORT | STANDALONE_MASK; 809 810 /** 811 * A style specifier for {@link #getDisplayName(int, int, Locale) 812 * getDisplayName} and {@link #getDisplayNames(int, int, Locale) 813 * getDisplayNames} indicating a long name used independently, 814 * such as a month name as calendar headers. 815 * 816 * @see #LONG_FORMAT 817 * @see #SHORT_FORMAT 818 * @see #SHORT_STANDALONE 819 * @since 1.8 820 */ 821 public static final int LONG_STANDALONE = LONG | STANDALONE_MASK; 822 823 // Internal notes: 824 // Calendar contains two kinds of time representations: current "time" in 825 // milliseconds, and a set of calendar "fields" representing the current time. 826 // The two representations are usually in sync, but can get out of sync 827 // as follows. 828 // 1. Initially, no fields are set, and the time is invalid. 829 // 2. If the time is set, all fields are computed and in sync. 830 // 3. If a single field is set, the time is invalid. 831 // Recomputation of the time and fields happens when the object needs 832 // to return a result to the user, or use a result for a computation. 833 834 /** 835 * The calendar field values for the currently set time for this calendar. 836 * This is an array of <code>FIELD_COUNT</code> integers, with index values 837 * <code>ERA</code> through <code>DST_OFFSET</code>. 838 * @serial 839 */ 840 @SuppressWarnings("ProtectedField") 841 protected int fields[]; 842 843 /** 844 * The flags which tell if a specified calendar field for the calendar is set. 845 * A new object has no fields set. After the first call to a method 846 * which generates the fields, they all remain set after that. 847 * This is an array of <code>FIELD_COUNT</code> booleans, with index values 848 * <code>ERA</code> through <code>DST_OFFSET</code>. 849 * @serial 850 */ 851 @SuppressWarnings("ProtectedField") 852 protected boolean isSet[]; 853 854 /** 855 * Pseudo-time-stamps which specify when each field was set. There 856 * are two special values, UNSET and COMPUTED. Values from 857 * MINIMUM_USER_SET to Integer.MAX_VALUE are legal user set values. 858 */ 859 transient private int stamp[]; 860 861 /** 862 * The currently set time for this calendar, expressed in milliseconds after 863 * January 1, 1970, 0:00:00 GMT. 864 * @see #isTimeSet 865 * @serial 866 */ 867 @SuppressWarnings("ProtectedField") 868 protected long time; 869 870 /** 871 * True if then the value of <code>time</code> is valid. 872 * The time is made invalid by a change to an item of <code>field[]</code>. 873 * @see #time 874 * @serial 875 */ 876 @SuppressWarnings("ProtectedField") 877 protected boolean isTimeSet; 878 879 /** 880 * True if <code>fields[]</code> are in sync with the currently set time. 881 * If false, then the next attempt to get the value of a field will 882 * force a recomputation of all fields from the current value of 883 * <code>time</code>. 884 * @serial 885 */ 886 @SuppressWarnings("ProtectedField") 887 protected boolean areFieldsSet; 888 889 /** 890 * True if all fields have been set. 891 * @serial 892 */ 893 transient boolean areAllFieldsSet; 894 895 /** 896 * <code>True</code> if this calendar allows out-of-range field values during computation 897 * of <code>time</code> from <code>fields[]</code>. 898 * @see #setLenient 899 * @see #isLenient 900 * @serial 901 */ 902 private boolean lenient = true; 903 904 /** 905 * The <code>TimeZone</code> used by this calendar. <code>Calendar</code> 906 * uses the time zone data to translate between locale and GMT time. 907 * @serial 908 */ 909 private TimeZone zone; 910 911 /** 912 * <code>True</code> if zone references to a shared TimeZone object. 913 */ 914 transient private boolean sharedZone = false; 915 916 /** 917 * The first day of the week, with possible values <code>SUNDAY</code>, 918 * <code>MONDAY</code>, etc. This is a locale-dependent value. 919 * @serial 920 */ 921 private int firstDayOfWeek; 922 923 /** 924 * The number of days required for the first week in a month or year, 925 * with possible values from 1 to 7. This is a locale-dependent value. 926 * @serial 927 */ 928 private int minimalDaysInFirstWeek; 929 930 /** 931 * Cache to hold the firstDayOfWeek and minimalDaysInFirstWeek 932 * of a Locale. 933 */ 934 private static final ConcurrentMap<Locale, int[]> cachedLocaleData 935 = new ConcurrentHashMap<>(3); 936 937 // Special values of stamp[] 938 /** 939 * The corresponding fields[] has no value. 940 */ 941 private static final int UNSET = 0; 942 943 /** 944 * The value of the corresponding fields[] has been calculated internally. 945 */ 946 private static final int COMPUTED = 1; 947 948 /** 949 * The value of the corresponding fields[] has been set externally. Stamp 950 * values which are greater than 1 represents the (pseudo) time when the 951 * corresponding fields[] value was set. 952 */ 953 private static final int MINIMUM_USER_STAMP = 2; 954 955 /** 956 * The mask value that represents all of the fields. 957 */ 958 static final int ALL_FIELDS = (1 << FIELD_COUNT) - 1; 959 960 /** 961 * The next available value for <code>stamp[]</code>, an internal array. 962 * This actually should not be written out to the stream, and will probably 963 * be removed from the stream in the near future. In the meantime, 964 * a value of <code>MINIMUM_USER_STAMP</code> should be used. 965 * @serial 966 */ 967 private int nextStamp = MINIMUM_USER_STAMP; 968 969 // the internal serial version which says which version was written 970 // - 0 (default) for version up to JDK 1.1.5 971 // - 1 for version from JDK 1.1.6, which writes a correct 'time' value 972 // as well as compatible values for other fields. This is a 973 // transitional format. 974 // - 2 (not implemented yet) a future version, in which fields[], 975 // areFieldsSet, and isTimeSet become transient, and isSet[] is 976 // removed. In JDK 1.1.6 we write a format compatible with version 2. 977 static final int currentSerialVersion = 1; 978 979 /** 980 * The version of the serialized data on the stream. Possible values: 981 * <dl> 982 * <dt><b>0</b> or not present on stream</dt> 983 * <dd> 984 * JDK 1.1.5 or earlier. 985 * </dd> 986 * <dt><b>1</b></dt> 987 * <dd> 988 * JDK 1.1.6 or later. Writes a correct 'time' value 989 * as well as compatible values for other fields. This is a 990 * transitional format. 991 * </dd> 992 * </dl> 993 * When streaming out this class, the most recent format 994 * and the highest allowable <code>serialVersionOnStream</code> 995 * is written. 996 * @serial 997 * @since JDK1.1.6 998 */ 999 private int serialVersionOnStream = currentSerialVersion; 1000 1001 // Proclaim serialization compatibility with JDK 1.1 1002 static final long serialVersionUID = -1807547505821590642L; 1003 1004 // Mask values for calendar fields 1005 @SuppressWarnings("PointlessBitwiseExpression") 1006 final static int ERA_MASK = (1 << ERA); 1007 final static int YEAR_MASK = (1 << YEAR); 1008 final static int MONTH_MASK = (1 << MONTH); 1009 final static int WEEK_OF_YEAR_MASK = (1 << WEEK_OF_YEAR); 1010 final static int WEEK_OF_MONTH_MASK = (1 << WEEK_OF_MONTH); 1011 final static int DAY_OF_MONTH_MASK = (1 << DAY_OF_MONTH); 1012 final static int DATE_MASK = DAY_OF_MONTH_MASK; 1013 final static int DAY_OF_YEAR_MASK = (1 << DAY_OF_YEAR); 1014 final static int DAY_OF_WEEK_MASK = (1 << DAY_OF_WEEK); 1015 final static int DAY_OF_WEEK_IN_MONTH_MASK = (1 << DAY_OF_WEEK_IN_MONTH); 1016 final static int AM_PM_MASK = (1 << AM_PM); 1017 final static int HOUR_MASK = (1 << HOUR); 1018 final static int HOUR_OF_DAY_MASK = (1 << HOUR_OF_DAY); 1019 final static int MINUTE_MASK = (1 << MINUTE); 1020 final static int SECOND_MASK = (1 << SECOND); 1021 final static int MILLISECOND_MASK = (1 << MILLISECOND); 1022 final static int ZONE_OFFSET_MASK = (1 << ZONE_OFFSET); 1023 final static int DST_OFFSET_MASK = (1 << DST_OFFSET); 1024 1025 /** 1026 * {@code Calendar.Builder} is used for creating a {@code Calendar} from 1027 * various date-time parameters. 1028 * 1029 * <p>There are two ways to set a {@code Calendar} to a date-time value. One 1030 * is to set the instant parameter to a millisecond offset from the <a 1031 * href="Calendar.html#Epoch">Epoch</a>. The other is to set individual 1032 * field parameters, such as {@link Calendar#YEAR YEAR}, to their desired 1033 * values. These two ways can't be mixed. Trying to set both the instant and 1034 * individual fields will cause an {@link IllegalStateException} to be 1035 * thrown. However, it is permitted to override previous values of the 1036 * instant or field parameters. 1037 * 1038 * <p>If no enough field parameters are given for determining date and/or 1039 * time, calendar specific default values are used when building a 1040 * {@code Calendar}. For example, if the {@link Calendar#YEAR YEAR} value 1041 * isn't given for the Gregorian calendar, 1970 will be used. If there are 1042 * any conflicts among field parameters, the <a 1043 * href="Calendar.html#resolution"> resolution rules</a> are applied. 1044 * Therefore, the order of field setting matters. 1045 * 1046 * <p>In addition to the date-time parameters, 1047 * the {@linkplain #setLocale(Locale) locale}, 1048 * {@linkplain #setTimeZone(TimeZone) time zone}, 1049 * {@linkplain #setWeekDefinition(int, int) week definition}, and 1050 * {@linkplain #setLenient(boolean) leniency mode} parameters can be set. 1051 * 1052 * <p><b>Examples</b> 1053 * <p>The following are sample usages. Sample code assumes that the 1054 * {@code Calendar} constants are statically imported. 1055 * 1056 * <p>The following code produces a {@code Calendar} with date 2012-12-31 1057 * (Gregorian) because Monday is the first day of a week with the <a 1058 * href="GregorianCalendar.html#iso8601_compatible_setting"> ISO 8601 1059 * compatible week parameters</a>. 1060 * <pre> 1061 * Calendar cal = new Calendar.Builder().setCalendarType("iso8601") 1062 * .setWeekDate(2013, 1, MONDAY).build();</pre> 1063 * <p>The following code produces a Japanese {@code Calendar} with date 1064 * 1989-01-08 (Gregorian), assuming that the default {@link Calendar#ERA ERA} 1065 * is <em>Heisei</em> that started on that day. 1066 * <pre> 1067 * Calendar cal = new Calendar.Builder().setCalendarType("japanese") 1068 * .setFields(YEAR, 1, DAY_OF_YEAR, 1).build();</pre> 1069 * 1070 * @since 1.8 1071 * @see Calendar#getInstance(TimeZone, Locale) 1072 * @see Calendar#fields 1073 */ 1074 public static class Builder { 1075 private static final int NFIELDS = FIELD_COUNT + 1; // +1 for WEEK_YEAR 1076 private static final int WEEK_YEAR = FIELD_COUNT; 1077 1078 private long instant; 1079 // Calendar.stamp[] (lower half) and Calendar.fields[] (upper half) combined 1080 private int[] fields; 1081 // Pseudo timestamp starting from MINIMUM_USER_STAMP. 1082 // (COMPUTED is used to indicate that the instant has been set.) 1083 private int nextStamp; 1084 // maxFieldIndex keeps the max index of fields which have been set. 1085 // (WEEK_YEAR is never included.) 1086 private int maxFieldIndex; 1087 private String type; 1088 private TimeZone zone; 1089 private boolean lenient = true; 1090 private Locale locale; 1091 private int firstDayOfWeek, minimalDaysInFirstWeek; 1092 1093 /** 1094 * Constructs a {@code Calendar.Builder}. 1095 */ 1096 public Builder() { 1097 } 1098 1099 /** 1100 * Sets the instant parameter to the given {@code instant} value that is 1101 * a millisecond offset from <a href="Calendar.html#Epoch">the 1102 * Epoch</a>. 1103 * 1104 * @param instant a millisecond offset from the Epoch 1105 * @return this {@code Calendar.Builder} 1106 * @throws IllegalStateException if any of the field parameters have 1107 * already been set 1108 * @see Calendar#setTime(Date) 1109 * @see Calendar#setTimeInMillis(long) 1110 * @see Calendar#time 1111 */ 1112 public Builder setInstant(long instant) { 1113 if (fields != null) { 1114 throw new IllegalStateException(); 1115 } 1116 this.instant = instant; 1117 nextStamp = COMPUTED; 1118 return this; 1119 } 1120 1121 /** 1122 * Sets the instant parameter to the {@code instant} value given by a 1123 * {@link Date}. This method is equivalent to a call to 1124 * {@link #setInstant(long) setInstant(instant.getTime())}. 1125 * 1126 * @param instant a {@code Date} representing a millisecond offset from 1127 * the Epoch 1128 * @return this {@code Calendar.Builder} 1129 * @throws NullPointerException if {@code instant} is {@code null} 1130 * @throws IllegalStateException if any of the field parameters have 1131 * already been set 1132 * @see Calendar#setTime(Date) 1133 * @see Calendar#setTimeInMillis(long) 1134 * @see Calendar#time 1135 */ 1136 public Builder setInstant(Date instant) { 1137 return setInstant(instant.getTime()); // NPE if instant == null 1138 } 1139 1140 /** 1141 * Sets the {@code field} parameter to the given {@code value}. 1142 * {@code field} is an index to the {@link Calendar#fields}, such as 1143 * {@link Calendar#DAY_OF_MONTH DAY_OF_MONTH}. Field value validation is 1144 * not performed in this method. Any out of range values are either 1145 * normalized in lenient mode or detected as an invalid value in 1146 * non-lenient mode when building a {@code Calendar}. 1147 * 1148 * @param field an index to the {@code Calendar} fields 1149 * @param value the field value 1150 * @return this {@code Calendar.Builder} 1151 * @throws IllegalArgumentException if {@code field} is invalid 1152 * @throws IllegalStateException if the instant value has already been set, 1153 * or if fields have been set too many 1154 * (approximately {@link Integer#MAX_VALUE}) times. 1155 * @see Calendar#set(int, int) 1156 */ 1157 public Builder set(int field, int value) { 1158 // Note: WEEK_YEAR can't be set with this method. 1159 if (field < 0 || field >= FIELD_COUNT) { 1160 throw new IllegalArgumentException("field is invalid"); 1161 } 1162 if (isInstantSet()) { 1163 throw new IllegalStateException("instant has been set"); 1164 } 1165 allocateFields(); 1166 internalSet(field, value); 1167 return this; 1168 } 1169 1170 /** 1171 * Sets field parameters to their values given by 1172 * {@code fieldValuePairs} that are pairs of a field and its value. 1173 * For example, 1174 * <pre> 1175 * setFeilds(Calendar.YEAR, 2013, 1176 * Calendar.MONTH, Calendar.DECEMBER, 1177 * Calendar.DAY_OF_MONTH, 23);</pre> 1178 * is equivalent to the sequence of the following 1179 * {@link #set(int, int) set} calls: 1180 * <pre> 1181 * set(Calendar.YEAR, 2013) 1182 * .set(Calendar.MONTH, Calendar.DECEMBER) 1183 * .set(Calendar.DAY_OF_MONTH, 23);</pre> 1184 * 1185 * @param fieldValuePairs field-value pairs 1186 * @return this {@code Calendar.Builder} 1187 * @throws NullPointerException if {@code fieldValuePairs} is {@code null} 1188 * @throws IllegalArgumentException if any of fields are invalid, 1189 * or if {@code fieldValuePairs.length} is an odd number. 1190 * @throws IllegalStateException if the instant value has been set, 1191 * or if fields have been set too many (approximately 1192 * {@link Integer#MAX_VALUE}) times. 1193 */ 1194 public Builder setFields(int... fieldValuePairs) { 1195 int len = fieldValuePairs.length; 1196 if ((len % 2) != 0) { 1197 throw new IllegalArgumentException(); 1198 } 1199 if (isInstantSet()) { 1200 throw new IllegalStateException("instant has been set"); 1201 } 1202 if ((nextStamp + len / 2) < 0) { 1203 throw new IllegalStateException("stamp counter overflow"); 1204 } 1205 allocateFields(); 1206 for (int i = 0; i < len; ) { 1207 int field = fieldValuePairs[i++]; 1208 // Note: WEEK_YEAR can't be set with this method. 1209 if (field < 0 || field >= FIELD_COUNT) { 1210 throw new IllegalArgumentException("field is invalid"); 1211 } 1212 internalSet(field, fieldValuePairs[i++]); 1213 } 1214 return this; 1215 } 1216 1217 /** 1218 * Sets the date field parameters to the values given by {@code year}, 1219 * {@code month}, and {@code dayOfMonth}. This method is equivalent to 1220 * a call to: 1221 * <pre> 1222 * setFields(Calendar.YEAR, year, 1223 * Calendar.MONTH, month, 1224 * Calendar.DAY_OF_MONTH, dayOfMonth);</pre> 1225 * 1226 * @param year the {@link Calendar#YEAR YEAR} value 1227 * @param month the {@link Calendar#MONTH MONTH} value 1228 * (the month numbering is <em>0-based</em>). 1229 * @param dayOfMonth the {@link Calendar#DAY_OF_MONTH DAY_OF_MONTH} value 1230 * @return this {@code Calendar.Builder} 1231 */ 1232 public Builder setDate(int year, int month, int dayOfMonth) { 1233 return setFields(YEAR, year, MONTH, month, DAY_OF_MONTH, dayOfMonth); 1234 } 1235 1236 /** 1237 * Sets the time of day field parameters to the values given by 1238 * {@code hourOfDay}, {@code minute}, and {@code second}. This method is 1239 * equivalent to a call to: 1240 * <pre> 1241 * setTimeOfDay(hourOfDay, minute, second, 0);</pre> 1242 * 1243 * @param hourOfDay the {@link Calendar#HOUR_OF_DAY HOUR_OF_DAY} value 1244 * (24-hour clock) 1245 * @param minute the {@link Calendar#MINUTE MINUTE} value 1246 * @param second the {@link Calendar#SECOND SECOND} value 1247 * @return this {@code Calendar.Builder} 1248 */ 1249 public Builder setTimeOfDay(int hourOfDay, int minute, int second) { 1250 return setTimeOfDay(hourOfDay, minute, second, 0); 1251 } 1252 1253 /** 1254 * Sets the time of day field parameters to the values given by 1255 * {@code hourOfDay}, {@code minute}, {@code second}, and 1256 * {@code millis}. This method is equivalent to a call to: 1257 * <pre> 1258 * setFields(Calendar.HOUR_OF_DAY, hourOfDay, 1259 * Calendar.MINUTE, minute, 1260 * Calendar.SECOND, second, 1261 * Calendar.MILLISECOND, millis);</pre> 1262 * 1263 * @param hourOfDay the {@link Calendar#HOUR_OF_DAY HOUR_OF_DAY} value 1264 * (24-hour clock) 1265 * @param minute the {@link Calendar#MINUTE MINUTE} value 1266 * @param second the {@link Calendar#SECOND SECOND} value 1267 * @param millis the {@link Calendar#MILLISECOND MILLISECOND} value 1268 * @return this {@code Calendar.Builder} 1269 */ 1270 public Builder setTimeOfDay(int hourOfDay, int minute, int second, int millis) { 1271 return setFields(HOUR_OF_DAY, hourOfDay, MINUTE, minute, 1272 SECOND, second, MILLISECOND, millis); 1273 } 1274 1275 /** 1276 * Sets the week-based date parameters to the values with the given 1277 * date specifiers - week year, week of year, and day of week. 1278 * 1279 * <p>If the specified calendar doesn't support week dates, the 1280 * {@link #build() build} method will throw an {@link IllegalArgumentException}. 1281 * 1282 * @param weekYear the week year 1283 * @param weekOfYear the week number based on {@code weekYear} 1284 * @param dayOfWeek the day of week value: one of the constants 1285 * for the {@link Calendar#DAY_OF_WEEK DAY_OF_WEEK} field: 1286 * {@link Calendar#SUNDAY SUNDAY}, ..., {@link Calendar#SATURDAY SATURDAY}. 1287 * @return this {@code Calendar.Builder} 1288 * @see Calendar#setWeekDate(int, int, int) 1289 * @see Calendar#isWeekDateSupported() 1290 */ 1291 public Builder setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) { 1292 allocateFields(); 1293 internalSet(WEEK_YEAR, weekYear); 1294 internalSet(WEEK_OF_YEAR, weekOfYear); 1295 internalSet(DAY_OF_WEEK, dayOfWeek); 1296 return this; 1297 } 1298 1299 /** 1300 * Sets the time zone parameter to the given {@code zone}. If no time 1301 * zone parameter is given to this {@code Caledar.Builder}, the 1302 * {@linkplain TimeZone#getDefault() default 1303 * <code>TimeZone</code>} will be used in the {@link #build() build} 1304 * method. 1305 * 1306 * @param zone the {@link TimeZone} 1307 * @return this {@code Calendar.Builder} 1308 * @throws NullPointerException if {@code zone} is {@code null} 1309 * @see Calendar#setTimeZone(TimeZone) 1310 */ 1311 public Builder setTimeZone(TimeZone zone) { 1312 if (zone == null) { 1313 throw new NullPointerException(); 1314 } 1315 this.zone = zone; 1316 return this; 1317 } 1318 1319 /** 1320 * Sets the lenient mode parameter to the value given by {@code lenient}. 1321 * If no lenient parameter is given to this {@code Calendar.Builder}, 1322 * lenient mode will be used in the {@link #build() build} method. 1323 * 1324 * @param lenient {@code true} for lenient mode; 1325 * {@code false} for non-lenient mode 1326 * @return this {@code Calendar.Builder} 1327 * @see Calendar#setLenient(boolean) 1328 */ 1329 public Builder setLenient(boolean lenient) { 1330 this.lenient = lenient; 1331 return this; 1332 } 1333 1334 /** 1335 * Sets the calendar type parameter to the given {@code type}. The 1336 * calendar type given by this method has precedence over any explicit 1337 * or implicit calendar type given by the 1338 * {@linkplain #setLocale(Locale) locale}. 1339 * 1340 * <p>In addition to the available calendar types returned by the 1341 * {@link Calendar#getAvailableCalendarTypes() Calendar.getAvailableCalendarTypes} 1342 * method, {@code "gregorian"} and {@code "iso8601"} as aliases of 1343 * {@code "gregory"} can be used with this method. 1344 * 1345 * @param type the calendar type 1346 * @return this {@code Calendar.Builder} 1347 * @throws NullPointerException if {@code type} is {@code null} 1348 * @throws IllegalArgumentException if {@code type} is unknown 1349 * @throws IllegalStateException if another calendar type has already been set 1350 * @see Calendar#getCalendarType() 1351 * @see Calendar#getAvailableCalendarTypes() 1352 */ 1353 public Builder setCalendarType(String type) { 1354 if (type.equals("gregorian")) { // NPE if type == null 1355 type = "gregory"; 1356 } 1357 if (!Calendar.getAvailableCalendarTypes().contains(type) 1358 && !type.equals("iso8601")) { 1359 throw new IllegalArgumentException("unknown calendar type: " + type); 1360 } 1361 if (this.type == null) { 1362 this.type = type; 1363 } else { 1364 if (!this.type.equals(type)) { 1365 throw new IllegalStateException("calendar type override"); 1366 } 1367 } 1368 return this; 1369 } 1370 1371 /** 1372 * Sets the locale parameter to the given {@code locale}. If no locale 1373 * is given to this {@code Calendar.Builder}, the {@linkplain 1374 * Locale#getDefault(Locale.Category) default <code>Locale</code>} 1375 * for {@link Locale.Category#FORMAT} will be used. 1376 * 1377 * <p>If no calendar type is explicitly given by a call to the 1378 * {@link #setCalendarType(String) setCalendarType} method, 1379 * the {@code Locale} value is used to determine what type of 1380 * {@code Calendar} to be built. 1381 * 1382 * <p>If no week definition parameters are explicitly given by a call to 1383 * the {@link #setWeekDefinition(int,int) setWeekDefinition} method, the 1384 * {@code Locale}'s default values are used. 1385 * 1386 * @param locale the {@link Locale} 1387 * @throws NullPointerException if {@code locale} is {@code null} 1388 * @return this {@code Calendar.Builder} 1389 * @see Calendar#getInstance(Locale) 1390 */ 1391 public Builder setLocale(Locale locale) { 1392 if (locale == null) { 1393 throw new NullPointerException(); 1394 } 1395 this.locale = locale; 1396 return this; 1397 } 1398 1399 /** 1400 * Sets the week definition parameters to the values given by 1401 * {@code firstDayOfWeek} and {@code minimalDaysInFirstWeek} that are 1402 * used to determine the <a href="Calendar.html#First_Week">first 1403 * week</a> of a year. The parameters given by this method have 1404 * precedence over the default values given by the 1405 * {@linkplain #setLocale(Locale) locale}. 1406 * 1407 * @param firstDayOfWeek the first day of a week; one of 1408 * {@link Calendar#SUNDAY} to {@link Calendar#SATURDAY} 1409 * @param minimalDaysInFirstWeek the minimal number of days in the first 1410 * week (1..7) 1411 * @return this {@code Calendar.Builder} 1412 * @throws IllegalArgumentException if {@code firstDayOfWeek} or 1413 * {@code minimalDaysInFirstWeek} is invalid 1414 * @see Calendar#getFirstDayOfWeek() 1415 * @see Calendar#getMinimalDaysInFirstWeek() 1416 */ 1417 public Builder setWeekDefinition(int firstDayOfWeek, int minimalDaysInFirstWeek) { 1418 if (!isValidWeekParameter(firstDayOfWeek) 1419 || !isValidWeekParameter(minimalDaysInFirstWeek)) { 1420 throw new IllegalArgumentException(); 1421 } 1422 this.firstDayOfWeek = firstDayOfWeek; 1423 this.minimalDaysInFirstWeek = minimalDaysInFirstWeek; 1424 return this; 1425 } 1426 1427 /** 1428 * Returns a {@code Calendar} built from the parameters set by the 1429 * setter methods. The calendar type given by the {@link #setCalendarType(String) 1430 * setCalendarType} method or the {@linkplain #setLocale(Locale) locale} is 1431 * used to determine what {@code Calendar} to be created. If no explicit 1432 * calendar type is given, the locale's default calendar is created. 1433 * 1434 * <p>If the calendar type is {@code "iso8601"}, the 1435 * {@linkplain GregorianCalendar#setGregorianChange(Date) Gregorian change date} 1436 * of a {@link GregorianCalendar} is set to {@code Date(Long.MIN_VALUE)} 1437 * to be the <em>proleptic</em> Gregorian calendar. Its week definition 1438 * parameters are also set to be <a 1439 * href="GregorianCalendar.html#iso8601_compatible_setting">compatible 1440 * with the ISO 8601 standard</a>. Note that the 1441 * {@link GregorianCalendar#getCalendarType() getCalendarType} method of 1442 * a {@code GregorianCalendar} created with {@code "iso8601"} returns 1443 * {@code "gregory"}. 1444 * 1445 * <p>The default values are used for locale and time zone if these 1446 * parameters haven't been given explicitly. 1447 * 1448 * <p>Any out of range field values are either normalized in lenient 1449 * mode or detected as an invalid value in non-lenient mode. 1450 * 1451 * @return a {@code Calendar} built with parameters of this {@code 1452 * Calendar.Builder} 1453 * @throws IllegalArgumentException if the calendar type is unknown, or 1454 * if any invalid field values are given in non-lenient mode, or 1455 * if a week date is given for the calendar type that doesn't 1456 * support week dates. 1457 * @see Calendar#getInstance(TimeZone, Locale) 1458 * @see Locale#getDefault(Locale.Category) 1459 * @see TimeZone#getDefault() 1460 */ 1461 public Calendar build() { 1462 if (locale == null) { 1463 locale = Locale.getDefault(); 1464 } 1465 if (zone == null) { 1466 zone = TimeZone.getDefault(); 1467 } 1468 Calendar cal; 1469 if (type == null) { 1470 type = locale.getUnicodeLocaleType("ca"); 1471 } 1472 if (type == null) { 1473 if (locale.getCountry() == "TH" 1474 && locale.getLanguage() == "th") { 1475 type = "buddhist"; 1476 } else { 1477 type = "gregory"; 1478 } 1479 } 1480 switch (type) { 1481 case "gregory": 1482 cal = new GregorianCalendar(zone, locale, true); 1483 break; 1484 case "iso8601": 1485 GregorianCalendar gcal = new GregorianCalendar(zone, locale, true); 1486 // make gcal a proleptic Gregorian 1487 gcal.setGregorianChange(new Date(Long.MIN_VALUE)); 1488 // and week definition to be compatible with ISO 8601 1489 setWeekDefinition(MONDAY, 4); 1490 cal = gcal; 1491 break; 1492 case "buddhist": 1493 cal = new BuddhistCalendar(zone, locale); 1494 cal.clear(); 1495 break; 1496 case "japanese": 1497 cal = new JapaneseImperialCalendar(zone, locale, true); 1498 break; 1499 default: 1500 throw new IllegalArgumentException("unknown calendar type: " + type); 1501 } 1502 cal.setLenient(lenient); 1503 if (firstDayOfWeek != 0) { 1504 cal.setFirstDayOfWeek(firstDayOfWeek); 1505 cal.setMinimalDaysInFirstWeek(minimalDaysInFirstWeek); 1506 } 1507 if (isInstantSet()) { 1508 cal.setTimeInMillis(instant); 1509 cal.complete(); 1510 return cal; 1511 } 1512 1513 if (fields != null) { 1514 boolean weekDate = isSet(WEEK_YEAR) 1515 && fields[WEEK_YEAR] > fields[YEAR]; 1516 if (weekDate && !cal.isWeekDateSupported()) { 1517 throw new IllegalArgumentException("week date is unsupported by " + type); 1518 } 1519 1520 // Set the fields from the min stamp to the max stamp so that 1521 // the fields resolution works in the Calendar. 1522 for (int stamp = MINIMUM_USER_STAMP; stamp < nextStamp; stamp++) { 1523 for (int index = 0; index <= maxFieldIndex; index++) { 1524 if (fields[index] == stamp) { 1525 cal.set(index, fields[NFIELDS + index]); 1526 break; 1527 } 1528 } 1529 } 1530 1531 if (weekDate) { 1532 int weekOfYear = isSet(WEEK_OF_YEAR) ? fields[NFIELDS + WEEK_OF_YEAR] : 1; 1533 int dayOfWeek = isSet(DAY_OF_WEEK) 1534 ? fields[NFIELDS + DAY_OF_WEEK] : cal.getFirstDayOfWeek(); 1535 cal.setWeekDate(fields[NFIELDS + WEEK_YEAR], weekOfYear, dayOfWeek); 1536 } 1537 cal.complete(); 1538 } 1539 1540 return cal; 1541 } 1542 1543 private void allocateFields() { 1544 if (fields == null) { 1545 fields = new int[NFIELDS * 2]; 1546 nextStamp = MINIMUM_USER_STAMP; 1547 maxFieldIndex = -1; 1548 } 1549 } 1550 1551 private void internalSet(int field, int value) { 1552 fields[field] = nextStamp++; 1553 if (nextStamp < 0) { 1554 throw new IllegalStateException("stamp counter overflow"); 1555 } 1556 fields[NFIELDS + field] = value; 1557 if (field > maxFieldIndex && field < WEEK_YEAR) { 1558 maxFieldIndex = field; 1559 } 1560 } 1561 1562 private boolean isInstantSet() { 1563 return nextStamp == COMPUTED; 1564 } 1565 1566 private boolean isSet(int index) { 1567 return fields != null && fields[index] > UNSET; 1568 } 1569 1570 private boolean isValidWeekParameter(int value) { 1571 return value > 0 && value <= 7; 1572 } 1573 } 1574 1575 /** 1576 * Constructs a Calendar with the default time zone 1577 * and the default {@link java.util.Locale.Category#FORMAT FORMAT} 1578 * locale. 1579 * @see TimeZone#getDefault 1580 */ 1581 protected Calendar() 1582 { 1583 this(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT)); 1584 sharedZone = true; 1585 } 1586 1587 /** 1588 * Constructs a calendar with the specified time zone and locale. 1589 * 1590 * @param zone the time zone to use 1591 * @param aLocale the locale for the week data 1592 */ 1593 protected Calendar(TimeZone zone, Locale aLocale) 1594 { 1595 fields = new int[FIELD_COUNT]; 1596 isSet = new boolean[FIELD_COUNT]; 1597 stamp = new int[FIELD_COUNT]; 1598 1599 this.zone = zone; 1600 setWeekCountData(aLocale); 1601 } 1602 1603 /** 1604 * Gets a calendar using the default time zone and locale. The 1605 * <code>Calendar</code> returned is based on the current time 1606 * in the default time zone with the default 1607 * {@link Locale.Category#FORMAT FORMAT} locale. 1608 * 1609 * @return a Calendar. 1610 */ 1611 public static Calendar getInstance() 1612 { 1613 return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT)); 1614 } 1615 1616 /** 1617 * Gets a calendar using the specified time zone and default locale. 1618 * The <code>Calendar</code> returned is based on the current time 1619 * in the given time zone with the default 1620 * {@link Locale.Category#FORMAT FORMAT} locale. 1621 * 1622 * @param zone the time zone to use 1623 * @return a Calendar. 1624 */ 1625 public static Calendar getInstance(TimeZone zone) 1626 { 1627 return createCalendar(zone, Locale.getDefault(Locale.Category.FORMAT)); 1628 } 1629 1630 /** 1631 * Gets a calendar using the default time zone and specified locale. 1632 * The <code>Calendar</code> returned is based on the current time 1633 * in the default time zone with the given locale. 1634 * 1635 * @param aLocale the locale for the week data 1636 * @return a Calendar. 1637 */ 1638 public static Calendar getInstance(Locale aLocale) 1639 { 1640 return createCalendar(TimeZone.getDefault(), aLocale); 1641 } 1642 1643 /** 1644 * Gets a calendar with the specified time zone and locale. 1645 * The <code>Calendar</code> returned is based on the current time 1646 * in the given time zone with the given locale. 1647 * 1648 * @param zone the time zone to use 1649 * @param aLocale the locale for the week data 1650 * @return a Calendar. 1651 */ 1652 public static Calendar getInstance(TimeZone zone, 1653 Locale aLocale) 1654 { 1655 return createCalendar(zone, aLocale); 1656 } 1657 1658 private static Calendar createCalendar(TimeZone zone, 1659 Locale aLocale) 1660 { 1661 CalendarProvider provider = 1662 LocaleProviderAdapter.getAdapter(CalendarProvider.class, aLocale) 1663 .getCalendarProvider(); 1664 if (provider != null) { 1665 try { 1666 return provider.getInstance(zone, aLocale); 1667 } catch (IllegalArgumentException iae) { 1668 // fall back to the default instantiation 1669 } 1670 } 1671 1672 Calendar cal = null; 1673 1674 if (aLocale.hasExtensions()) { 1675 String caltype = aLocale.getUnicodeLocaleType("ca"); 1676 if (caltype != null) { 1677 switch (caltype) { 1678 case "buddhist": 1679 cal = new BuddhistCalendar(zone, aLocale); 1680 break; 1681 case "japanese": 1682 cal = new JapaneseImperialCalendar(zone, aLocale); 1683 break; 1684 case "gregory": 1685 cal = new GregorianCalendar(zone, aLocale); 1686 break; 1687 } 1688 } 1689 } 1690 if (cal == null) { 1691 // If no known calendar type is explicitly specified, 1692 // perform the traditional way to create a Calendar: 1693 // create a BuddhistCalendar for th_TH locale, 1694 // a JapaneseImperialCalendar for ja_JP_JP locale, or 1695 // a GregorianCalendar for any other locales. 1696 // NOTE: The language, country and variant strings are interned. 1697 if (aLocale.getLanguage() == "th" && aLocale.getCountry() == "TH") { 1698 cal = new BuddhistCalendar(zone, aLocale); 1699 } else if (aLocale.getVariant() == "JP" && aLocale.getLanguage() == "ja" 1700 && aLocale.getCountry() == "JP") { 1701 cal = new JapaneseImperialCalendar(zone, aLocale); 1702 } else { 1703 cal = new GregorianCalendar(zone, aLocale); 1704 } 1705 } 1706 return cal; 1707 } 1708 1709 /** 1710 * Returns an array of all locales for which the <code>getInstance</code> 1711 * methods of this class can return localized instances. 1712 * The array returned must contain at least a <code>Locale</code> 1713 * instance equal to {@link java.util.Locale#US Locale.US}. 1714 * 1715 * @return An array of locales for which localized 1716 * <code>Calendar</code> instances are available. 1717 */ 1718 public static synchronized Locale[] getAvailableLocales() 1719 { 1720 return DateFormat.getAvailableLocales(); 1721 } 1722 1723 /** 1724 * Converts the current calendar field values in {@link #fields fields[]} 1725 * to the millisecond time value 1726 * {@link #time}. 1727 * 1728 * @see #complete() 1729 * @see #computeFields() 1730 */ 1731 protected abstract void computeTime(); 1732 1733 /** 1734 * Converts the current millisecond time value {@link #time} 1735 * to calendar field values in {@link #fields fields[]}. 1736 * This allows you to sync up the calendar field values with 1737 * a new time that is set for the calendar. The time is <em>not</em> 1738 * recomputed first; to recompute the time, then the fields, call the 1739 * {@link #complete()} method. 1740 * 1741 * @see #computeTime() 1742 */ 1743 protected abstract void computeFields(); 1744 1745 /** 1746 * Returns a <code>Date</code> object representing this 1747 * <code>Calendar</code>'s time value (millisecond offset from the <a 1748 * href="#Epoch">Epoch</a>"). 1749 * 1750 * @return a <code>Date</code> representing the time value. 1751 * @see #setTime(Date) 1752 * @see #getTimeInMillis() 1753 */ 1754 public final Date getTime() { 1755 return new Date(getTimeInMillis()); 1756 } 1757 1758 /** 1759 * Sets this Calendar's time with the given <code>Date</code>. 1760 * <p> 1761 * Note: Calling <code>setTime()</code> with 1762 * <code>Date(Long.MAX_VALUE)</code> or <code>Date(Long.MIN_VALUE)</code> 1763 * may yield incorrect field values from <code>get()</code>. 1764 * 1765 * @param date the given Date. 1766 * @see #getTime() 1767 * @see #setTimeInMillis(long) 1768 */ 1769 public final void setTime(Date date) { 1770 setTimeInMillis(date.getTime()); 1771 } 1772 1773 /** 1774 * Returns this Calendar's time value in milliseconds. 1775 * 1776 * @return the current time as UTC milliseconds from the epoch. 1777 * @see #getTime() 1778 * @see #setTimeInMillis(long) 1779 */ 1780 public long getTimeInMillis() { 1781 if (!isTimeSet) { 1782 updateTime(); 1783 } 1784 return time; 1785 } 1786 1787 /** 1788 * Sets this Calendar's current time from the given long value. 1789 * 1790 * @param millis the new time in UTC milliseconds from the epoch. 1791 * @see #setTime(Date) 1792 * @see #getTimeInMillis() 1793 */ 1794 public void setTimeInMillis(long millis) { 1795 // If we don't need to recalculate the calendar field values, 1796 // do nothing. 1797 if (time == millis && isTimeSet && areFieldsSet && areAllFieldsSet 1798 && (zone instanceof ZoneInfo) && !((ZoneInfo)zone).isDirty()) { 1799 return; 1800 } 1801 time = millis; 1802 isTimeSet = true; 1803 areFieldsSet = false; 1804 computeFields(); 1805 areAllFieldsSet = areFieldsSet = true; 1806 } 1807 1808 /** 1809 * Returns the value of the given calendar field. In lenient mode, 1810 * all calendar fields are normalized. In non-lenient mode, all 1811 * calendar fields are validated and this method throws an 1812 * exception if any calendar fields have out-of-range values. The 1813 * normalization and validation are handled by the 1814 * {@link #complete()} method, which process is calendar 1815 * system dependent. 1816 * 1817 * @param field the given calendar field. 1818 * @return the value for the given calendar field. 1819 * @throws ArrayIndexOutOfBoundsException if the specified field is out of range 1820 * (<code>field < 0 || field >= FIELD_COUNT</code>). 1821 * @see #set(int,int) 1822 * @see #complete() 1823 */ 1824 public int get(int field) 1825 { 1826 complete(); 1827 return internalGet(field); 1828 } 1829 1830 /** 1831 * Returns the value of the given calendar field. This method does 1832 * not involve normalization or validation of the field value. 1833 * 1834 * @param field the given calendar field. 1835 * @return the value for the given calendar field. 1836 * @see #get(int) 1837 */ 1838 protected final int internalGet(int field) 1839 { 1840 return fields[field]; 1841 } 1842 1843 /** 1844 * Sets the value of the given calendar field. This method does 1845 * not affect any setting state of the field in this 1846 * <code>Calendar</code> instance. 1847 * 1848 * @throws IndexOutOfBoundsException if the specified field is out of range 1849 * (<code>field < 0 || field >= FIELD_COUNT</code>). 1850 * @see #areFieldsSet 1851 * @see #isTimeSet 1852 * @see #areAllFieldsSet 1853 * @see #set(int,int) 1854 */ 1855 final void internalSet(int field, int value) 1856 { 1857 fields[field] = value; 1858 } 1859 1860 /** 1861 * Sets the given calendar field to the given value. The value is not 1862 * interpreted by this method regardless of the leniency mode. 1863 * 1864 * @param field the given calendar field. 1865 * @param value the value to be set for the given calendar field. 1866 * @throws ArrayIndexOutOfBoundsException if the specified field is out of range 1867 * (<code>field < 0 || field >= FIELD_COUNT</code>). 1868 * in non-lenient mode. 1869 * @see #set(int,int,int) 1870 * @see #set(int,int,int,int,int) 1871 * @see #set(int,int,int,int,int,int) 1872 * @see #get(int) 1873 */ 1874 public void set(int field, int value) 1875 { 1876 // If the fields are partially normalized, calculate all the 1877 // fields before changing any fields. 1878 if (areFieldsSet && !areAllFieldsSet) { 1879 computeFields(); 1880 } 1881 internalSet(field, value); 1882 isTimeSet = false; 1883 areFieldsSet = false; 1884 isSet[field] = true; 1885 stamp[field] = nextStamp++; 1886 if (nextStamp == Integer.MAX_VALUE) { 1887 adjustStamp(); 1888 } 1889 } 1890 1891 /** 1892 * Sets the values for the calendar fields <code>YEAR</code>, 1893 * <code>MONTH</code>, and <code>DAY_OF_MONTH</code>. 1894 * Previous values of other calendar fields are retained. If this is not desired, 1895 * call {@link #clear()} first. 1896 * 1897 * @param year the value used to set the <code>YEAR</code> calendar field. 1898 * @param month the value used to set the <code>MONTH</code> calendar field. 1899 * Month value is 0-based. e.g., 0 for January. 1900 * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field. 1901 * @see #set(int,int) 1902 * @see #set(int,int,int,int,int) 1903 * @see #set(int,int,int,int,int,int) 1904 */ 1905 public final void set(int year, int month, int date) 1906 { 1907 set(YEAR, year); 1908 set(MONTH, month); 1909 set(DATE, date); 1910 } 1911 1912 /** 1913 * Sets the values for the calendar fields <code>YEAR</code>, 1914 * <code>MONTH</code>, <code>DAY_OF_MONTH</code>, 1915 * <code>HOUR_OF_DAY</code>, and <code>MINUTE</code>. 1916 * Previous values of other fields are retained. If this is not desired, 1917 * call {@link #clear()} first. 1918 * 1919 * @param year the value used to set the <code>YEAR</code> calendar field. 1920 * @param month the value used to set the <code>MONTH</code> calendar field. 1921 * Month value is 0-based. e.g., 0 for January. 1922 * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field. 1923 * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field. 1924 * @param minute the value used to set the <code>MINUTE</code> calendar field. 1925 * @see #set(int,int) 1926 * @see #set(int,int,int) 1927 * @see #set(int,int,int,int,int,int) 1928 */ 1929 public final void set(int year, int month, int date, int hourOfDay, int minute) 1930 { 1931 set(YEAR, year); 1932 set(MONTH, month); 1933 set(DATE, date); 1934 set(HOUR_OF_DAY, hourOfDay); 1935 set(MINUTE, minute); 1936 } 1937 1938 /** 1939 * Sets the values for the fields <code>YEAR</code>, <code>MONTH</code>, 1940 * <code>DAY_OF_MONTH</code>, <code>HOUR</code>, <code>MINUTE</code>, and 1941 * <code>SECOND</code>. 1942 * Previous values of other fields are retained. If this is not desired, 1943 * call {@link #clear()} first. 1944 * 1945 * @param year the value used to set the <code>YEAR</code> calendar field. 1946 * @param month the value used to set the <code>MONTH</code> calendar field. 1947 * Month value is 0-based. e.g., 0 for January. 1948 * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field. 1949 * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field. 1950 * @param minute the value used to set the <code>MINUTE</code> calendar field. 1951 * @param second the value used to set the <code>SECOND</code> calendar field. 1952 * @see #set(int,int) 1953 * @see #set(int,int,int) 1954 * @see #set(int,int,int,int,int) 1955 */ 1956 public final void set(int year, int month, int date, int hourOfDay, int minute, 1957 int second) 1958 { 1959 set(YEAR, year); 1960 set(MONTH, month); 1961 set(DATE, date); 1962 set(HOUR_OF_DAY, hourOfDay); 1963 set(MINUTE, minute); 1964 set(SECOND, second); 1965 } 1966 1967 /** 1968 * Sets all the calendar field values and the time value 1969 * (millisecond offset from the <a href="#Epoch">Epoch</a>) of 1970 * this <code>Calendar</code> undefined. This means that {@link 1971 * #isSet(int) isSet()} will return <code>false</code> for all the 1972 * calendar fields, and the date and time calculations will treat 1973 * the fields as if they had never been set. A 1974 * <code>Calendar</code> implementation class may use its specific 1975 * default field values for date/time calculations. For example, 1976 * <code>GregorianCalendar</code> uses 1970 if the 1977 * <code>YEAR</code> field value is undefined. 1978 * 1979 * @see #clear(int) 1980 */ 1981 public final void clear() 1982 { 1983 for (int i = 0; i < fields.length; ) { 1984 stamp[i] = fields[i] = 0; // UNSET == 0 1985 isSet[i++] = false; 1986 } 1987 areAllFieldsSet = areFieldsSet = false; 1988 isTimeSet = false; 1989 } 1990 1991 /** 1992 * Sets the given calendar field value and the time value 1993 * (millisecond offset from the <a href="#Epoch">Epoch</a>) of 1994 * this <code>Calendar</code> undefined. This means that {@link 1995 * #isSet(int) isSet(field)} will return <code>false</code>, and 1996 * the date and time calculations will treat the field as if it 1997 * had never been set. A <code>Calendar</code> implementation 1998 * class may use the field's specific default value for date and 1999 * time calculations. 2000 * 2001 * <p>The {@link #HOUR_OF_DAY}, {@link #HOUR} and {@link #AM_PM} 2002 * fields are handled independently and the <a 2003 * href="#time_resolution">the resolution rule for the time of 2004 * day</a> is applied. Clearing one of the fields doesn't reset 2005 * the hour of day value of this <code>Calendar</code>. Use {@link 2006 * #set(int,int) set(Calendar.HOUR_OF_DAY, 0)} to reset the hour 2007 * value. 2008 * 2009 * @param field the calendar field to be cleared. 2010 * @see #clear() 2011 */ 2012 public final void clear(int field) 2013 { 2014 fields[field] = 0; 2015 stamp[field] = UNSET; 2016 isSet[field] = false; 2017 2018 areAllFieldsSet = areFieldsSet = false; 2019 isTimeSet = false; 2020 } 2021 2022 /** 2023 * Determines if the given calendar field has a value set, 2024 * including cases that the value has been set by internal fields 2025 * calculations triggered by a <code>get</code> method call. 2026 * 2027 * @return <code>true</code> if the given calendar field has a value set; 2028 * <code>false</code> otherwise. 2029 */ 2030 public final boolean isSet(int field) 2031 { 2032 return stamp[field] != UNSET; 2033 } 2034 2035 /** 2036 * Returns the string representation of the calendar 2037 * <code>field</code> value in the given <code>style</code> and 2038 * <code>locale</code>. If no string representation is 2039 * applicable, <code>null</code> is returned. This method calls 2040 * {@link Calendar#get(int) get(field)} to get the calendar 2041 * <code>field</code> value if the string representation is 2042 * applicable to the given calendar <code>field</code>. 2043 * 2044 * <p>For example, if this <code>Calendar</code> is a 2045 * <code>GregorianCalendar</code> and its date is 2005-01-01, then 2046 * the string representation of the {@link #MONTH} field would be 2047 * "January" in the long style in an English locale or "Jan" in 2048 * the short style. However, no string representation would be 2049 * available for the {@link #DAY_OF_MONTH} field, and this method 2050 * would return <code>null</code>. 2051 * 2052 * <p>The default implementation supports the calendar fields for 2053 * which a {@link DateFormatSymbols} has names in the given 2054 * <code>locale</code>. 2055 * 2056 * @param field 2057 * the calendar field for which the string representation 2058 * is returned 2059 * @param style 2060 * the style applied to the string representation; one of {@link 2061 * #SHORT_FORMAT} ({@link #SHORT}), {@link #SHORT_STANDALONE}, 2062 * {@link #LONG_FORMAT} ({@link #LONG}), {@link #LONG_STANDALONE}, 2063 * {@link #NARROW_FORMAT}, or {@link #NARROW_STANDALONE}. 2064 * @param locale 2065 * the locale for the string representation 2066 * (any calendar types specified by {@code locale} are ignored) 2067 * @return the string representation of the given 2068 * {@code field} in the given {@code style}, or 2069 * {@code null} if no string representation is 2070 * applicable. 2071 * @exception IllegalArgumentException 2072 * if {@code field} or {@code style} is invalid, 2073 * or if this {@code Calendar} is non-lenient and any 2074 * of the calendar fields have invalid values 2075 * @exception NullPointerException 2076 * if {@code locale} is null 2077 * @since 1.6 2078 */ 2079 public String getDisplayName(int field, int style, Locale locale) { 2080 if (!checkDisplayNameParams(field, style, SHORT, NARROW_FORMAT, locale, 2081 ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) { 2082 return null; 2083 } 2084 2085 // the standalone and narrow styles are supported only through CalendarDataProviders. 2086 if (isStandaloneStyle(style) || isNarrowStyle(style)) { 2087 return CalendarDataUtility.retrieveFieldValueName(getCalendarType(), 2088 field, get(field), 2089 style, locale); 2090 } 2091 2092 DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale); 2093 String[] strings = getFieldStrings(field, style, symbols); 2094 if (strings != null) { 2095 int fieldValue = get(field); 2096 if (fieldValue < strings.length) { 2097 return strings[fieldValue]; 2098 } 2099 } 2100 return null; 2101 } 2102 2103 /** 2104 * Returns a {@code Map} containing all names of the calendar 2105 * {@code field} in the given {@code style} and 2106 * {@code locale} and their corresponding field values. For 2107 * example, if this {@code Calendar} is a {@link 2108 * GregorianCalendar}, the returned map would contain "Jan" to 2109 * {@link #JANUARY}, "Feb" to {@link #FEBRUARY}, and so on, in the 2110 * {@linkplain #SHORT short} style in an English locale. 2111 * 2112 * <p>Narrow names may not be unique due to use of single characters, 2113 * such as "S" for Sunday and Saturday. In that case narrow names are not 2114 * included in the returned {@code Map}. 2115 * 2116 * <p>The values of other calendar fields may be taken into 2117 * account to determine a set of display names. For example, if 2118 * this {@code Calendar} is a lunisolar calendar system and 2119 * the year value given by the {@link #YEAR} field has a leap 2120 * month, this method would return month names containing the leap 2121 * month name, and month names are mapped to their values specific 2122 * for the year. 2123 * 2124 * <p>The default implementation supports display names contained in 2125 * a {@link DateFormatSymbols}. For example, if {@code field} 2126 * is {@link #MONTH} and {@code style} is {@link 2127 * #ALL_STYLES}, this method returns a {@code Map} containing 2128 * all strings returned by {@link DateFormatSymbols#getShortMonths()} 2129 * and {@link DateFormatSymbols#getMonths()}. 2130 * 2131 * @param field 2132 * the calendar field for which the display names are returned 2133 * @param style 2134 * the style applied to the string representation; one of {@link 2135 * #SHORT_FORMAT} ({@link #SHORT}), {@link #SHORT_STANDALONE}, 2136 * {@link #LONG_FORMAT} ({@link #LONG}), {@link #LONG_STANDALONE}, 2137 * {@link #NARROW_FORMAT}, or {@link #NARROW_STANDALONE} 2138 * @param locale 2139 * the locale for the display names 2140 * @return a {@code Map} containing all display names in 2141 * {@code style} and {@code locale} and their 2142 * field values, or {@code null} if no display names 2143 * are defined for {@code field} 2144 * @exception IllegalArgumentException 2145 * if {@code field} or {@code style} is invalid, 2146 * or if this {@code Calendar} is non-lenient and any 2147 * of the calendar fields have invalid values 2148 * @exception NullPointerException 2149 * if {@code locale} is null 2150 * @since 1.6 2151 */ 2152 public Map<String, Integer> getDisplayNames(int field, int style, Locale locale) { 2153 if (!checkDisplayNameParams(field, style, ALL_STYLES, NARROW_FORMAT, locale, 2154 ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) { 2155 return null; 2156 } 2157 if (style == ALL_STYLES || isStandaloneStyle(style)) { 2158 return CalendarDataUtility.retrieveFieldValueNames(getCalendarType(), field, style, locale); 2159 } 2160 // SHORT, LONG, or NARROW 2161 return getDisplayNamesImpl(field, style, locale); 2162 } 2163 2164 private Map<String,Integer> getDisplayNamesImpl(int field, int style, Locale locale) { 2165 DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale); 2166 String[] strings = getFieldStrings(field, style, symbols); 2167 if (strings != null) { 2168 Map<String,Integer> names = new HashMap<>(); 2169 for (int i = 0; i < strings.length; i++) { 2170 if (strings[i].length() == 0) { 2171 continue; 2172 } 2173 names.put(strings[i], i); 2174 } 2175 return names; 2176 } 2177 return null; 2178 } 2179 2180 boolean checkDisplayNameParams(int field, int style, int minStyle, int maxStyle, 2181 Locale locale, int fieldMask) { 2182 int baseStyle = getBaseStyle(style); // Ignore the standalone mask 2183 if (field < 0 || field >= fields.length || 2184 baseStyle < minStyle || baseStyle > maxStyle) { 2185 throw new IllegalArgumentException(); 2186 } 2187 if (locale == null) { 2188 throw new NullPointerException(); 2189 } 2190 return isFieldSet(fieldMask, field); 2191 } 2192 2193 private String[] getFieldStrings(int field, int style, DateFormatSymbols symbols) { 2194 int baseStyle = getBaseStyle(style); // ignore the standalone mask 2195 2196 // DateFormatSymbols doesn't support any narrow names. 2197 if (baseStyle == NARROW_FORMAT) { 2198 return null; 2199 } 2200 2201 String[] strings = null; 2202 switch (field) { 2203 case ERA: 2204 strings = symbols.getEras(); 2205 break; 2206 2207 case MONTH: 2208 strings = (baseStyle == LONG) ? symbols.getMonths() : symbols.getShortMonths(); 2209 break; 2210 2211 case DAY_OF_WEEK: 2212 strings = (baseStyle == LONG) ? symbols.getWeekdays() : symbols.getShortWeekdays(); 2213 break; 2214 2215 case AM_PM: 2216 strings = symbols.getAmPmStrings(); 2217 break; 2218 } 2219 return strings; 2220 } 2221 2222 /** 2223 * Fills in any unset fields in the calendar fields. First, the {@link 2224 * #computeTime()} method is called if the time value (millisecond offset 2225 * from the <a href="#Epoch">Epoch</a>) has not been calculated from 2226 * calendar field values. Then, the {@link #computeFields()} method is 2227 * called to calculate all calendar field values. 2228 */ 2229 protected void complete() 2230 { 2231 if (!isTimeSet) { 2232 updateTime(); 2233 } 2234 if (!areFieldsSet || !areAllFieldsSet) { 2235 computeFields(); // fills in unset fields 2236 areAllFieldsSet = areFieldsSet = true; 2237 } 2238 } 2239 2240 /** 2241 * Returns whether the value of the specified calendar field has been set 2242 * externally by calling one of the setter methods rather than by the 2243 * internal time calculation. 2244 * 2245 * @return <code>true</code> if the field has been set externally, 2246 * <code>false</code> otherwise. 2247 * @exception IndexOutOfBoundsException if the specified 2248 * <code>field</code> is out of range 2249 * (<code>field < 0 || field >= FIELD_COUNT</code>). 2250 * @see #selectFields() 2251 * @see #setFieldsComputed(int) 2252 */ 2253 final boolean isExternallySet(int field) { 2254 return stamp[field] >= MINIMUM_USER_STAMP; 2255 } 2256 2257 /** 2258 * Returns a field mask (bit mask) indicating all calendar fields that 2259 * have the state of externally or internally set. 2260 * 2261 * @return a bit mask indicating set state fields 2262 */ 2263 final int getSetStateFields() { 2264 int mask = 0; 2265 for (int i = 0; i < fields.length; i++) { 2266 if (stamp[i] != UNSET) { 2267 mask |= 1 << i; 2268 } 2269 } 2270 return mask; 2271 } 2272 2273 /** 2274 * Sets the state of the specified calendar fields to 2275 * <em>computed</em>. This state means that the specified calendar fields 2276 * have valid values that have been set by internal time calculation 2277 * rather than by calling one of the setter methods. 2278 * 2279 * @param fieldMask the field to be marked as computed. 2280 * @exception IndexOutOfBoundsException if the specified 2281 * <code>field</code> is out of range 2282 * (<code>field < 0 || field >= FIELD_COUNT</code>). 2283 * @see #isExternallySet(int) 2284 * @see #selectFields() 2285 */ 2286 final void setFieldsComputed(int fieldMask) { 2287 if (fieldMask == ALL_FIELDS) { 2288 for (int i = 0; i < fields.length; i++) { 2289 stamp[i] = COMPUTED; 2290 isSet[i] = true; 2291 } 2292 areFieldsSet = areAllFieldsSet = true; 2293 } else { 2294 for (int i = 0; i < fields.length; i++) { 2295 if ((fieldMask & 1) == 1) { 2296 stamp[i] = COMPUTED; 2297 isSet[i] = true; 2298 } else { 2299 if (areAllFieldsSet && !isSet[i]) { 2300 areAllFieldsSet = false; 2301 } 2302 } 2303 fieldMask >>>= 1; 2304 } 2305 } 2306 } 2307 2308 /** 2309 * Sets the state of the calendar fields that are <em>not</em> specified 2310 * by <code>fieldMask</code> to <em>unset</em>. If <code>fieldMask</code> 2311 * specifies all the calendar fields, then the state of this 2312 * <code>Calendar</code> becomes that all the calendar fields are in sync 2313 * with the time value (millisecond offset from the Epoch). 2314 * 2315 * @param fieldMask the field mask indicating which calendar fields are in 2316 * sync with the time value. 2317 * @exception IndexOutOfBoundsException if the specified 2318 * <code>field</code> is out of range 2319 * (<code>field < 0 || field >= FIELD_COUNT</code>). 2320 * @see #isExternallySet(int) 2321 * @see #selectFields() 2322 */ 2323 final void setFieldsNormalized(int fieldMask) { 2324 if (fieldMask != ALL_FIELDS) { 2325 for (int i = 0; i < fields.length; i++) { 2326 if ((fieldMask & 1) == 0) { 2327 stamp[i] = fields[i] = 0; // UNSET == 0 2328 isSet[i] = false; 2329 } 2330 fieldMask >>= 1; 2331 } 2332 } 2333 2334 // Some or all of the fields are in sync with the 2335 // milliseconds, but the stamp values are not normalized yet. 2336 areFieldsSet = true; 2337 areAllFieldsSet = false; 2338 } 2339 2340 /** 2341 * Returns whether the calendar fields are partially in sync with the time 2342 * value or fully in sync but not stamp values are not normalized yet. 2343 */ 2344 final boolean isPartiallyNormalized() { 2345 return areFieldsSet && !areAllFieldsSet; 2346 } 2347 2348 /** 2349 * Returns whether the calendar fields are fully in sync with the time 2350 * value. 2351 */ 2352 final boolean isFullyNormalized() { 2353 return areFieldsSet && areAllFieldsSet; 2354 } 2355 2356 /** 2357 * Marks this Calendar as not sync'd. 2358 */ 2359 final void setUnnormalized() { 2360 areFieldsSet = areAllFieldsSet = false; 2361 } 2362 2363 /** 2364 * Returns whether the specified <code>field</code> is on in the 2365 * <code>fieldMask</code>. 2366 */ 2367 static boolean isFieldSet(int fieldMask, int field) { 2368 return (fieldMask & (1 << field)) != 0; 2369 } 2370 2371 /** 2372 * Returns a field mask indicating which calendar field values 2373 * to be used to calculate the time value. The calendar fields are 2374 * returned as a bit mask, each bit of which corresponds to a field, i.e., 2375 * the mask value of <code>field</code> is <code>(1 << 2376 * field)</code>. For example, 0x26 represents the <code>YEAR</code>, 2377 * <code>MONTH</code>, and <code>DAY_OF_MONTH</code> fields (i.e., 0x26 is 2378 * equal to 2379 * <code>(1<<YEAR)|(1<<MONTH)|(1<<DAY_OF_MONTH))</code>. 2380 * 2381 * <p>This method supports the calendar fields resolution as described in 2382 * the class description. If the bit mask for a given field is on and its 2383 * field has not been set (i.e., <code>isSet(field)</code> is 2384 * <code>false</code>), then the default value of the field has to be 2385 * used, which case means that the field has been selected because the 2386 * selected combination involves the field. 2387 * 2388 * @return a bit mask of selected fields 2389 * @see #isExternallySet(int) 2390 */ 2391 final int selectFields() { 2392 // This implementation has been taken from the GregorianCalendar class. 2393 2394 // The YEAR field must always be used regardless of its SET 2395 // state because YEAR is a mandatory field to determine the date 2396 // and the default value (EPOCH_YEAR) may change through the 2397 // normalization process. 2398 int fieldMask = YEAR_MASK; 2399 2400 if (stamp[ERA] != UNSET) { 2401 fieldMask |= ERA_MASK; 2402 } 2403 // Find the most recent group of fields specifying the day within 2404 // the year. These may be any of the following combinations: 2405 // MONTH + DAY_OF_MONTH 2406 // MONTH + WEEK_OF_MONTH + DAY_OF_WEEK 2407 // MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK 2408 // DAY_OF_YEAR 2409 // WEEK_OF_YEAR + DAY_OF_WEEK 2410 // We look for the most recent of the fields in each group to determine 2411 // the age of the group. For groups involving a week-related field such 2412 // as WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR, both the 2413 // week-related field and the DAY_OF_WEEK must be set for the group as a 2414 // whole to be considered. (See bug 4153860 - liu 7/24/98.) 2415 int dowStamp = stamp[DAY_OF_WEEK]; 2416 int monthStamp = stamp[MONTH]; 2417 int domStamp = stamp[DAY_OF_MONTH]; 2418 int womStamp = aggregateStamp(stamp[WEEK_OF_MONTH], dowStamp); 2419 int dowimStamp = aggregateStamp(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp); 2420 int doyStamp = stamp[DAY_OF_YEAR]; 2421 int woyStamp = aggregateStamp(stamp[WEEK_OF_YEAR], dowStamp); 2422 2423 int bestStamp = domStamp; 2424 if (womStamp > bestStamp) { 2425 bestStamp = womStamp; 2426 } 2427 if (dowimStamp > bestStamp) { 2428 bestStamp = dowimStamp; 2429 } 2430 if (doyStamp > bestStamp) { 2431 bestStamp = doyStamp; 2432 } 2433 if (woyStamp > bestStamp) { 2434 bestStamp = woyStamp; 2435 } 2436 2437 /* No complete combination exists. Look for WEEK_OF_MONTH, 2438 * DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR alone. Treat DAY_OF_WEEK alone 2439 * as DAY_OF_WEEK_IN_MONTH. 2440 */ 2441 if (bestStamp == UNSET) { 2442 womStamp = stamp[WEEK_OF_MONTH]; 2443 dowimStamp = Math.max(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp); 2444 woyStamp = stamp[WEEK_OF_YEAR]; 2445 bestStamp = Math.max(Math.max(womStamp, dowimStamp), woyStamp); 2446 2447 /* Treat MONTH alone or no fields at all as DAY_OF_MONTH. This may 2448 * result in bestStamp = domStamp = UNSET if no fields are set, 2449 * which indicates DAY_OF_MONTH. 2450 */ 2451 if (bestStamp == UNSET) { 2452 bestStamp = domStamp = monthStamp; 2453 } 2454 } 2455 2456 if (bestStamp == domStamp || 2457 (bestStamp == womStamp && stamp[WEEK_OF_MONTH] >= stamp[WEEK_OF_YEAR]) || 2458 (bestStamp == dowimStamp && stamp[DAY_OF_WEEK_IN_MONTH] >= stamp[WEEK_OF_YEAR])) { 2459 fieldMask |= MONTH_MASK; 2460 if (bestStamp == domStamp) { 2461 fieldMask |= DAY_OF_MONTH_MASK; 2462 } else { 2463 assert (bestStamp == womStamp || bestStamp == dowimStamp); 2464 if (dowStamp != UNSET) { 2465 fieldMask |= DAY_OF_WEEK_MASK; 2466 } 2467 if (womStamp == dowimStamp) { 2468 // When they are equal, give the priority to 2469 // WEEK_OF_MONTH for compatibility. 2470 if (stamp[WEEK_OF_MONTH] >= stamp[DAY_OF_WEEK_IN_MONTH]) { 2471 fieldMask |= WEEK_OF_MONTH_MASK; 2472 } else { 2473 fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK; 2474 } 2475 } else { 2476 if (bestStamp == womStamp) { 2477 fieldMask |= WEEK_OF_MONTH_MASK; 2478 } else { 2479 assert (bestStamp == dowimStamp); 2480 if (stamp[DAY_OF_WEEK_IN_MONTH] != UNSET) { 2481 fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK; 2482 } 2483 } 2484 } 2485 } 2486 } else { 2487 assert (bestStamp == doyStamp || bestStamp == woyStamp || 2488 bestStamp == UNSET); 2489 if (bestStamp == doyStamp) { 2490 fieldMask |= DAY_OF_YEAR_MASK; 2491 } else { 2492 assert (bestStamp == woyStamp); 2493 if (dowStamp != UNSET) { 2494 fieldMask |= DAY_OF_WEEK_MASK; 2495 } 2496 fieldMask |= WEEK_OF_YEAR_MASK; 2497 } 2498 } 2499 2500 // Find the best set of fields specifying the time of day. There 2501 // are only two possibilities here; the HOUR_OF_DAY or the 2502 // AM_PM and the HOUR. 2503 int hourOfDayStamp = stamp[HOUR_OF_DAY]; 2504 int hourStamp = aggregateStamp(stamp[HOUR], stamp[AM_PM]); 2505 bestStamp = (hourStamp > hourOfDayStamp) ? hourStamp : hourOfDayStamp; 2506 2507 // if bestStamp is still UNSET, then take HOUR or AM_PM. (See 4846659) 2508 if (bestStamp == UNSET) { 2509 bestStamp = Math.max(stamp[HOUR], stamp[AM_PM]); 2510 } 2511 2512 // Hours 2513 if (bestStamp != UNSET) { 2514 if (bestStamp == hourOfDayStamp) { 2515 fieldMask |= HOUR_OF_DAY_MASK; 2516 } else { 2517 fieldMask |= HOUR_MASK; 2518 if (stamp[AM_PM] != UNSET) { 2519 fieldMask |= AM_PM_MASK; 2520 } 2521 } 2522 } 2523 if (stamp[MINUTE] != UNSET) { 2524 fieldMask |= MINUTE_MASK; 2525 } 2526 if (stamp[SECOND] != UNSET) { 2527 fieldMask |= SECOND_MASK; 2528 } 2529 if (stamp[MILLISECOND] != UNSET) { 2530 fieldMask |= MILLISECOND_MASK; 2531 } 2532 if (stamp[ZONE_OFFSET] >= MINIMUM_USER_STAMP) { 2533 fieldMask |= ZONE_OFFSET_MASK; 2534 } 2535 if (stamp[DST_OFFSET] >= MINIMUM_USER_STAMP) { 2536 fieldMask |= DST_OFFSET_MASK; 2537 } 2538 2539 return fieldMask; 2540 } 2541 2542 int getBaseStyle(int style) { 2543 return style & ~STANDALONE_MASK; 2544 } 2545 2546 boolean isStandaloneStyle(int style) { 2547 return (style & STANDALONE_MASK) != 0; 2548 } 2549 2550 boolean isNarrowStyle(int style) { 2551 return style == NARROW_FORMAT || style == NARROW_STANDALONE; 2552 } 2553 2554 /** 2555 * Returns the pseudo-time-stamp for two fields, given their 2556 * individual pseudo-time-stamps. If either of the fields 2557 * is unset, then the aggregate is unset. Otherwise, the 2558 * aggregate is the later of the two stamps. 2559 */ 2560 private static int aggregateStamp(int stamp_a, int stamp_b) { 2561 if (stamp_a == UNSET || stamp_b == UNSET) { 2562 return UNSET; 2563 } 2564 return (stamp_a > stamp_b) ? stamp_a : stamp_b; 2565 } 2566 2567 /** 2568 * Returns an unmodifiable {@code Set} containing all calendar types 2569 * supported by {@code Calendar} in the runtime environment. The available 2570 * calendar types can be used for the <a 2571 * href="Locale.html#def_locale_extension">Unicode locale extensions</a>. 2572 * The {@code Set} returned contains at least {@code "gregory"}. The 2573 * calendar types don't include aliases, such as {@code "gregorian"} for 2574 * {@code "gregory"}. 2575 * 2576 * @return an unmodifiable {@code Set} containing all available calendar types 2577 * @since 1.8 2578 * @see #getCalendarType() 2579 * @see Calendar.Builder#setCalendarType(String) 2580 * @see Locale#getUnicodeLocaleType(String) 2581 */ 2582 public static Set<String> getAvailableCalendarTypes() { 2583 return AvailableCalendarTypes.SET; 2584 } 2585 2586 private static class AvailableCalendarTypes { 2587 private static final Set<String> SET; 2588 static { 2589 Set<String> set = new HashSet<>(3); 2590 set.add("gregory"); 2591 set.add("buddhist"); 2592 set.add("japanese"); 2593 SET = Collections.unmodifiableSet(set); 2594 } 2595 private AvailableCalendarTypes() { 2596 } 2597 } 2598 2599 /** 2600 * Returns the calendar type of this {@code Calendar}. Calendar types are 2601 * defined by the <em>Unicode Locale Data Markup Language (LDML)</em> 2602 * specification. 2603 * 2604 * <p>The default implementation of this method returns the class name of 2605 * this {@code Calendar} instance. Any subclasses that implement 2606 * LDML-defined calendar systems should override this method to return 2607 * appropriate calendar types. 2608 * 2609 * @return the LDML-defined calendar type or the class name of this 2610 * {@code Calendar} instance 2611 * @since 1.8 2612 * @see <a href="Locale.html#def_extensions">Locale extensions</a> 2613 * @see Locale.Builder#setLocale(Locale) 2614 * @see Locale.Builder#setUnicodeLocaleKeyword(String, String) 2615 */ 2616 public String getCalendarType() { 2617 return this.getClass().getName(); 2618 } 2619 2620 /** 2621 * Compares this <code>Calendar</code> to the specified 2622 * <code>Object</code>. The result is <code>true</code> if and only if 2623 * the argument is a <code>Calendar</code> object of the same calendar 2624 * system that represents the same time value (millisecond offset from the 2625 * <a href="#Epoch">Epoch</a>) under the same 2626 * <code>Calendar</code> parameters as this object. 2627 * 2628 * <p>The <code>Calendar</code> parameters are the values represented 2629 * by the <code>isLenient</code>, <code>getFirstDayOfWeek</code>, 2630 * <code>getMinimalDaysInFirstWeek</code> and <code>getTimeZone</code> 2631 * methods. If there is any difference in those parameters 2632 * between the two <code>Calendar</code>s, this method returns 2633 * <code>false</code>. 2634 * 2635 * <p>Use the {@link #compareTo(Calendar) compareTo} method to 2636 * compare only the time values. 2637 * 2638 * @param obj the object to compare with. 2639 * @return <code>true</code> if this object is equal to <code>obj</code>; 2640 * <code>false</code> otherwise. 2641 */ 2642 @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") 2643 @Override 2644 public boolean equals(Object obj) { 2645 if (this == obj) { 2646 return true; 2647 } 2648 try { 2649 Calendar that = (Calendar)obj; 2650 return compareTo(getMillisOf(that)) == 0 && 2651 lenient == that.lenient && 2652 firstDayOfWeek == that.firstDayOfWeek && 2653 minimalDaysInFirstWeek == that.minimalDaysInFirstWeek && 2654 zone.equals(that.zone); 2655 } catch (Exception e) { 2656 // Note: GregorianCalendar.computeTime throws 2657 // IllegalArgumentException if the ERA value is invalid 2658 // even it's in lenient mode. 2659 } 2660 return false; 2661 } 2662 2663 /** 2664 * Returns a hash code for this calendar. 2665 * 2666 * @return a hash code value for this object. 2667 * @since 1.2 2668 */ 2669 @Override 2670 public int hashCode() { 2671 // 'otheritems' represents the hash code for the previous versions. 2672 int otheritems = (lenient ? 1 : 0) 2673 | (firstDayOfWeek << 1) 2674 | (minimalDaysInFirstWeek << 4) 2675 | (zone.hashCode() << 7); 2676 long t = getMillisOf(this); 2677 return (int) t ^ (int)(t >> 32) ^ otheritems; 2678 } 2679 2680 /** 2681 * Returns whether this <code>Calendar</code> represents a time 2682 * before the time represented by the specified 2683 * <code>Object</code>. This method is equivalent to: 2684 * <pre><blockquote> 2685 * compareTo(when) < 0 2686 * </blockquote></pre> 2687 * if and only if <code>when</code> is a <code>Calendar</code> 2688 * instance. Otherwise, the method returns <code>false</code>. 2689 * 2690 * @param when the <code>Object</code> to be compared 2691 * @return <code>true</code> if the time of this 2692 * <code>Calendar</code> is before the time represented by 2693 * <code>when</code>; <code>false</code> otherwise. 2694 * @see #compareTo(Calendar) 2695 */ 2696 public boolean before(Object when) { 2697 return when instanceof Calendar 2698 && compareTo((Calendar)when) < 0; 2699 } 2700 2701 /** 2702 * Returns whether this <code>Calendar</code> represents a time 2703 * after the time represented by the specified 2704 * <code>Object</code>. This method is equivalent to: 2705 * <pre><blockquote> 2706 * compareTo(when) > 0 2707 * </blockquote></pre> 2708 * if and only if <code>when</code> is a <code>Calendar</code> 2709 * instance. Otherwise, the method returns <code>false</code>. 2710 * 2711 * @param when the <code>Object</code> to be compared 2712 * @return <code>true</code> if the time of this <code>Calendar</code> is 2713 * after the time represented by <code>when</code>; <code>false</code> 2714 * otherwise. 2715 * @see #compareTo(Calendar) 2716 */ 2717 public boolean after(Object when) { 2718 return when instanceof Calendar 2719 && compareTo((Calendar)when) > 0; 2720 } 2721 2722 /** 2723 * Compares the time values (millisecond offsets from the <a 2724 * href="#Epoch">Epoch</a>) represented by two 2725 * <code>Calendar</code> objects. 2726 * 2727 * @param anotherCalendar the <code>Calendar</code> to be compared. 2728 * @return the value <code>0</code> if the time represented by the argument 2729 * is equal to the time represented by this <code>Calendar</code>; a value 2730 * less than <code>0</code> if the time of this <code>Calendar</code> is 2731 * before the time represented by the argument; and a value greater than 2732 * <code>0</code> if the time of this <code>Calendar</code> is after the 2733 * time represented by the argument. 2734 * @exception NullPointerException if the specified <code>Calendar</code> is 2735 * <code>null</code>. 2736 * @exception IllegalArgumentException if the time value of the 2737 * specified <code>Calendar</code> object can't be obtained due to 2738 * any invalid calendar values. 2739 * @since 1.5 2740 */ 2741 @Override 2742 public int compareTo(Calendar anotherCalendar) { 2743 return compareTo(getMillisOf(anotherCalendar)); 2744 } 2745 2746 /** 2747 * Adds or subtracts the specified amount of time to the given calendar field, 2748 * based on the calendar's rules. For example, to subtract 5 days from 2749 * the current time of the calendar, you can achieve it by calling: 2750 * <p><code>add(Calendar.DAY_OF_MONTH, -5)</code>. 2751 * 2752 * @param field the calendar field. 2753 * @param amount the amount of date or time to be added to the field. 2754 * @see #roll(int,int) 2755 * @see #set(int,int) 2756 */ 2757 abstract public void add(int field, int amount); 2758 2759 /** 2760 * Adds or subtracts (up/down) a single unit of time on the given time 2761 * field without changing larger fields. For example, to roll the current 2762 * date up by one day, you can achieve it by calling: 2763 * <p>roll(Calendar.DATE, true). 2764 * When rolling on the year or Calendar.YEAR field, it will roll the year 2765 * value in the range between 1 and the value returned by calling 2766 * <code>getMaximum(Calendar.YEAR)</code>. 2767 * When rolling on the month or Calendar.MONTH field, other fields like 2768 * date might conflict and, need to be changed. For instance, 2769 * rolling the month on the date 01/31/96 will result in 02/29/96. 2770 * When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field, it will 2771 * roll the hour value in the range between 0 and 23, which is zero-based. 2772 * 2773 * @param field the time field. 2774 * @param up indicates if the value of the specified time field is to be 2775 * rolled up or rolled down. Use true if rolling up, false otherwise. 2776 * @see Calendar#add(int,int) 2777 * @see Calendar#set(int,int) 2778 */ 2779 abstract public void roll(int field, boolean up); 2780 2781 /** 2782 * Adds the specified (signed) amount to the specified calendar field 2783 * without changing larger fields. A negative amount means to roll 2784 * down. 2785 * 2786 * <p>NOTE: This default implementation on <code>Calendar</code> just repeatedly calls the 2787 * version of {@link #roll(int,boolean) roll()} that rolls by one unit. This may not 2788 * always do the right thing. For example, if the <code>DAY_OF_MONTH</code> field is 31, 2789 * rolling through February will leave it set to 28. The <code>GregorianCalendar</code> 2790 * version of this function takes care of this problem. Other subclasses 2791 * should also provide overrides of this function that do the right thing. 2792 * 2793 * @param field the calendar field. 2794 * @param amount the signed amount to add to the calendar <code>field</code>. 2795 * @since 1.2 2796 * @see #roll(int,boolean) 2797 * @see #add(int,int) 2798 * @see #set(int,int) 2799 */ 2800 public void roll(int field, int amount) 2801 { 2802 while (amount > 0) { 2803 roll(field, true); 2804 amount--; 2805 } 2806 while (amount < 0) { 2807 roll(field, false); 2808 amount++; 2809 } 2810 } 2811 2812 /** 2813 * Sets the time zone with the given time zone value. 2814 * 2815 * @param value the given time zone. 2816 */ 2817 public void setTimeZone(TimeZone value) 2818 { 2819 zone = value; 2820 sharedZone = false; 2821 /* Recompute the fields from the time using the new zone. This also 2822 * works if isTimeSet is false (after a call to set()). In that case 2823 * the time will be computed from the fields using the new zone, then 2824 * the fields will get recomputed from that. Consider the sequence of 2825 * calls: cal.setTimeZone(EST); cal.set(HOUR, 1); cal.setTimeZone(PST). 2826 * Is cal set to 1 o'clock EST or 1 o'clock PST? Answer: PST. More 2827 * generally, a call to setTimeZone() affects calls to set() BEFORE AND 2828 * AFTER it up to the next call to complete(). 2829 */ 2830 areAllFieldsSet = areFieldsSet = false; 2831 } 2832 2833 /** 2834 * Gets the time zone. 2835 * 2836 * @return the time zone object associated with this calendar. 2837 */ 2838 public TimeZone getTimeZone() 2839 { 2840 // If the TimeZone object is shared by other Calendar instances, then 2841 // create a clone. 2842 if (sharedZone) { 2843 zone = (TimeZone) zone.clone(); 2844 sharedZone = false; 2845 } 2846 return zone; 2847 } 2848 2849 /** 2850 * Returns the time zone (without cloning). 2851 */ 2852 TimeZone getZone() { 2853 return zone; 2854 } 2855 2856 /** 2857 * Sets the sharedZone flag to <code>shared</code>. 2858 */ 2859 void setZoneShared(boolean shared) { 2860 sharedZone = shared; 2861 } 2862 2863 /** 2864 * Specifies whether or not date/time interpretation is to be lenient. With 2865 * lenient interpretation, a date such as "February 942, 1996" will be 2866 * treated as being equivalent to the 941st day after February 1, 1996. 2867 * With strict (non-lenient) interpretation, such dates will cause an exception to be 2868 * thrown. The default is lenient. 2869 * 2870 * @param lenient <code>true</code> if the lenient mode is to be turned 2871 * on; <code>false</code> if it is to be turned off. 2872 * @see #isLenient() 2873 * @see java.text.DateFormat#setLenient 2874 */ 2875 public void setLenient(boolean lenient) 2876 { 2877 this.lenient = lenient; 2878 } 2879 2880 /** 2881 * Tells whether date/time interpretation is to be lenient. 2882 * 2883 * @return <code>true</code> if the interpretation mode of this calendar is lenient; 2884 * <code>false</code> otherwise. 2885 * @see #setLenient(boolean) 2886 */ 2887 public boolean isLenient() 2888 { 2889 return lenient; 2890 } 2891 2892 /** 2893 * Sets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S., 2894 * <code>MONDAY</code> in France. 2895 * 2896 * @param value the given first day of the week. 2897 * @see #getFirstDayOfWeek() 2898 * @see #getMinimalDaysInFirstWeek() 2899 */ 2900 public void setFirstDayOfWeek(int value) 2901 { 2902 if (firstDayOfWeek == value) { 2903 return; 2904 } 2905 firstDayOfWeek = value; 2906 invalidateWeekFields(); 2907 } 2908 2909 /** 2910 * Gets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S., 2911 * <code>MONDAY</code> in France. 2912 * 2913 * @return the first day of the week. 2914 * @see #setFirstDayOfWeek(int) 2915 * @see #getMinimalDaysInFirstWeek() 2916 */ 2917 public int getFirstDayOfWeek() 2918 { 2919 return firstDayOfWeek; 2920 } 2921 2922 /** 2923 * Sets what the minimal days required in the first week of the year are; 2924 * For example, if the first week is defined as one that contains the first 2925 * day of the first month of a year, call this method with value 1. If it 2926 * must be a full week, use value 7. 2927 * 2928 * @param value the given minimal days required in the first week 2929 * of the year. 2930 * @see #getMinimalDaysInFirstWeek() 2931 */ 2932 public void setMinimalDaysInFirstWeek(int value) 2933 { 2934 if (minimalDaysInFirstWeek == value) { 2935 return; 2936 } 2937 minimalDaysInFirstWeek = value; 2938 invalidateWeekFields(); 2939 } 2940 2941 /** 2942 * Gets what the minimal days required in the first week of the year are; 2943 * e.g., if the first week is defined as one that contains the first day 2944 * of the first month of a year, this method returns 1. If 2945 * the minimal days required must be a full week, this method 2946 * returns 7. 2947 * 2948 * @return the minimal days required in the first week of the year. 2949 * @see #setMinimalDaysInFirstWeek(int) 2950 */ 2951 public int getMinimalDaysInFirstWeek() 2952 { 2953 return minimalDaysInFirstWeek; 2954 } 2955 2956 /** 2957 * Returns whether this {@code Calendar} supports week dates. 2958 * 2959 * <p>The default implementation of this method returns {@code false}. 2960 * 2961 * @return {@code true} if this {@code Calendar} supports week dates; 2962 * {@code false} otherwise. 2963 * @see #getWeekYear() 2964 * @see #setWeekDate(int,int,int) 2965 * @see #getWeeksInWeekYear() 2966 * @since 1.7 2967 */ 2968 public boolean isWeekDateSupported() { 2969 return false; 2970 } 2971 2972 /** 2973 * Returns the week year represented by this {@code Calendar}. The 2974 * week year is in sync with the week cycle. The {@linkplain 2975 * #getFirstDayOfWeek() first day of the first week} is the first 2976 * day of the week year. 2977 * 2978 * <p>The default implementation of this method throws an 2979 * {@link UnsupportedOperationException}. 2980 * 2981 * @return the week year of this {@code Calendar} 2982 * @exception UnsupportedOperationException 2983 * if any week year numbering isn't supported 2984 * in this {@code Calendar}. 2985 * @see #isWeekDateSupported() 2986 * @see #getFirstDayOfWeek() 2987 * @see #getMinimalDaysInFirstWeek() 2988 * @since 1.7 2989 */ 2990 public int getWeekYear() { 2991 throw new UnsupportedOperationException(); 2992 } 2993 2994 /** 2995 * Sets the date of this {@code Calendar} with the the given date 2996 * specifiers - week year, week of year, and day of week. 2997 * 2998 * <p>Unlike the {@code set} method, all of the calendar fields 2999 * and {@code time} values are calculated upon return. 3000 * 3001 * <p>If {@code weekOfYear} is out of the valid week-of-year range 3002 * in {@code weekYear}, the {@code weekYear} and {@code 3003 * weekOfYear} values are adjusted in lenient mode, or an {@code 3004 * IllegalArgumentException} is thrown in non-lenient mode. 3005 * 3006 * <p>The default implementation of this method throws an 3007 * {@code UnsupportedOperationException}. 3008 * 3009 * @param weekYear the week year 3010 * @param weekOfYear the week number based on {@code weekYear} 3011 * @param dayOfWeek the day of week value: one of the constants 3012 * for the {@link #DAY_OF_WEEK} field: {@link 3013 * #SUNDAY}, ..., {@link #SATURDAY}. 3014 * @exception IllegalArgumentException 3015 * if any of the given date specifiers is invalid 3016 * or any of the calendar fields are inconsistent 3017 * with the given date specifiers in non-lenient mode 3018 * @exception UnsupportedOperationException 3019 * if any week year numbering isn't supported in this 3020 * {@code Calendar}. 3021 * @see #isWeekDateSupported() 3022 * @see #getFirstDayOfWeek() 3023 * @see #getMinimalDaysInFirstWeek() 3024 * @since 1.7 3025 */ 3026 public void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) { 3027 throw new UnsupportedOperationException(); 3028 } 3029 3030 /** 3031 * Returns the number of weeks in the week year represented by this 3032 * {@code Calendar}. 3033 * 3034 * <p>The default implementation of this method throws an 3035 * {@code UnsupportedOperationException}. 3036 * 3037 * @return the number of weeks in the week year. 3038 * @exception UnsupportedOperationException 3039 * if any week year numbering isn't supported in this 3040 * {@code Calendar}. 3041 * @see #WEEK_OF_YEAR 3042 * @see #isWeekDateSupported() 3043 * @see #getWeekYear() 3044 * @see #getActualMaximum(int) 3045 * @since 1.7 3046 */ 3047 public int getWeeksInWeekYear() { 3048 throw new UnsupportedOperationException(); 3049 } 3050 3051 /** 3052 * Returns the minimum value for the given calendar field of this 3053 * <code>Calendar</code> instance. The minimum value is defined as 3054 * the smallest value returned by the {@link #get(int) get} method 3055 * for any possible time value. The minimum value depends on 3056 * calendar system specific parameters of the instance. 3057 * 3058 * @param field the calendar field. 3059 * @return the minimum value for the given calendar field. 3060 * @see #getMaximum(int) 3061 * @see #getGreatestMinimum(int) 3062 * @see #getLeastMaximum(int) 3063 * @see #getActualMinimum(int) 3064 * @see #getActualMaximum(int) 3065 */ 3066 abstract public int getMinimum(int field); 3067 3068 /** 3069 * Returns the maximum value for the given calendar field of this 3070 * <code>Calendar</code> instance. The maximum value is defined as 3071 * the largest value returned by the {@link #get(int) get} method 3072 * for any possible time value. The maximum value depends on 3073 * calendar system specific parameters of the instance. 3074 * 3075 * @param field the calendar field. 3076 * @return the maximum value for the given calendar field. 3077 * @see #getMinimum(int) 3078 * @see #getGreatestMinimum(int) 3079 * @see #getLeastMaximum(int) 3080 * @see #getActualMinimum(int) 3081 * @see #getActualMaximum(int) 3082 */ 3083 abstract public int getMaximum(int field); 3084 3085 /** 3086 * Returns the highest minimum value for the given calendar field 3087 * of this <code>Calendar</code> instance. The highest minimum 3088 * value is defined as the largest value returned by {@link 3089 * #getActualMinimum(int)} for any possible time value. The 3090 * greatest minimum value depends on calendar system specific 3091 * parameters of the instance. 3092 * 3093 * @param field the calendar field. 3094 * @return the highest minimum value for the given calendar field. 3095 * @see #getMinimum(int) 3096 * @see #getMaximum(int) 3097 * @see #getLeastMaximum(int) 3098 * @see #getActualMinimum(int) 3099 * @see #getActualMaximum(int) 3100 */ 3101 abstract public int getGreatestMinimum(int field); 3102 3103 /** 3104 * Returns the lowest maximum value for the given calendar field 3105 * of this <code>Calendar</code> instance. The lowest maximum 3106 * value is defined as the smallest value returned by {@link 3107 * #getActualMaximum(int)} for any possible time value. The least 3108 * maximum value depends on calendar system specific parameters of 3109 * the instance. For example, a <code>Calendar</code> for the 3110 * Gregorian calendar system returns 28 for the 3111 * <code>DAY_OF_MONTH</code> field, because the 28th is the last 3112 * day of the shortest month of this calendar, February in a 3113 * common year. 3114 * 3115 * @param field the calendar field. 3116 * @return the lowest maximum value for the given calendar field. 3117 * @see #getMinimum(int) 3118 * @see #getMaximum(int) 3119 * @see #getGreatestMinimum(int) 3120 * @see #getActualMinimum(int) 3121 * @see #getActualMaximum(int) 3122 */ 3123 abstract public int getLeastMaximum(int field); 3124 3125 /** 3126 * Returns the minimum value that the specified calendar field 3127 * could have, given the time value of this <code>Calendar</code>. 3128 * 3129 * <p>The default implementation of this method uses an iterative 3130 * algorithm to determine the actual minimum value for the 3131 * calendar field. Subclasses should, if possible, override this 3132 * with a more efficient implementation - in many cases, they can 3133 * simply return <code>getMinimum()</code>. 3134 * 3135 * @param field the calendar field 3136 * @return the minimum of the given calendar field for the time 3137 * value of this <code>Calendar</code> 3138 * @see #getMinimum(int) 3139 * @see #getMaximum(int) 3140 * @see #getGreatestMinimum(int) 3141 * @see #getLeastMaximum(int) 3142 * @see #getActualMaximum(int) 3143 * @since 1.2 3144 */ 3145 public int getActualMinimum(int field) { 3146 int fieldValue = getGreatestMinimum(field); 3147 int endValue = getMinimum(field); 3148 3149 // if we know that the minimum value is always the same, just return it 3150 if (fieldValue == endValue) { 3151 return fieldValue; 3152 } 3153 3154 // clone the calendar so we don't mess with the real one, and set it to 3155 // accept anything for the field values 3156 Calendar work = (Calendar)this.clone(); 3157 work.setLenient(true); 3158 3159 // now try each value from getLeastMaximum() to getMaximum() one by one until 3160 // we get a value that normalizes to another value. The last value that 3161 // normalizes to itself is the actual minimum for the current date 3162 int result = fieldValue; 3163 3164 do { 3165 work.set(field, fieldValue); 3166 if (work.get(field) != fieldValue) { 3167 break; 3168 } else { 3169 result = fieldValue; 3170 fieldValue--; 3171 } 3172 } while (fieldValue >= endValue); 3173 3174 return result; 3175 } 3176 3177 /** 3178 * Returns the maximum value that the specified calendar field 3179 * could have, given the time value of this 3180 * <code>Calendar</code>. For example, the actual maximum value of 3181 * the <code>MONTH</code> field is 12 in some years, and 13 in 3182 * other years in the Hebrew calendar system. 3183 * 3184 * <p>The default implementation of this method uses an iterative 3185 * algorithm to determine the actual maximum value for the 3186 * calendar field. Subclasses should, if possible, override this 3187 * with a more efficient implementation. 3188 * 3189 * @param field the calendar field 3190 * @return the maximum of the given calendar field for the time 3191 * value of this <code>Calendar</code> 3192 * @see #getMinimum(int) 3193 * @see #getMaximum(int) 3194 * @see #getGreatestMinimum(int) 3195 * @see #getLeastMaximum(int) 3196 * @see #getActualMinimum(int) 3197 * @since 1.2 3198 */ 3199 public int getActualMaximum(int field) { 3200 int fieldValue = getLeastMaximum(field); 3201 int endValue = getMaximum(field); 3202 3203 // if we know that the maximum value is always the same, just return it. 3204 if (fieldValue == endValue) { 3205 return fieldValue; 3206 } 3207 3208 // clone the calendar so we don't mess with the real one, and set it to 3209 // accept anything for the field values. 3210 Calendar work = (Calendar)this.clone(); 3211 work.setLenient(true); 3212 3213 // if we're counting weeks, set the day of the week to Sunday. We know the 3214 // last week of a month or year will contain the first day of the week. 3215 if (field == WEEK_OF_YEAR || field == WEEK_OF_MONTH) { 3216 work.set(DAY_OF_WEEK, firstDayOfWeek); 3217 } 3218 3219 // now try each value from getLeastMaximum() to getMaximum() one by one until 3220 // we get a value that normalizes to another value. The last value that 3221 // normalizes to itself is the actual maximum for the current date 3222 int result = fieldValue; 3223 3224 do { 3225 work.set(field, fieldValue); 3226 if (work.get(field) != fieldValue) { 3227 break; 3228 } else { 3229 result = fieldValue; 3230 fieldValue++; 3231 } 3232 } while (fieldValue <= endValue); 3233 3234 return result; 3235 } 3236 3237 /** 3238 * Creates and returns a copy of this object. 3239 * 3240 * @return a copy of this object. 3241 */ 3242 @Override 3243 public Object clone() 3244 { 3245 try { 3246 Calendar other = (Calendar) super.clone(); 3247 3248 other.fields = new int[FIELD_COUNT]; 3249 other.isSet = new boolean[FIELD_COUNT]; 3250 other.stamp = new int[FIELD_COUNT]; 3251 for (int i = 0; i < FIELD_COUNT; i++) { 3252 other.fields[i] = fields[i]; 3253 other.stamp[i] = stamp[i]; 3254 other.isSet[i] = isSet[i]; 3255 } 3256 other.zone = (TimeZone) zone.clone(); 3257 return other; 3258 } 3259 catch (CloneNotSupportedException e) { 3260 // this shouldn't happen, since we are Cloneable 3261 throw new InternalError(e); 3262 } 3263 } 3264 3265 private static final String[] FIELD_NAME = { 3266 "ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH", "DAY_OF_MONTH", 3267 "DAY_OF_YEAR", "DAY_OF_WEEK", "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR", 3268 "HOUR_OF_DAY", "MINUTE", "SECOND", "MILLISECOND", "ZONE_OFFSET", 3269 "DST_OFFSET" 3270 }; 3271 3272 /** 3273 * Returns the name of the specified calendar field. 3274 * 3275 * @param field the calendar field 3276 * @return the calendar field name 3277 * @exception IndexOutOfBoundsException if <code>field</code> is negative, 3278 * equal to or greater then <code>FIELD_COUNT</code>. 3279 */ 3280 static String getFieldName(int field) { 3281 return FIELD_NAME[field]; 3282 } 3283 3284 /** 3285 * Return a string representation of this calendar. This method 3286 * is intended to be used only for debugging purposes, and the 3287 * format of the returned string may vary between implementations. 3288 * The returned string may be empty but may not be <code>null</code>. 3289 * 3290 * @return a string representation of this calendar. 3291 */ 3292 @Override 3293 public String toString() { 3294 // NOTE: BuddhistCalendar.toString() interprets the string 3295 // produced by this method so that the Gregorian year number 3296 // is substituted by its B.E. year value. It relies on 3297 // "...,YEAR=<year>,..." or "...,YEAR=?,...". 3298 StringBuilder buffer = new StringBuilder(800); 3299 buffer.append(getClass().getName()).append('['); 3300 appendValue(buffer, "time", isTimeSet, time); 3301 buffer.append(",areFieldsSet=").append(areFieldsSet); 3302 buffer.append(",areAllFieldsSet=").append(areAllFieldsSet); 3303 buffer.append(",lenient=").append(lenient); 3304 buffer.append(",zone=").append(zone); 3305 appendValue(buffer, ",firstDayOfWeek", true, (long) firstDayOfWeek); 3306 appendValue(buffer, ",minimalDaysInFirstWeek", true, (long) minimalDaysInFirstWeek); 3307 for (int i = 0; i < FIELD_COUNT; ++i) { 3308 buffer.append(','); 3309 appendValue(buffer, FIELD_NAME[i], isSet(i), (long) fields[i]); 3310 } 3311 buffer.append(']'); 3312 return buffer.toString(); 3313 } 3314 3315 // =======================privates=============================== 3316 3317 private static void appendValue(StringBuilder sb, String item, boolean valid, long value) { 3318 sb.append(item).append('='); 3319 if (valid) { 3320 sb.append(value); 3321 } else { 3322 sb.append('?'); 3323 } 3324 } 3325 3326 /** 3327 * Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent. 3328 * They are used to figure out the week count for a specific date for 3329 * a given locale. These must be set when a Calendar is constructed. 3330 * @param desiredLocale the given locale. 3331 */ 3332 private void setWeekCountData(Locale desiredLocale) 3333 { 3334 /* try to get the Locale data from the cache */ 3335 int[] data = cachedLocaleData.get(desiredLocale); 3336 if (data == null) { /* cache miss */ 3337 data = new int[2]; 3338 data[0] = CalendarDataUtility.retrieveFirstDayOfWeek(desiredLocale); 3339 data[1] = CalendarDataUtility.retrieveMinimalDaysInFirstWeek(desiredLocale); 3340 cachedLocaleData.putIfAbsent(desiredLocale, data); 3341 } 3342 firstDayOfWeek = data[0]; 3343 minimalDaysInFirstWeek = data[1]; 3344 } 3345 3346 /** 3347 * Recomputes the time and updates the status fields isTimeSet 3348 * and areFieldsSet. Callers should check isTimeSet and only 3349 * call this method if isTimeSet is false. 3350 */ 3351 private void updateTime() { 3352 computeTime(); 3353 // The areFieldsSet and areAllFieldsSet values are no longer 3354 // controlled here (as of 1.5). 3355 isTimeSet = true; 3356 } 3357 3358 private int compareTo(long t) { 3359 long thisTime = getMillisOf(this); 3360 return (thisTime > t) ? 1 : (thisTime == t) ? 0 : -1; 3361 } 3362 3363 private static long getMillisOf(Calendar calendar) { 3364 if (calendar.isTimeSet) { 3365 return calendar.time; 3366 } 3367 Calendar cal = (Calendar) calendar.clone(); 3368 cal.setLenient(true); 3369 return cal.getTimeInMillis(); 3370 } 3371 3372 /** 3373 * Adjusts the stamp[] values before nextStamp overflow. nextStamp 3374 * is set to the next stamp value upon the return. 3375 */ 3376 private void adjustStamp() { 3377 int max = MINIMUM_USER_STAMP; 3378 int newStamp = MINIMUM_USER_STAMP; 3379 3380 for (;;) { 3381 int min = Integer.MAX_VALUE; 3382 for (int i = 0; i < stamp.length; i++) { 3383 int v = stamp[i]; 3384 if (v >= newStamp && min > v) { 3385 min = v; 3386 } 3387 if (max < v) { 3388 max = v; 3389 } 3390 } 3391 if (max != min && min == Integer.MAX_VALUE) { 3392 break; 3393 } 3394 for (int i = 0; i < stamp.length; i++) { 3395 if (stamp[i] == min) { 3396 stamp[i] = newStamp; 3397 } 3398 } 3399 newStamp++; 3400 if (min == max) { 3401 break; 3402 } 3403 } 3404 nextStamp = newStamp; 3405 } 3406 3407 /** 3408 * Sets the WEEK_OF_MONTH and WEEK_OF_YEAR fields to new values with the 3409 * new parameter value if they have been calculated internally. 3410 */ 3411 private void invalidateWeekFields() 3412 { 3413 if (stamp[WEEK_OF_MONTH] != COMPUTED && 3414 stamp[WEEK_OF_YEAR] != COMPUTED) { 3415 return; 3416 } 3417 3418 // We have to check the new values of these fields after changing 3419 // firstDayOfWeek and/or minimalDaysInFirstWeek. If the field values 3420 // have been changed, then set the new values. (4822110) 3421 Calendar cal = (Calendar) clone(); 3422 cal.setLenient(true); 3423 cal.clear(WEEK_OF_MONTH); 3424 cal.clear(WEEK_OF_YEAR); 3425 3426 if (stamp[WEEK_OF_MONTH] == COMPUTED) { 3427 int weekOfMonth = cal.get(WEEK_OF_MONTH); 3428 if (fields[WEEK_OF_MONTH] != weekOfMonth) { 3429 fields[WEEK_OF_MONTH] = weekOfMonth; 3430 } 3431 } 3432 3433 if (stamp[WEEK_OF_YEAR] == COMPUTED) { 3434 int weekOfYear = cal.get(WEEK_OF_YEAR); 3435 if (fields[WEEK_OF_YEAR] != weekOfYear) { 3436 fields[WEEK_OF_YEAR] = weekOfYear; 3437 } 3438 } 3439 } 3440 3441 /** 3442 * Save the state of this object to a stream (i.e., serialize it). 3443 * 3444 * Ideally, <code>Calendar</code> would only write out its state data and 3445 * the current time, and not write any field data out, such as 3446 * <code>fields[]</code>, <code>isTimeSet</code>, <code>areFieldsSet</code>, 3447 * and <code>isSet[]</code>. <code>nextStamp</code> also should not be part 3448 * of the persistent state. Unfortunately, this didn't happen before JDK 1.1 3449 * shipped. To be compatible with JDK 1.1, we will always have to write out 3450 * the field values and state flags. However, <code>nextStamp</code> can be 3451 * removed from the serialization stream; this will probably happen in the 3452 * near future. 3453 */ 3454 private synchronized void writeObject(ObjectOutputStream stream) 3455 throws IOException 3456 { 3457 // Try to compute the time correctly, for the future (stream 3458 // version 2) in which we don't write out fields[] or isSet[]. 3459 if (!isTimeSet) { 3460 try { 3461 updateTime(); 3462 } 3463 catch (IllegalArgumentException e) {} 3464 } 3465 3466 // If this Calendar has a ZoneInfo, save it and set a 3467 // SimpleTimeZone equivalent (as a single DST schedule) for 3468 // backward compatibility. 3469 TimeZone savedZone = null; 3470 if (zone instanceof ZoneInfo) { 3471 SimpleTimeZone stz = ((ZoneInfo)zone).getLastRuleInstance(); 3472 if (stz == null) { 3473 stz = new SimpleTimeZone(zone.getRawOffset(), zone.getID()); 3474 } 3475 savedZone = zone; 3476 zone = stz; 3477 } 3478 3479 // Write out the 1.1 FCS object. 3480 stream.defaultWriteObject(); 3481 3482 // Write out the ZoneInfo object 3483 // 4802409: we write out even if it is null, a temporary workaround 3484 // the real fix for bug 4844924 in corba-iiop 3485 stream.writeObject(savedZone); 3486 if (savedZone != null) { 3487 zone = savedZone; 3488 } 3489 } 3490 3491 private static class CalendarAccessControlContext { 3492 private static final AccessControlContext INSTANCE; 3493 static { 3494 RuntimePermission perm = new RuntimePermission("accessClassInPackage.sun.util.calendar"); 3495 PermissionCollection perms = perm.newPermissionCollection(); 3496 perms.add(perm); 3497 INSTANCE = new AccessControlContext(new ProtectionDomain[] { 3498 new ProtectionDomain(null, perms) 3499 }); 3500 } 3501 private CalendarAccessControlContext() { 3502 } 3503 } 3504 3505 /** 3506 * Reconstitutes this object from a stream (i.e., deserialize it). 3507 */ 3508 private void readObject(ObjectInputStream stream) 3509 throws IOException, ClassNotFoundException 3510 { 3511 final ObjectInputStream input = stream; 3512 input.defaultReadObject(); 3513 3514 stamp = new int[FIELD_COUNT]; 3515 3516 // Starting with version 2 (not implemented yet), we expect that 3517 // fields[], isSet[], isTimeSet, and areFieldsSet may not be 3518 // streamed out anymore. We expect 'time' to be correct. 3519 if (serialVersionOnStream >= 2) 3520 { 3521 isTimeSet = true; 3522 if (fields == null) { 3523 fields = new int[FIELD_COUNT]; 3524 } 3525 if (isSet == null) { 3526 isSet = new boolean[FIELD_COUNT]; 3527 } 3528 } 3529 else if (serialVersionOnStream >= 0) 3530 { 3531 for (int i=0; i<FIELD_COUNT; ++i) { 3532 stamp[i] = isSet[i] ? COMPUTED : UNSET; 3533 } 3534 } 3535 3536 serialVersionOnStream = currentSerialVersion; 3537 3538 // If there's a ZoneInfo object, use it for zone. 3539 ZoneInfo zi = null; 3540 try { 3541 zi = AccessController.doPrivileged( 3542 new PrivilegedExceptionAction<ZoneInfo>() { 3543 @Override 3544 public ZoneInfo run() throws Exception { 3545 return (ZoneInfo) input.readObject(); 3546 } 3547 }, 3548 CalendarAccessControlContext.INSTANCE); 3549 } catch (PrivilegedActionException pae) { 3550 Exception e = pae.getException(); 3551 if (!(e instanceof OptionalDataException)) { 3552 if (e instanceof RuntimeException) { 3553 throw (RuntimeException) e; 3554 } else if (e instanceof IOException) { 3555 throw (IOException) e; 3556 } else if (e instanceof ClassNotFoundException) { 3557 throw (ClassNotFoundException) e; 3558 } 3559 throw new RuntimeException(e); 3560 } 3561 } 3562 if (zi != null) { 3563 zone = zi; 3564 } 3565 3566 // If the deserialized object has a SimpleTimeZone, try to 3567 // replace it with a ZoneInfo equivalent (as of 1.4) in order 3568 // to be compatible with the SimpleTimeZone-based 3569 // implementation as much as possible. 3570 if (zone instanceof SimpleTimeZone) { 3571 String id = zone.getID(); 3572 TimeZone tz = TimeZone.getTimeZone(id); 3573 if (tz != null && tz.hasSameRules(zone) && tz.getID().equals(id)) { 3574 zone = tz; 3575 } 3576 } 3577 } 3578 3579 /** 3580 * Converts this object to an {@link Instant}. 3581 * <p> 3582 * The conversion creates an {@code Instant} that represents the 3583 * same point on the time-line as this {@code Calendar}. 3584 * 3585 * @return the instant representing the same point on the time-line 3586 * @since 1.8 3587 */ 3588 public final Instant toInstant() { 3589 return Instant.ofEpochMilli(getTimeInMillis()); 3590 } 3591 }