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