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