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