• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* GENERATED SOURCE. DO NOT MODIFY. */
2 // © 2016 and later: Unicode, Inc. and others.
3 // License & terms of use: http://www.unicode.org/copyright.html#License
4 /*
5  *   Copyright (C) 1996-2016, International Business Machines
6  *   Corporation and others.  All Rights Reserved.
7  */
8 
9 package ohos.global.icu.text;
10 
11 import java.io.IOException;
12 import java.io.InvalidObjectException;
13 import java.io.ObjectInputStream;
14 import java.text.FieldPosition;
15 import java.text.Format;
16 import java.text.ParseException;
17 import java.text.ParsePosition;
18 import java.util.Arrays;
19 import java.util.Date;
20 import java.util.EnumSet;
21 import java.util.HashMap;
22 import java.util.List;
23 import java.util.Locale;
24 import java.util.Map;
25 import java.util.MissingResourceException;
26 
27 import ohos.global.icu.impl.ICUResourceBundle;
28 import ohos.global.icu.impl.RelativeDateFormat;
29 import ohos.global.icu.util.Calendar;
30 import ohos.global.icu.util.GregorianCalendar;
31 import ohos.global.icu.util.TimeZone;
32 import ohos.global.icu.util.ULocale;
33 import ohos.global.icu.util.ULocale.Category;
34 
35 /**
36  * <strong>[icu enhancement]</strong> ICU's replacement for {@link java.text.DateFormat}.&nbsp;Methods, fields, and other functionality specific to ICU are labeled '<strong>[icu]</strong>'.
37  *
38  * <p>
39  * DateFormat is an abstract class for date/time formatting subclasses which formats and parses dates or time in a
40  * language-independent manner. The date/time formatting subclass, such as SimpleDateFormat, allows for formatting
41  * (i.e., date -&gt; text), parsing (text -&gt; date), and normalization. The date is represented as a <code>Date</code>
42  * object or as the milliseconds since January 1, 1970, 00:00:00 GMT.
43  *
44  * <p>
45  * DateFormat helps you to format and parse dates for any locale. Your code can be completely independent of the locale
46  * conventions for months, days of the week, or even the calendar format: lunar vs. solar. It provides many class
47  * methods for obtaining default date/time formatters based on the default for a given locale and a number of formatting
48  * styles or arbitrary "skeletons".
49  * <ol>
50  * <li>The formatting styles include FULL, LONG, MEDIUM, and SHORT. More detail and examples of using these styles are
51  * provided in the method descriptions.
52  * <li>The formatting styles only cover a fraction of the necessary usage. You often need to have just certain
53  * combinations of fields, like Month and Year, but have it to be formatted appropriate to a given locale. This is done
54  * using the (misnamed) getPatternInstance() method, supplying a skeleton. There are a number of constants that have
55  * common pre-defined skeletons, such as {@link #MINUTE_SECOND} for something like "13:45" or {@link #YEAR_ABBR_MONTH}
56  * for something like "Sept 2012".
57  * </ol>
58  *
59  * <p>
60  * To format a date for the current Locale, use one of the static factory methods:
61  *
62  * <pre>
63  * myString = DateFormat.getDateInstance().format(myDate);
64  * myString = DateFormat.getPatternInstance(DateFormat.YEAR_ABBR_MONTH).format(myDate);
65  * </pre>
66  * <p>
67  * If you are formatting multiple numbers, it is more efficient to get the format and use it multiple times so that the
68  * system doesn't have to fetch the information about the local language and country conventions multiple times.
69  *
70  * <pre>
71  * DateFormat df = DateFormat.getDateInstance();
72  * for (int i = 0; i &lt; a.length; ++i) {
73  *     output.println(df.format(myDate[i]) + &quot;; &quot;);
74  * }
75  * </pre>
76  * <p>
77  * To format a date for a different Locale, specify it in the call to getDateInstance().
78  *
79  * <pre>
80  * DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);
81  * </pre>
82  * <p>
83  * You can use a DateFormat to parse also.
84  *
85  * <pre>
86  * myDate = df.parse(myString);
87  * </pre>
88  * <p>
89  * There are many static factory methods available. Use getDateInstance to get the normal date format for that country.
90  * Use getTimeInstance to get the time format for that country. Use getDateTimeInstance to get a date and time format.
91  * You can pass in different options to these factory methods to control the length of the result; from SHORT to MEDIUM
92  * to LONG to FULL. The exact result depends on the locale, but generally:
93  * <ul>
94  * <li>SHORT is completely numeric, such as 12.13.52 or 3:30pm
95  * <li>MEDIUM is longer, such as Jan 12, 1952
96  * <li>LONG is longer, such as January 12, 1952 or 3:30:32pm
97  * <li>FULL is pretty completely specified, such as Tuesday, April 12, 1952 AD or 3:30:42pm PST.
98  * </ul>
99  *
100  * <p>
101  * Use getPatternInstance to format with a skeleton. Typically this is with a predefined skeleton, like
102  * {@link #YEAR_ABBR_MONTH} for something like "Sept 2012". If you don't want to use one of the predefined skeletons,
103  * you can supply your own. The skeletons are like the patterns in SimpleDateFormat, except they:
104  * <ol>
105  * <li>only keep the field pattern letter and ignore all other parts in a pattern, such as space, punctuation, and
106  * string literals.
107  * <li>are independent of the order of fields.
108  * <li>ignore certain differences in the field's pattern letter length:
109  * <ol>
110  * <li>For those non-digit calendar fields, the pattern letter length is important, such as MMM, MMMM, and MMMMM; E and
111  * EEEE, and the field's pattern letter length is honored.
112  * <li>For the digit calendar fields, such as M or MM, d or dd, yy or yyyy, the field pattern length is ignored and the
113  * best match, which is defined in date time patterns, will be returned without honor the field pattern letter length in
114  * skeleton.
115  * </ol>
116  * </ol>
117  *
118  * <p>
119  * You can also set the time zone on the format if you wish. If you want even more control over the format or parsing,
120  * (or want to give your users more control), you can try casting the DateFormat you get from the factory methods to a
121  * SimpleDateFormat. This will work for the majority of countries; just remember to put it in a try block in case you
122  * encounter an unusual one.
123  *
124  * <p>
125  * You can also use forms of the parse and format methods with ParsePosition and FieldPosition to allow you to
126  * <ul>
127  * <li>progressively parse through pieces of a string.
128  * <li>align any particular field, or find out where it is for selection on the screen.
129  * </ul>
130  *
131  * <h3>Synchronization</h3>
132  *
133  * Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple
134  * threads access a format concurrently, it must be synchronized externally.
135  *
136  * @see UFormat
137  * @see NumberFormat
138  * @see SimpleDateFormat
139  * @see ohos.global.icu.util.Calendar
140  * @see ohos.global.icu.util.GregorianCalendar
141  * @see ohos.global.icu.util.TimeZone
142  * @author Mark Davis, Chen-Lieh Huang, Alan Liu
143  */
144 public abstract class DateFormat extends UFormat {
145 
146     /**
147      * The calendar that <code>DateFormat</code> uses to produce the time field
148      * values needed to implement date and time formatting.  Subclasses should
149      * initialize this to a calendar appropriate for the locale associated with
150      * this <code>DateFormat</code>.
151      * @serial
152      */
153     protected Calendar calendar;
154 
155     /**
156      * The number formatter that <code>DateFormat</code> uses to format numbers
157      * in dates and times.  Subclasses should initialize this to a number format
158      * appropriate for the locale associated with this <code>DateFormat</code>.
159      * @serial
160      */
161     protected NumberFormat numberFormat;
162 
163     /**
164      * FieldPosition selector for 'G' field alignment,
165      * corresponding to the {@link Calendar#ERA} field.
166      */
167     public final static int ERA_FIELD = 0;
168 
169     /**
170      * FieldPosition selector for 'y' field alignment,
171      * corresponding to the {@link Calendar#YEAR} field.
172      */
173     public final static int YEAR_FIELD = 1;
174 
175     /**
176      * FieldPosition selector for 'M' field alignment,
177      * corresponding to the {@link Calendar#MONTH} field.
178      */
179     public final static int MONTH_FIELD = 2;
180 
181     /**
182      * FieldPosition selector for 'd' field alignment,
183      * corresponding to the {@link Calendar#DATE} field.
184      */
185     public final static int DATE_FIELD = 3;
186 
187     /**
188      * FieldPosition selector for 'k' field alignment,
189      * corresponding to the {@link Calendar#HOUR_OF_DAY} field.
190      * HOUR_OF_DAY1_FIELD is used for the one-based 24-hour clock.
191      * For example, 23:59 + 01:00 results in 24:59.
192      */
193     public final static int HOUR_OF_DAY1_FIELD = 4;
194 
195     /**
196      * FieldPosition selector for 'H' field alignment,
197      * corresponding to the {@link Calendar#HOUR_OF_DAY} field.
198      * HOUR_OF_DAY0_FIELD is used for the zero-based 24-hour clock.
199      * For example, 23:59 + 01:00 results in 00:59.
200      */
201     public final static int HOUR_OF_DAY0_FIELD = 5;
202 
203     /**
204      * FieldPosition selector for 'm' field alignment,
205      * corresponding to the {@link Calendar#MINUTE} field.
206      */
207     public final static int MINUTE_FIELD = 6;
208 
209     /**
210      * FieldPosition selector for 's' field alignment,
211      * corresponding to the {@link Calendar#SECOND} field.
212      */
213     public final static int SECOND_FIELD = 7;
214 
215     /**
216      * <strong>[icu]</strong> FieldPosition selector for 'S' field alignment,
217      * corresponding to the {@link Calendar#MILLISECOND} field.
218      *
219      * Note: Time formats that use 'S' can display a maximum of three
220      * significant digits for fractional seconds, corresponding to millisecond
221      * resolution and a fractional seconds sub-pattern of SSS. If the
222      * sub-pattern is S or SS, the fractional seconds value will be truncated
223      * (not rounded) to the number of display places specified. If the
224      * fractional seconds sub-pattern is longer than SSS, the additional
225      * display places will be filled with zeros.
226      */
227     public final static int FRACTIONAL_SECOND_FIELD = 8;
228 
229     /**
230      * Alias for FRACTIONAL_SECOND_FIELD.
231      */
232     public final static int MILLISECOND_FIELD = FRACTIONAL_SECOND_FIELD;
233 
234     /**
235      * FieldPosition selector for 'E' field alignment,
236      * corresponding to the {@link Calendar#DAY_OF_WEEK} field.
237      */
238     public final static int DAY_OF_WEEK_FIELD = 9;
239 
240     /**
241      * FieldPosition selector for 'D' field alignment,
242      * corresponding to the {@link Calendar#DAY_OF_YEAR} field.
243      */
244     public final static int DAY_OF_YEAR_FIELD = 10;
245 
246     /**
247      * FieldPosition selector for 'F' field alignment,
248      * corresponding to the {@link Calendar#DAY_OF_WEEK_IN_MONTH} field.
249      */
250     public final static int DAY_OF_WEEK_IN_MONTH_FIELD = 11;
251 
252     /**
253      * FieldPosition selector for 'w' field alignment,
254      * corresponding to the {@link Calendar#WEEK_OF_YEAR} field.
255      */
256     public final static int WEEK_OF_YEAR_FIELD = 12;
257 
258     /**
259      * FieldPosition selector for 'W' field alignment,
260      * corresponding to the {@link Calendar#WEEK_OF_MONTH} field.
261      */
262     public final static int WEEK_OF_MONTH_FIELD = 13;
263 
264     /**
265      * FieldPosition selector for 'a' field alignment,
266      * corresponding to the {@link Calendar#AM_PM} field.
267      */
268     public final static int AM_PM_FIELD = 14;
269 
270     /**
271      * FieldPosition selector for 'h' field alignment,
272      * corresponding to the {@link Calendar#HOUR} field.
273      * HOUR1_FIELD is used for the one-based 12-hour clock.
274      * For example, 11:30 PM + 1 hour results in 12:30 AM.
275      */
276     public final static int HOUR1_FIELD = 15;
277 
278     /**
279      * FieldPosition selector for 'K' field alignment,
280      * corresponding to the {@link Calendar#HOUR} field.
281      * HOUR0_FIELD is used for the zero-based 12-hour clock.
282      * For example, 11:30 PM + 1 hour results in 00:30 AM.
283      */
284     public final static int HOUR0_FIELD = 16;
285 
286     /**
287      * FieldPosition selector for 'z' field alignment,
288      * corresponding to the {@link Calendar#ZONE_OFFSET} and
289      * {@link Calendar#DST_OFFSET} fields.
290      */
291     public final static int TIMEZONE_FIELD = 17;
292 
293     /**
294      * <strong>[icu]</strong> FieldPosition selector for 'Y' field alignment,
295      * corresponding to the {@link Calendar#YEAR_WOY} field.
296      */
297     public final static int YEAR_WOY_FIELD = 18;
298 
299     /**
300      * <strong>[icu]</strong> FieldPosition selector for 'e' field alignment,
301      * corresponding to the {@link Calendar#DOW_LOCAL} field.
302      */
303     public final static int DOW_LOCAL_FIELD = 19;
304 
305     /**
306      * <strong>[icu]</strong> FieldPosition selector for 'u' field alignment,
307      * corresponding to the {@link Calendar#EXTENDED_YEAR} field.
308      */
309     public final static int EXTENDED_YEAR_FIELD = 20;
310 
311     /**
312      * <strong>[icu]</strong> FieldPosition selector for 'g' field alignment,
313      * corresponding to the {@link Calendar#JULIAN_DAY} field.
314      */
315     public final static int JULIAN_DAY_FIELD = 21;
316 
317     /**
318      * <strong>[icu]</strong> FieldPosition selector for 'A' field alignment,
319      * corresponding to the {@link Calendar#MILLISECONDS_IN_DAY} field.
320      */
321     public final static int MILLISECONDS_IN_DAY_FIELD = 22;
322 
323     /**
324      * <strong>[icu]</strong> FieldPosition selector for 'Z' field alignment,
325      * corresponding to the {@link Calendar#ZONE_OFFSET} and
326      * {@link Calendar#DST_OFFSET} fields.
327      */
328     public final static int TIMEZONE_RFC_FIELD = 23;
329 
330     /**
331      * <strong>[icu]</strong> FieldPosition selector for 'v' field alignment,
332      * corresponding to the {@link Calendar#ZONE_OFFSET} and
333      * {@link Calendar#DST_OFFSET} fields.  This displays the generic zone
334      * name, if available.
335      */
336     public final static int TIMEZONE_GENERIC_FIELD = 24;
337 
338     /**
339      * <strong>[icu]</strong> FieldPosition selector for 'c' field alignment,
340      * corresponding to the {@link Calendar#DAY_OF_WEEK} field.
341      * This displays the stand alone day name, if available.
342      */
343     public final static int STANDALONE_DAY_FIELD = 25;
344 
345     /**
346      * <strong>[icu]</strong> FieldPosition selector for 'L' field alignment,
347      * corresponding to the {@link Calendar#MONTH} field.
348      * This displays the stand alone month name, if available.
349      */
350     public final static int STANDALONE_MONTH_FIELD = 26;
351 
352     /**
353      * <strong>[icu]</strong> FieldPosition selector for 'Q' field alignment,
354      * corresponding to the {@link Calendar#MONTH} field.
355      * This displays the quarter.
356      */
357     public final static int QUARTER_FIELD = 27;
358 
359     /**
360      * <strong>[icu]</strong> FieldPosition selector for 'q' field alignment,
361      * corresponding to the {@link Calendar#MONTH} field.
362      * This displays the stand alone quarter, if available.
363      */
364     public final static int STANDALONE_QUARTER_FIELD = 28;
365 
366     /**
367      * <strong>[icu]</strong> FieldPosition selector for 'V' field alignment,
368      * corresponding to the {@link Calendar#ZONE_OFFSET} and
369      * {@link Calendar#DST_OFFSET} fields.  This displays the fallback timezone
370      * name when VVVV is specified, and the short standard or daylight
371      * timezone name ignoring commonlyUsed when a single V is specified.
372      */
373     public final static int TIMEZONE_SPECIAL_FIELD = 29;
374 
375     /**
376      * <strong>[icu]</strong> FieldPosition selector for 'U' field alignment,
377      * corresponding to the {@link Calendar#YEAR} field.
378      * This displays the cyclic year name, if available.
379      */
380     public final static int YEAR_NAME_FIELD = 30;
381 
382     /**
383      * <strong>[icu]</strong> FieldPosition selector for 'O' field alignment,
384      * corresponding to the {@link Calendar#ZONE_OFFSET} and
385      * {@link Calendar#DST_OFFSET} fields.  This displays the
386      * localized GMT format.
387      */
388     public final static int TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD = 31;
389 
390     /**
391      * <strong>[icu]</strong> FieldPosition selector for 'X' field alignment,
392      * corresponding to the {@link Calendar#ZONE_OFFSET} and
393      * {@link Calendar#DST_OFFSET} fields.  This displays the
394      * ISO 8601 local time offset format or UTC indicator ("Z").
395      */
396     public final static int TIMEZONE_ISO_FIELD = 32;
397 
398     /**
399      * <strong>[icu]</strong> FieldPosition selector for 'x' field alignment,
400      * corresponding to the {@link Calendar#ZONE_OFFSET} and
401      * {@link Calendar#DST_OFFSET} fields.  This displays the
402      * ISO 8601 local time offset format.
403      */
404     public final static int TIMEZONE_ISO_LOCAL_FIELD = 33;
405 
406     /**
407      * <strong>[icu]</strong> FieldPosition selector for 'r' field alignment,
408      * corresponding to the {@link Calendar#EXTENDED_YEAR} field
409      * of the *related* calendar which may be different than the
410      * one used by the DateFormat.
411      * @deprecated This API is ICU internal only.
412      * @hide draft / provisional / internal are hidden on OHOS
413      */
414     @Deprecated
415     final static int RELATED_YEAR = 34;
416 
417     /**
418      * <strong>[icu]</strong> FieldPosition selector for 'b' field alignment.
419      * No related Calendar field.
420      * This displays the fixed day period (am/pm/midnight/noon).
421      */
422     public final static int AM_PM_MIDNIGHT_NOON_FIELD = 35;
423 
424     /**
425      * <strong>[icu]</strong> FieldPosition selector for 'B' field alignment.
426      * No related Calendar field.
427      * This displays the flexible day period.
428      */
429     public final static int FLEXIBLE_DAY_PERIOD_FIELD = 36;
430 
431     /**
432      * <strong>[icu]</strong> FieldPosition selector time separator,
433      * no related Calendar field. No pattern character is currently
434      * defined for this.
435      * @deprecated This API is ICU internal only.
436      * @hide draft / provisional / internal are hidden on OHOS
437      */
438     @Deprecated
439     public final static int TIME_SEPARATOR = 37;
440 
441     /**
442      * <strong>[icu]</strong> Number of FieldPosition selectors for DateFormat.
443      * Valid selectors range from 0 to FIELD_COUNT-1.
444      * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
445      * @hide unsupported on OHOS
446      */
447     @Deprecated
448     public final static int FIELD_COUNT = 38;
449     // A previous comment for the above stated that we must have
450     // DateFormat.FIELD_COUNT == DateFormatSymbols.patternChars.length()
451     // but that does not seem to be the case, and in fact since there is
452     // no pattern character currently defined for TIME_SEPARATOR it is
453     // currently the case that
454     // DateFormat.FIELD_COUNT == DateFormatSymbols.patternChars.length() + 1
455 
456 
457     /**
458      * boolean attributes
459      */
460     public enum BooleanAttribute {
461         /**
462          * indicates whitespace tolerance. Also included is trailing dot tolerance.
463          */
464         PARSE_ALLOW_WHITESPACE,
465         /**
466          * indicates tolerance of numeric data when String data may be assumed.
467          * e.g. YEAR_NAME_FIELD
468          */
469         PARSE_ALLOW_NUMERIC,
470         /**
471          * indicates tolerance of pattern mismatch between input data and specified format pattern.
472          * e.g. accepting "September" for a month pattern of MMM ("Sep")
473          */
474         PARSE_MULTIPLE_PATTERNS_FOR_MATCH,
475         /**
476          * indicates tolerance of a partial literal match
477          * e.g. accepting "--mon-02-march-2011" for a pattern of "'--: 'EEE-WW-MMMM-yyyy"
478          */
479         PARSE_PARTIAL_LITERAL_MATCH,
480         /**
481          * alias of PARSE_PARTIAL_LITERAL_MATCH
482          * @deprecated
483          * @hide draft / provisional / internal are hidden on OHOS
484          */
485         @Deprecated
486         PARSE_PARTIAL_MATCH
487     };
488 
489     /**
490      * boolean attributes for this instance. Inclusion in this is indicates a true condition.
491      */
492     private EnumSet<BooleanAttribute> booleanAttributes = EnumSet.allOf(BooleanAttribute.class);
493 
494     /**
495      * Hour Cycle
496      * @hide exposed on OHOS
497      * @hide draft / provisional / internal are hidden on OHOS
498      */
499     public enum HourCycle {
500         /**
501          * hour in am/pm (0~11)
502          * @hide draft / provisional / internal are hidden on OHOS
503          */
504         HOUR_CYCLE_11,
505 
506         /**
507          * hour in am/pm (1~12)
508          * @hide draft / provisional / internal are hidden on OHOS
509          */
510         HOUR_CYCLE_12,
511 
512         /**
513          * hour in day (0~23)
514          * @hide draft / provisional / internal are hidden on OHOS
515          */
516         HOUR_CYCLE_23,
517 
518         /**
519          * hour in day (1~24)
520          * @hide draft / provisional / internal are hidden on OHOS
521          */
522         HOUR_CYCLE_24;
523     };
524 
525     /*
526      * Capitalization setting, hoisted to DateFormat ICU 53
527      * Note that SimpleDateFormat serialization may call getContext/setContext to read/write
528      * this for compatibility with serialization for its old copy of capitalizationSetting.
529      * @serial
530      */
531     private DisplayContext capitalizationSetting = DisplayContext.CAPITALIZATION_NONE;
532 
533     static final int currentSerialVersion = 1;
534 
535     /**
536      * Describes the version of <code>DateFormat</code> present on the stream.
537      * Possible values are:
538      * <ul>
539      * <li><b>0</b> (or uninitialized): the pre-ICU-53 version
540      *
541      * <li><b>1</b>: ICU 53, adds serialVersionOnStream and capitalizationSetting
542      * </ul>
543      * When streaming out a <code>DateFormat</code>, the most recent format
544      * (corresponding to the highest allowable <code>serialVersionOnStream</code>)
545      * is always written.
546      *
547      * @serial
548      */
549     private int serialVersionOnStream = currentSerialVersion;
550 
551     // Proclaim serial compatibility with 1.1 FCS
552     private static final long serialVersionUID = 7218322306649953788L;
553 
554     /**
555      * Formats a time object into a time string. Examples of time objects
556      * are a time value expressed in milliseconds and a Date object.
557      * @param obj must be a Number or a Date or a Calendar.
558      * @param toAppendTo the string buffer for the returning time string.
559      * @return the formatted time string.
560      * @param fieldPosition keeps track of the position of the field
561      * within the returned string.
562      * On input: an alignment field,
563      * if desired. On output: the offsets of the alignment field. For
564      * example, given a time text "1996.07.10 AD at 15:08:56 PDT",
565      * if the given fieldPosition is DateFormat.YEAR_FIELD, the
566      * begin index and end index of fieldPosition will be set to
567      * 0 and 4, respectively.
568      * Notice that if the same time field appears
569      * more than once in a pattern, the fieldPosition will be set for the first
570      * occurrence of that time field. For instance, formatting a Date to
571      * the time string "1 PM PDT (Pacific Daylight Time)" using the pattern
572      * "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD,
573      * the begin index and end index of fieldPosition will be set to
574      * 5 and 8, respectively, for the first occurrence of the timezone
575      * pattern character 'z'.
576      * @see java.text.Format
577      */
578     @Override
format(Object obj, StringBuffer toAppendTo, FieldPosition fieldPosition)579     public final StringBuffer format(Object obj, StringBuffer toAppendTo,
580                                      FieldPosition fieldPosition)
581     {
582         if (obj instanceof Calendar)
583             return format( (Calendar)obj, toAppendTo, fieldPosition );
584         else if (obj instanceof Date)
585             return format( (Date)obj, toAppendTo, fieldPosition );
586         else if (obj instanceof Number)
587             return format( new Date(((Number)obj).longValue()),
588                           toAppendTo, fieldPosition );
589         else
590             throw new IllegalArgumentException("Cannot format given Object (" +
591                                                obj.getClass().getName() + ") as a Date");
592     }
593 
594     /**
595      * Formats a date into a date/time string.
596      * @param cal a Calendar set to the date and time to be formatted
597      * into a date/time string.  When the calendar type is different from
598      * the internal calendar held by this DateFormat instance, the date
599      * and the time zone will be inherited from the input calendar, but
600      * other calendar field values will be calculated by the internal calendar.
601      * @param toAppendTo the string buffer for the returning date/time string.
602      * @param fieldPosition keeps track of the position of the field
603      * within the returned string.
604      * On input: an alignment field,
605      * if desired. On output: the offsets of the alignment field. For
606      * example, given a time text "1996.07.10 AD at 15:08:56 PDT",
607      * if the given fieldPosition is DateFormat.YEAR_FIELD, the
608      * begin index and end index of fieldPosition will be set to
609      * 0 and 4, respectively.
610      * Notice that if the same time field appears
611      * more than once in a pattern, the fieldPosition will be set for the first
612      * occurrence of that time field. For instance, formatting a Date to
613      * the time string "1 PM PDT (Pacific Daylight Time)" using the pattern
614      * "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD,
615      * the begin index and end index of fieldPosition will be set to
616      * 5 and 8, respectively, for the first occurrence of the timezone
617      * pattern character 'z'.
618      * @return the formatted date/time string.
619      */
format(Calendar cal, StringBuffer toAppendTo, FieldPosition fieldPosition)620     public abstract StringBuffer format(Calendar cal, StringBuffer toAppendTo,
621                                         FieldPosition fieldPosition);
622 
623     /**
624      * Formats a Date into a date/time string.
625      * @param date a Date to be formatted into a date/time string.
626      * @param toAppendTo the string buffer for the returning date/time string.
627      * @param fieldPosition keeps track of the position of the field
628      * within the returned string.
629      * On input: an alignment field,
630      * if desired. On output: the offsets of the alignment field. For
631      * example, given a time text "1996.07.10 AD at 15:08:56 PDT",
632      * if the given fieldPosition is DateFormat.YEAR_FIELD, the
633      * begin index and end index of fieldPosition will be set to
634      * 0 and 4, respectively.
635      * Notice that if the same time field appears
636      * more than once in a pattern, the fieldPosition will be set for the first
637      * occurrence of that time field. For instance, formatting a Date to
638      * the time string "1 PM PDT (Pacific Daylight Time)" using the pattern
639      * "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD,
640      * the begin index and end index of fieldPosition will be set to
641      * 5 and 8, respectively, for the first occurrence of the timezone
642      * pattern character 'z'.
643      * @return the formatted date/time string.
644      */
format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition)645     public StringBuffer format(Date date, StringBuffer toAppendTo,
646                                      FieldPosition fieldPosition) {
647         // Use our Calendar object
648         calendar.setTime(date);
649         return format(calendar, toAppendTo, fieldPosition);
650     }
651 
652     /**
653      * Formats a Date into a date/time string.
654      * @param date the time value to be formatted into a time string.
655      * @return the formatted time string.
656      */
format(Date date)657     public final String format(Date date)
658     {
659         return format(date, new StringBuffer(64),new FieldPosition(0)).toString();
660     }
661 
662     /**
663      * Parses a date/time string. For example, a time text "07/10/96 4:5 PM, PDT"
664      * will be parsed into a Date that is equivalent to Date(837039928046).
665      * Parsing begins at the beginning of the string and proceeds as far as
666      * possible.  Assuming no parse errors were encountered, this function
667      * doesn't return any information about how much of the string was consumed
668      * by the parsing.  If you need that information, use a version of
669      * parse() that takes a ParsePosition.
670      *
671      * <p> By default, parsing is lenient: If the input is not in the form used
672      * by this object's format method but can still be parsed as a date, then
673      * the parse succeeds.  Clients may insist on strict adherence to the
674      * format by calling setLenient(false).
675      *
676      * <p> Note that the normal date formats associated with some calendars - such
677      * as the Chinese lunar calendar - do not specify enough fields to enable
678      * dates to be parsed unambiguously. In the case of the Chinese lunar
679      * calendar, while the year within the current 60-year cycle is specified,
680      * the number of such cycles since the start date of the calendar (in the
681      * ERA field of the Calendar object) is not normally part of the format,
682      * and parsing may assume the wrong era. For cases such as this it is
683      * recommended that clients parse using the parse method that takes a Calendar
684      * with the Calendar passed in set to the current date, or to a date
685      * within the era/cycle that should be assumed if absent in the format.
686      *
687      * @param text  The date/time string to be parsed
688      *
689      * @return      A Date, or null if the input could not be parsed
690      *
691      * @exception  ParseException  If the given string cannot be parsed as a date.
692      *
693      * @see #parse(String, ParsePosition)
694      */
parse(String text)695     public Date parse(String text) throws ParseException
696     {
697         ParsePosition pos = new ParsePosition(0);
698         Date result = parse(text, pos);
699         if (pos.getIndex() == 0) // ICU4J
700             throw new ParseException("Unparseable date: \"" + text + "\"" ,
701                                      pos.getErrorIndex()); // ICU4J
702         return result;
703     }
704 
705     /**
706      * Parses a date/time string according to the given parse position.
707      * For example, a time text "07/10/96 4:5 PM, PDT" will be parsed
708      * into a Calendar that is equivalent to Date(837039928046). Before
709      * calling this method the caller should initialize the calendar
710      * in one of two ways (unless existing field information is to be kept):
711      * (1) clear the calendar, or (2) set the calendar to the current date
712      * (or to any date whose fields should be used to supply values that
713      * are missing in the parsed date). For example, Chinese calendar dates
714      * do not normally provide an era/cycle; in this case the calendar that
715      * is passed in should be set to a date within the era that should be
716      * assumed, normally the current era.
717      *
718      * <p> By default, parsing is lenient: If the input is not in the form used
719      * by this object's format method but can still be parsed as a date, then
720      * the parse succeeds.  Clients may insist on strict adherence to the
721      * format by calling setLenient(false).
722      *
723      * @see #setLenient(boolean)
724      *
725      * @param text  The date/time string to be parsed
726      *
727      * @param cal   The calendar set on input to the date and time to be used
728      *              for missing values in the date/time string being parsed,
729      *              and set on output to the parsed date/time. In general, this
730      *              should be initialized before calling this method - either
731      *              cleared or set to the current date, depending on desired
732      *              behavior. If this parse fails, the calendar may still
733      *              have been modified. When the calendar type is different
734      *              from the internal calendar held by this DateFormat
735      *              instance, calendar field values will be parsed based
736      *              on the internal calendar initialized with the time and
737      *              the time zone taken from this calendar, then the
738      *              parse result (time in milliseconds and time zone) will
739      *              be set back to this calendar.
740      *
741      * @param pos   On input, the position at which to start parsing; on
742      *              output, the position at which parsing terminated, or the
743      *              start position if the parse failed.
744      */
parse(String text, Calendar cal, ParsePosition pos)745     public abstract void parse(String text, Calendar cal, ParsePosition pos);
746 
747     /**
748      * Parses a date/time string according to the given parse position.  For
749      * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date
750      * that is equivalent to Date(837039928046).
751      *
752      * <p> By default, parsing is lenient: If the input is not in the form used
753      * by this object's format method but can still be parsed as a date, then
754      * the parse succeeds.  Clients may insist on strict adherence to the
755      * format by calling setLenient(false).
756      *
757      * <p> Note that the normal date formats associated with some calendars - such
758      * as the Chinese lunar calendar - do not specify enough fields to enable
759      * dates to be parsed unambiguously. In the case of the Chinese lunar
760      * calendar, while the year within the current 60-year cycle is specified,
761      * the number of such cycles since the start date of the calendar (in the
762      * ERA field of the Calendar object) is not normally part of the format,
763      * and parsing may assume the wrong era. For cases such as this it is
764      * recommended that clients parse using the parse method that takes a Calendar
765      * with the Calendar passed in set to the current date, or to a date
766      * within the era/cycle that should be assumed if absent in the format.
767      *
768      * @see #setLenient(boolean)
769      *
770      * @param text  The date/time string to be parsed
771      *
772      * @param pos   On input, the position at which to start parsing; on
773      *              output, the position at which parsing terminated, or the
774      *              start position if the parse failed.
775      *
776      * @return      A Date, or null if the input could not be parsed
777      */
parse(String text, ParsePosition pos)778     public Date parse(String text, ParsePosition pos) {
779         Date result = null;
780         int start = pos.getIndex();
781         TimeZone tzsav = calendar.getTimeZone();
782         calendar.clear();
783         parse(text, calendar, pos);
784         if (pos.getIndex() != start) {
785             try {
786                 result = calendar.getTime();
787             } catch (IllegalArgumentException e) {
788                 // This occurs if the calendar is non-lenient and there is
789                 // an out-of-range field.  We don't know which field was
790                 // illegal so we set the error index to the start.
791                 pos.setIndex(start);
792                 pos.setErrorIndex(start);
793             }
794         }
795         // Restore TimeZone
796         calendar.setTimeZone(tzsav);
797         return result;
798     }
799 
800     /**
801      * Parses a date/time string into an Object.  This convenience method simply
802      * calls parse(String, ParsePosition).
803      *
804      * @see #parse(String, ParsePosition)
805      */
806     @Override
parseObject(String source, ParsePosition pos)807     public Object parseObject (String source, ParsePosition pos)
808     {
809         return parse(source, pos);
810     }
811 
812     /**
813      * <strong>[icu]</strong> Constant for empty style pattern.
814      */
815     public static final int NONE = -1;
816 
817     /**
818      * Constant for full style pattern.
819      */
820     public static final int FULL = 0;
821 
822     /**
823      * Constant for long style pattern.
824      */
825     public static final int LONG = 1;
826 
827     /**
828      * Constant for medium style pattern.
829      */
830     public static final int MEDIUM = 2;
831 
832     /**
833      * Constant for short style pattern.
834      */
835     public static final int SHORT = 3;
836 
837     /**
838      * Constant for default style pattern.  Its value is MEDIUM.
839      */
840     public static final int DEFAULT = MEDIUM;
841 
842     /**
843      * <strong>[icu]</strong> Constant for relative style mask.
844      */
845     public static final int RELATIVE = (1 << 7);
846 
847     /**
848      * <strong>[icu]</strong> Constant for relative full style pattern.
849      */
850     public static final int RELATIVE_FULL = RELATIVE | FULL;
851 
852     /**
853      * <strong>[icu]</strong> Constant for relative style pattern.
854      */
855     public static final int RELATIVE_LONG = RELATIVE | LONG;
856 
857     /**
858      * <strong>[icu]</strong> Constant for relative style pattern.
859      */
860     public static final int RELATIVE_MEDIUM = RELATIVE | MEDIUM;
861 
862     /**
863      * <strong>[icu]</strong> Constant for relative style pattern.
864      */
865     public static final int RELATIVE_SHORT = RELATIVE | SHORT;
866 
867     /**
868      * <strong>[icu]</strong> Constant for relative default style pattern.
869      */
870     public static final int RELATIVE_DEFAULT = RELATIVE | DEFAULT;
871 
872     /*
873      * DATES
874      */
875 
876     /**
877      * <strong>[icu]</strong> Constant for date skeleton with year.
878      */
879     public static final String YEAR = "y";
880 
881     /**
882      * <strong>[icu]</strong> Constant for date skeleton with quarter.
883      */
884     public static final String QUARTER = "QQQQ";
885 
886     /**
887      * <strong>[icu]</strong> Constant for date skeleton with abbreviated quarter.
888      */
889     public static final String ABBR_QUARTER = "QQQ";
890 
891     /**
892      * <strong>[icu]</strong> Constant for date skeleton with year and quarter.
893      */
894     public static final String YEAR_QUARTER = "yQQQQ";
895 
896     /**
897      * <strong>[icu]</strong> Constant for date skeleton with year and abbreviated quarter.
898      */
899     public static final String YEAR_ABBR_QUARTER = "yQQQ";
900 
901     /**
902      * <strong>[icu]</strong> Constant for date skeleton with month.
903      */
904     public static final String MONTH = "MMMM";
905 
906     /**
907      * <strong>[icu]</strong> Constant for date skeleton with abbreviated month.
908      */
909     public static final String ABBR_MONTH = "MMM";
910 
911     /**
912      * <strong>[icu]</strong> Constant for date skeleton with numeric month.
913      */
914     public static final String NUM_MONTH = "M";
915 
916     /**
917      * <strong>[icu]</strong> Constant for date skeleton with year and month.
918      */
919     public static final String YEAR_MONTH = "yMMMM";
920 
921     /**
922      * <strong>[icu]</strong> Constant for date skeleton with year and abbreviated month.
923      */
924     public static final String YEAR_ABBR_MONTH = "yMMM";
925 
926     /**
927      * <strong>[icu]</strong> Constant for date skeleton with year and numeric month.
928      */
929     public static final String YEAR_NUM_MONTH = "yM";
930 
931     /**
932      * <strong>[icu]</strong> Constant for date skeleton with day.
933      */
934     public static final String DAY = "d";
935 
936     /**
937      * <strong>[icu]</strong> Constant for date skeleton with year, month, and day.
938      * Used in combinations date + time, date + time + zone, or time + zone.
939      */
940     public static final String YEAR_MONTH_DAY = "yMMMMd";
941 
942     /**
943      * <strong>[icu]</strong> Constant for date skeleton with year, abbreviated month, and day.
944      * Used in combinations date + time, date + time + zone, or time + zone.
945      */
946     public static final String YEAR_ABBR_MONTH_DAY = "yMMMd";
947 
948     /**
949      * <strong>[icu]</strong> Constant for date skeleton with year, numeric month, and day.
950      * Used in combinations date + time, date + time + zone, or time + zone.
951      */
952     public static final String YEAR_NUM_MONTH_DAY = "yMd";
953 
954     /**
955      * <strong>[icu]</strong> Constant for date skeleton with weekday.
956      */
957     public static final String WEEKDAY = "EEEE";
958 
959     /**
960      * <strong>[icu]</strong> Constant for date skeleton with abbreviated weekday.
961      */
962     public static final String ABBR_WEEKDAY = "E";
963 
964     /**
965      * <strong>[icu]</strong> Constant for date skeleton with year, month, weekday, and day.
966      * Used in combinations date + time, date + time + zone, or time + zone.
967      */
968     public static final String YEAR_MONTH_WEEKDAY_DAY = "yMMMMEEEEd";
969 
970     /**
971      * <strong>[icu]</strong> Constant for date skeleton with year, abbreviated month, weekday, and day.
972      * Used in combinations date + time, date + time + zone, or time + zone.
973      */
974     public static final String YEAR_ABBR_MONTH_WEEKDAY_DAY = "yMMMEd";
975 
976     /**
977      * <strong>[icu]</strong> Constant for date skeleton with year, numeric month, weekday, and day.
978      * Used in combinations date + time, date + time + zone, or time + zone.
979      */
980     public static final String YEAR_NUM_MONTH_WEEKDAY_DAY = "yMEd";
981 
982     /**
983      * <strong>[icu]</strong> Constant for date skeleton with long month and day.
984      * Used in combinations date + time, date + time + zone, or time + zone.
985      */
986     public static final String MONTH_DAY = "MMMMd";
987 
988     /**
989      * <strong>[icu]</strong> Constant for date skeleton with abbreviated month and day.
990      * Used in combinations date + time, date + time + zone, or time + zone.
991      */
992     public static final String ABBR_MONTH_DAY = "MMMd";
993 
994     /**
995      * <strong>[icu]</strong> Constant for date skeleton with numeric month and day.
996      * Used in combinations date + time, date + time + zone, or time + zone.
997      */
998     public static final String NUM_MONTH_DAY = "Md";
999 
1000     /**
1001      * <strong>[icu]</strong> Constant for date skeleton with month, weekday, and day.
1002      * Used in combinations date + time, date + time + zone, or time + zone.
1003      */
1004     public static final String MONTH_WEEKDAY_DAY = "MMMMEEEEd";
1005 
1006     /**
1007      * <strong>[icu]</strong> Constant for date skeleton with abbreviated month, weekday, and day.
1008      * Used in combinations date + time, date + time + zone, or time + zone.
1009      */
1010     public static final String ABBR_MONTH_WEEKDAY_DAY = "MMMEd";
1011 
1012     /**
1013      * <strong>[icu]</strong> Constant for date skeleton with numeric month, weekday, and day.
1014      * Used in combinations date + time, date + time + zone, or time + zone.
1015      */
1016     public static final String NUM_MONTH_WEEKDAY_DAY = "MEd";
1017 
1018     /**
1019      * List of all of the date skeleton constants for iteration.
1020      * Note that this is fragile; be sure to add any values that are added above.
1021      * @deprecated This API is ICU internal only.
1022      * @hide deprecated on icu4j-org
1023      * @hide draft / provisional / internal are hidden on OHOS
1024      */
1025     @Deprecated
1026     public static final List<String> DATE_SKELETONS = Arrays.asList(
1027             YEAR,
1028             QUARTER,
1029             ABBR_QUARTER,
1030             YEAR_QUARTER,
1031             YEAR_ABBR_QUARTER,
1032             MONTH,
1033             ABBR_MONTH,
1034             NUM_MONTH,
1035             YEAR_MONTH,
1036             YEAR_ABBR_MONTH,
1037             YEAR_NUM_MONTH,
1038             DAY,
1039             YEAR_MONTH_DAY,
1040             YEAR_ABBR_MONTH_DAY,
1041             YEAR_NUM_MONTH_DAY,
1042             WEEKDAY,
1043             ABBR_WEEKDAY,
1044             YEAR_MONTH_WEEKDAY_DAY,
1045             YEAR_ABBR_MONTH_WEEKDAY_DAY,
1046             YEAR_NUM_MONTH_WEEKDAY_DAY,
1047             MONTH_DAY,
1048             ABBR_MONTH_DAY,
1049             NUM_MONTH_DAY,
1050             MONTH_WEEKDAY_DAY,
1051             ABBR_MONTH_WEEKDAY_DAY,
1052             NUM_MONTH_WEEKDAY_DAY);
1053 
1054     /*
1055      * TIMES
1056      */
1057 
1058     /**
1059      * <strong>[icu]</strong> Constant for date skeleton with hour, with the locale's preferred hour format (12 or 24).
1060      */
1061     public static final String HOUR = "j";
1062 
1063     /**
1064      * <strong>[icu]</strong> Constant for date skeleton with hour in 24-hour presentation.
1065      */
1066     public static final String HOUR24 = "H";
1067 
1068     /**
1069      * <strong>[icu]</strong> Constant for date skeleton with minute.
1070      */
1071     public static final String MINUTE = "m";
1072 
1073     /**
1074      * <strong>[icu]</strong> Constant for date skeleton with hour and minute, with the locale's preferred hour format (12 or 24).
1075      * Used in combinations date + time, date + time + zone, or time + zone.
1076      */
1077     public static final String HOUR_MINUTE = "jm";
1078 
1079     /**
1080      * <strong>[icu]</strong> Constant for date skeleton with hour and minute in 24-hour presentation.
1081      * Used in combinations date + time, date + time + zone, or time + zone.
1082      */
1083     public static final String HOUR24_MINUTE = "Hm";
1084 
1085     /**
1086      * <strong>[icu]</strong> Constant for date skeleton with second.
1087      */
1088     public static final String SECOND = "s";
1089 
1090     /**
1091      * <strong>[icu]</strong> Constant for date skeleton with hour, minute, and second,
1092      * with the locale's preferred hour format (12 or 24).
1093      * Used in combinations date + time, date + time + zone, or time + zone.
1094      */
1095     public static final String HOUR_MINUTE_SECOND = "jms";
1096 
1097     /**
1098      * <strong>[icu]</strong> Constant for date skeleton with hour, minute, and second in
1099      * 24-hour presentation.
1100      * Used in combinations date + time, date + time + zone, or time + zone.
1101      */
1102     public static final String HOUR24_MINUTE_SECOND = "Hms";
1103 
1104     /**
1105      * <strong>[icu]</strong> Constant for date skeleton with minute and second.
1106      * Used in combinations date + time, date + time + zone, or time + zone.
1107      */
1108     public static final String MINUTE_SECOND = "ms";
1109 
1110     /**
1111      * List of all of the time skeleton constants for iteration.
1112      * Note that this is fragile; be sure to add any values that are added above.
1113      * @deprecated This API is ICU internal only.
1114      * @hide deprecated on icu4j-org
1115      * @hide draft / provisional / internal are hidden on OHOS
1116      */
1117     @Deprecated
1118     public static final List<String> TIME_SKELETONS = Arrays.asList(
1119             HOUR,
1120             HOUR24,
1121             MINUTE,
1122             HOUR_MINUTE,
1123             HOUR24_MINUTE,
1124             SECOND,
1125             HOUR_MINUTE_SECOND,
1126             HOUR24_MINUTE_SECOND,
1127             MINUTE_SECOND);
1128 
1129     /*
1130      * TIMEZONES
1131      */
1132 
1133     /**
1134      * <strong>[icu]</strong> Constant for <i>generic location format</i>, such as Los Angeles Time;
1135      * used in combinations date + time + zone, or time + zone.
1136      * @see <a href="http://unicode.org/reports/tr35/#Date_Format_Patterns">LDML Date Format Patterns</a>
1137      * @see <a href="http://unicode.org/reports/tr35/#Time_Zone_Fallback">LDML Time Zone Fallback</a>
1138      */
1139     public static final String LOCATION_TZ = "VVVV";
1140 
1141     /**
1142      * <strong>[icu]</strong> Constant for <i>generic non-location format</i>, such as Pacific Time;
1143      * used in combinations date + time + zone, or time + zone.
1144      * @see <a href="http://unicode.org/reports/tr35/#Date_Format_Patterns">LDML Date Format Patterns</a>
1145      * @see <a href="http://unicode.org/reports/tr35/#Time_Zone_Fallback">LDML Time Zone Fallback</a>
1146      */
1147     public static final String GENERIC_TZ = "vvvv";
1148 
1149     /**
1150      * <strong>[icu]</strong> Constant for <i>generic non-location format</i>, abbreviated if possible, such as PT;
1151      * used in combinations date + time + zone, or time + zone.
1152      * @see <a href="http://unicode.org/reports/tr35/#Date_Format_Patterns">LDML Date Format Patterns</a>
1153      * @see <a href="http://unicode.org/reports/tr35/#Time_Zone_Fallback">LDML Time Zone Fallback</a>
1154      */
1155     public static final String ABBR_GENERIC_TZ = "v";
1156 
1157     /**
1158      * <strong>[icu]</strong> Constant for <i>specific non-location format</i>, such as Pacific Daylight Time;
1159      * used in combinations date + time + zone, or time + zone.
1160      * @see <a href="http://unicode.org/reports/tr35/#Date_Format_Patterns">LDML Date Format Patterns</a>
1161      * @see <a href="http://unicode.org/reports/tr35/#Time_Zone_Fallback">LDML Time Zone Fallback</a>
1162      */
1163     public static final String SPECIFIC_TZ = "zzzz";
1164 
1165     /**
1166      * <strong>[icu]</strong> Constant for <i>specific non-location format</i>, abbreviated if possible, such as PDT;
1167      * used in combinations date + time + zone, or time + zone.
1168      * @see <a href="http://unicode.org/reports/tr35/#Date_Format_Patterns">LDML Date Format Patterns</a>
1169      * @see <a href="http://unicode.org/reports/tr35/#Time_Zone_Fallback">LDML Time Zone Fallback</a>
1170      */
1171     public static final String ABBR_SPECIFIC_TZ = "z";
1172 
1173     /**
1174      * <strong>[icu]</strong> Constant for <i>localized GMT/UTC format</i>, such as GMT+8:00 or HPG-8:00;
1175      * used in combinations date + time + zone, or time + zone.
1176      * @see <a href="http://unicode.org/reports/tr35/#Date_Format_Patterns">LDML Date Format Patterns</a>
1177      * @see <a href="http://unicode.org/reports/tr35/#Time_Zone_Fallback">LDML Time Zone Fallback</a>
1178      */
1179     public static final String ABBR_UTC_TZ = "ZZZZ";
1180 
1181     /**
1182      * List of all of the zone skeleton constants for iteration.
1183      * Note that this is fragile; be sure to add any values that are added above.
1184      * @deprecated This API is ICU internal only.
1185      * @hide deprecated on icu4j-org
1186      * @hide draft / provisional / internal are hidden on OHOS
1187      */
1188     @Deprecated
1189     public static final List<String> ZONE_SKELETONS = Arrays.asList(
1190             LOCATION_TZ,
1191             GENERIC_TZ,
1192             ABBR_GENERIC_TZ,
1193             SPECIFIC_TZ,
1194             ABBR_SPECIFIC_TZ,
1195             ABBR_UTC_TZ);
1196 
1197     /*
1198      * deprecated skeleton constants
1199      */
1200 
1201     /**
1202      * <strong>[icu]</strong> Constant for date skeleton with standalone month.
1203      * @deprecated ICU 50 Use {@link #MONTH} instead.
1204      * @hide deprecated on icu4j-org
1205      */
1206     @Deprecated
1207     public static final String STANDALONE_MONTH = "LLLL";
1208 
1209     /**
1210      * <strong>[icu]</strong> Constant for date skeleton with standalone abbreviated month.
1211      * @deprecated ICU 50 Use {@link #ABBR_MONTH} instead.
1212      * @hide deprecated on icu4j-org
1213      */
1214     @Deprecated
1215     public static final String ABBR_STANDALONE_MONTH = "LLL";
1216 
1217     /**
1218      * <strong>[icu]</strong> Constant for date skeleton with hour, minute, and generic timezone.
1219      * @deprecated ICU 50 Use instead {@link #HOUR_MINUTE}+{@link #ABBR_GENERIC_TZ} or some other timezone presentation.
1220      * @hide deprecated on icu4j-org
1221      */
1222     @Deprecated
1223     public static final String HOUR_MINUTE_GENERIC_TZ = "jmv";
1224 
1225     /**
1226      * <strong>[icu]</strong> Constant for date skeleton with hour, minute, and timezone.
1227      * @deprecated ICU 50 Use instead {@link #HOUR_MINUTE}+{@link #ABBR_SPECIFIC_TZ} or some other timezone presentation.
1228      * @hide deprecated on icu4j-org
1229      */
1230     @Deprecated
1231     public static final String HOUR_MINUTE_TZ = "jmz";
1232 
1233     /**
1234      * <strong>[icu]</strong> Constant for date skeleton with hour and generic timezone.
1235      * @deprecated ICU 50 Use instead {@link #HOUR}+{@link #ABBR_GENERIC_TZ} or some other timezone presentation.
1236      * @hide deprecated on icu4j-org
1237      */
1238     @Deprecated
1239     public static final String HOUR_GENERIC_TZ = "jv";
1240 
1241     /**
1242      * <strong>[icu]</strong> Constant for date skeleton with hour and timezone.
1243      * @deprecated ICU 50 Use instead {@link #HOUR}+{@link #ABBR_SPECIFIC_TZ} or some other timezone presentation.
1244      * @hide deprecated on icu4j-org
1245      */
1246     @Deprecated
1247     public static final String HOUR_TZ = "jz";
1248 
1249     /**
1250      * Constant for Unicode string name of new (in 2019) Japanese calendar era,
1251      * root/English abbreviated version (ASCII-range characters).
1252      * @deprecated This API is ICU internal only.
1253      * @hide draft / provisional / internal are hidden on OHOS
1254      */
1255     @Deprecated
1256     public static final String JP_ERA_2019_ROOT = "Reiwa";
1257 
1258     /**
1259      * Constant for Unicode string name of new (in 2019) Japanese calendar era,
1260      * Japanese abbreviated version (Han, or fullwidth Latin for testing).
1261      * @deprecated This API is ICU internal only.
1262      * @hide draft / provisional / internal are hidden on OHOS
1263      */
1264     @Deprecated
1265     public static final String JP_ERA_2019_JA = "\u4EE4\u548C";
1266 
1267     /**
1268      * Constant for Unicode string name of new (in 2019) Japanese calendar era,
1269      * root and Japanese narrow version (ASCII-range characters).
1270      * @deprecated This API is ICU internal only.
1271      * @hide draft / provisional / internal are hidden on OHOS
1272      */
1273     @Deprecated
1274     public static final String JP_ERA_2019_NARROW = "R";
1275 
1276     /**
1277      * Gets the time formatter with the default formatting style
1278      * for the default <code>FORMAT</code> locale.
1279      * @return a time formatter.
1280      * @see Category#FORMAT
1281      */
getTimeInstance()1282     public final static DateFormat getTimeInstance()
1283     {
1284         return get(-1, DEFAULT, ULocale.getDefault(Category.FORMAT), null);
1285     }
1286 
1287     /**
1288      * Returns the time formatter with the given formatting style
1289      * for the default <code>FORMAT</code> locale.
1290      * @param style the given formatting style. For example,
1291      * SHORT for "h:mm a" in the US locale. Relative time styles are not currently
1292      * supported, and behave just like the corresponding non-relative style.
1293      * @return a time formatter.
1294      * @see Category#FORMAT
1295      */
getTimeInstance(int style)1296     public final static DateFormat getTimeInstance(int style)
1297     {
1298         return get(-1, style, ULocale.getDefault(Category.FORMAT), null);
1299     }
1300 
1301     /**
1302      * Returns the time formatter with the given formatting style
1303      * for the given locale.
1304      * @param style the given formatting style. For example,
1305      * SHORT for "h:mm a" in the US locale. Relative time styles are not currently
1306      * supported, and behave just like the corresponding non-relative style.
1307      * @param aLocale the given locale.
1308      * @return a time formatter.
1309      */
getTimeInstance(int style, Locale aLocale)1310     public final static DateFormat getTimeInstance(int style,
1311                                                  Locale aLocale)
1312     {
1313         return get(-1, style, ULocale.forLocale(aLocale), null);
1314     }
1315 
1316     /**
1317      * Returns the time formatter with the given formatting style
1318      * for the given locale.
1319      * @param style the given formatting style. For example,
1320      * SHORT for "h:mm a" in the US locale. Relative time styles are not currently
1321      * supported, and behave just like the corresponding non-relative style.
1322      * @param locale the given ulocale.
1323      * @return a time formatter.
1324      */
getTimeInstance(int style, ULocale locale)1325     public final static DateFormat getTimeInstance(int style,
1326                                                  ULocale locale)
1327     {
1328         return get(-1, style, locale, null);
1329     }
1330 
1331     /**
1332      * Returns the date formatter with the default formatting style
1333      * for the default <code>FORMAT</code> locale.
1334      * @return a date formatter.
1335      * @see Category#FORMAT
1336      */
getDateInstance()1337     public final static DateFormat getDateInstance()
1338     {
1339         return get(DEFAULT, -1, ULocale.getDefault(Category.FORMAT), null);
1340     }
1341 
1342     /**
1343      * Returns the date formatter with the given formatting style
1344      * for the default <code>FORMAT</code> locale.
1345      * @param style the given formatting style. For example,
1346      * SHORT for "M/d/yy" in the US locale. As currently implemented, relative date
1347      * formatting only affects a limited range of calendar days before or after the
1348      * current date, based on the CLDR &lt;field type="day"&gt;/&lt;relative&gt; data: For example,
1349      * in English, "Yesterday", "Today", and "Tomorrow". Outside of this range, relative
1350      * dates are formatted using the corresponding non-relative style.
1351      * @return a date formatter.
1352      * @see Category#FORMAT
1353      */
getDateInstance(int style)1354     public final static DateFormat getDateInstance(int style)
1355     {
1356         return get(style, -1, ULocale.getDefault(Category.FORMAT), null);
1357     }
1358 
1359     /**
1360      * Returns the date formatter with the given formatting style
1361      * for the given locale.
1362      * @param style the given formatting style. For example,
1363      * SHORT for "M/d/yy" in the US locale. As currently implemented, relative date
1364      * formatting only affects a limited range of calendar days before or after the
1365      * current date, based on the CLDR &lt;field type="day"&gt;/&lt;relative&gt; data: For example,
1366      * in English, "Yesterday", "Today", and "Tomorrow". Outside of this range, relative
1367      * dates are formatted using the corresponding non-relative style.
1368      * @param aLocale the given locale.
1369      * @return a date formatter.
1370      */
getDateInstance(int style, Locale aLocale)1371     public final static DateFormat getDateInstance(int style,
1372                                                  Locale aLocale)
1373     {
1374         return get(style, -1, ULocale.forLocale(aLocale), null);
1375     }
1376 
1377     /**
1378      * Returns the date formatter with the given formatting style
1379      * for the given locale.
1380      * @param style the given formatting style. For example,
1381      * SHORT for "M/d/yy" in the US locale. As currently implemented, relative date
1382      * formatting only affects a limited range of calendar days before or after the
1383      * current date, based on the CLDR &lt;field type="day"&gt;/&lt;relative&gt; data: For example,
1384      * in English, "Yesterday", "Today", and "Tomorrow". Outside of this range, relative
1385      * dates are formatted using the corresponding non-relative style.
1386      * @param locale the given ulocale.
1387      * @return a date formatter.
1388      */
getDateInstance(int style, ULocale locale)1389     public final static DateFormat getDateInstance(int style,
1390                                                  ULocale locale)
1391     {
1392         return get(style, -1, locale, null);
1393     }
1394 
1395     /**
1396      * Returns the date/time formatter with the default formatting style
1397      * for the default <code>FORMAT</code> locale.
1398      * @return a date/time formatter.
1399      * @see Category#FORMAT
1400      */
getDateTimeInstance()1401     public final static DateFormat getDateTimeInstance()
1402     {
1403         return get(DEFAULT, DEFAULT, ULocale.getDefault(Category.FORMAT), null);
1404     }
1405 
1406     /**
1407      * Returns the date/time formatter with the given date and time
1408      * formatting styles for the default <code>FORMAT</code> locale.
1409      * @param dateStyle the given date formatting style. For example,
1410      * SHORT for "M/d/yy" in the US locale. As currently implemented, relative date
1411      * formatting only affects a limited range of calendar days before or after the
1412      * current date, based on the CLDR &lt;field type="day"&gt;/&lt;relative&gt; data: For example,
1413      * in English, "Yesterday", "Today", and "Tomorrow". Outside of this range, relative
1414      * dates are formatted using the corresponding non-relative style.
1415      * @param timeStyle the given time formatting style. For example,
1416      * SHORT for "h:mm a" in the US locale. Relative time styles are not currently
1417      * supported, and behave just like the corresponding non-relative style.
1418      * @return a date/time formatter.
1419      * @see Category#FORMAT
1420      */
getDateTimeInstance(int dateStyle, int timeStyle)1421     public final static DateFormat getDateTimeInstance(int dateStyle,
1422                                                        int timeStyle)
1423     {
1424         return get(dateStyle, timeStyle, ULocale.getDefault(Category.FORMAT), null);
1425     }
1426 
1427     /**
1428      * Returns the date/time formatter with the given formatting styles
1429      * for the given locale.
1430      * @param dateStyle the given date formatting style. As currently implemented, relative date
1431      * formatting only affects a limited range of calendar days before or after the
1432      * current date, based on the CLDR &lt;field type="day"&gt;/&lt;relative&gt; data: For example,
1433      * in English, "Yesterday", "Today", and "Tomorrow". Outside of this range, relative
1434      * dates are formatted using the corresponding non-relative style.
1435      * @param timeStyle the given time formatting style. Relative time styles are not
1436      * currently supported, and behave just like the corresponding non-relative style.
1437      * @param aLocale the given locale.
1438      * @return a date/time formatter.
1439      */
getDateTimeInstance( int dateStyle, int timeStyle, Locale aLocale)1440     public final static DateFormat getDateTimeInstance(
1441         int dateStyle, int timeStyle, Locale aLocale)
1442     {
1443         return get(dateStyle, timeStyle, ULocale.forLocale(aLocale), null);
1444     }
1445 
1446     /**
1447      * Returns the date/time formatter with the given formatting styles
1448      * for the given locale.
1449      * @param dateStyle the given date formatting style. As currently implemented, relative date
1450      * formatting only affects a limited range of calendar days before or after the
1451      * current date, based on the CLDR &lt;field type="day"&gt;/&lt;relative&gt; data: For example,
1452      * in English, "Yesterday", "Today", and "Tomorrow". Outside of this range, relative
1453      * dates are formatted using the corresponding non-relative style.
1454      * @param timeStyle the given time formatting style. Relative time styles are not
1455      * currently supported, and behave just like the corresponding non-relative style.
1456      * @param locale the given ulocale.
1457      * @return a date/time formatter.
1458      */
getDateTimeInstance( int dateStyle, int timeStyle, ULocale locale)1459     public final static DateFormat getDateTimeInstance(
1460         int dateStyle, int timeStyle, ULocale locale)
1461     {
1462         return get(dateStyle, timeStyle, locale, null);
1463     }
1464 
1465     /**
1466      * Returns a default date/time formatter that uses the SHORT style for both the
1467      * date and the time.
1468      */
getInstance()1469     public final static DateFormat getInstance() {
1470         return getDateTimeInstance(SHORT, SHORT);
1471     }
1472 
1473     /**
1474      * Returns the set of locales for which DateFormats are installed.
1475      * @return the set of locales for which DateFormats are installed.
1476      */
getAvailableLocales()1477     public static Locale[] getAvailableLocales()
1478     {
1479         return ICUResourceBundle.getAvailableLocales();
1480     }
1481 
1482     /**
1483      * <strong>[icu]</strong> Returns the set of locales for which DateFormats are installed.
1484      * @return the set of locales for which DateFormats are installed.
1485      * @hide draft / provisional / internal are hidden on OHOS
1486      */
getAvailableULocales()1487     public static ULocale[] getAvailableULocales()
1488     {
1489         return ICUResourceBundle.getAvailableULocales();
1490     }
1491 
1492     /**
1493      * Sets the calendar to be used by this date format.  Initially, the default
1494      * calendar for the specified or default locale is used.
1495      * @param newCalendar the new Calendar to be used by the date format
1496      */
setCalendar(Calendar newCalendar)1497     public void setCalendar(Calendar newCalendar)
1498     {
1499         this.calendar = newCalendar;
1500     }
1501 
1502     /**
1503      * Returns the calendar associated with this date/time formatter.
1504      * @return the calendar associated with this date/time formatter.
1505      */
getCalendar()1506     public Calendar getCalendar()
1507     {
1508         return calendar;
1509     }
1510 
1511     /**
1512      * Sets the number formatter.
1513      * @param newNumberFormat the given new NumberFormat.
1514      */
setNumberFormat(NumberFormat newNumberFormat)1515     public void setNumberFormat(NumberFormat newNumberFormat)
1516     {
1517         numberFormat = (NumberFormat)newNumberFormat.clone();
1518         fixNumberFormatForDates(numberFormat);
1519     }
1520 
1521     // no matter what the locale's default number format looked like, we want
1522     // to modify it so that it doesn't use thousands separators, doesn't always
1523     // show the decimal point, and recognizes integers only when parsing
fixNumberFormatForDates(NumberFormat nf)1524     static void fixNumberFormatForDates(NumberFormat nf) {
1525         nf.setGroupingUsed(false);
1526         if (nf instanceof DecimalFormat) {
1527             ((DecimalFormat)nf).setDecimalSeparatorAlwaysShown(false);
1528         }
1529         nf.setParseIntegerOnly(true);
1530         nf.setMinimumFractionDigits(0);
1531     }
1532 
1533     /**
1534      * Returns the number formatter which this date/time formatter uses to
1535      * format and parse a time.
1536      * @return the number formatter which this date/time formatter uses.
1537      */
getNumberFormat()1538     public NumberFormat getNumberFormat()
1539     {
1540         return numberFormat;
1541     }
1542 
1543     /**
1544      * Sets the time zone for the calendar of this DateFormat object.
1545      * @param zone the given new time zone.
1546      */
setTimeZone(TimeZone zone)1547     public void setTimeZone(TimeZone zone)
1548     {
1549         calendar.setTimeZone(zone);
1550     }
1551 
1552     /**
1553      * Returns the time zone.
1554      * @return the time zone associated with the calendar of DateFormat.
1555      */
getTimeZone()1556     public TimeZone getTimeZone()
1557     {
1558         return calendar.getTimeZone();
1559     }
1560 
1561     /**
1562      * Specifies whether date/time parsing is to be lenient.  With
1563      * lenient parsing, the parser may use heuristics to interpret inputs that
1564      * do not precisely match this object's format.  Without lenient parsing,
1565      * inputs must match this object's format more closely.
1566      * <br><br>
1567      * <b>Note:</b> ICU 53 introduced finer grained control of leniency (and added
1568      * new control points) making the preferred method a combination of
1569      * setCalendarLenient() &amp; setBooleanAttribute() calls.
1570      * This method supports prior functionality but may not support all
1571      * future leniency control &amp; behavior of DateFormat. For control of pre 53 leniency,
1572      * Calendar and DateFormat whitespace &amp; numeric tolerance, this method is safe to
1573      * use. However, mixing leniency control via this method and modification of the
1574      * newer attributes via setBooleanAttribute() may produce undesirable
1575      * results.
1576      *
1577      * @param lenient True specifies date/time interpretation to be lenient.
1578      * @see ohos.global.icu.util.Calendar#setLenient
1579      * @see #setBooleanAttribute(BooleanAttribute, boolean)
1580      * @see #setCalendarLenient(boolean)
1581      */
setLenient(boolean lenient)1582     public void setLenient(boolean lenient)
1583     {
1584         calendar.setLenient(lenient);
1585         setBooleanAttribute(BooleanAttribute.PARSE_ALLOW_NUMERIC, lenient);
1586         setBooleanAttribute(BooleanAttribute.PARSE_ALLOW_WHITESPACE, lenient);
1587     }
1588 
1589     /**
1590      * Returns whether both date/time parsing in the encapsulated Calendar object and DateFormat whitespace &amp;
1591      * numeric processing is lenient.
1592      */
isLenient()1593     public boolean isLenient()
1594     {
1595         return calendar.isLenient()
1596                 && getBooleanAttribute(BooleanAttribute.PARSE_ALLOW_NUMERIC)
1597                 && getBooleanAttribute(BooleanAttribute.PARSE_ALLOW_WHITESPACE);
1598     }
1599 
1600     /**
1601      * Specifies whether date/time parsing in the encapsulated Calendar object should be lenient.
1602      * With lenient parsing, the parser may use heuristics to interpret inputs that
1603      * do not precisely match this object's format.  Without lenient parsing,
1604      * inputs must match this object's format more closely.
1605      * @param lenient when true, Calendar parsing is lenient
1606      * @see ohos.global.icu.util.Calendar#setLenient
1607      */
setCalendarLenient(boolean lenient)1608     public void setCalendarLenient(boolean lenient)
1609     {
1610         calendar.setLenient(lenient);
1611     }
1612 
1613 
1614     /**
1615      * Returns whether date/time parsing in the encapsulated Calendar object is lenient.
1616      */
isCalendarLenient()1617     public boolean isCalendarLenient()
1618     {
1619         return calendar.isLenient();
1620     }
1621 
1622     /**
1623      * Sets a boolean attribute for this instance. Aspects of DateFormat leniency are controlled by
1624      * boolean attributes.
1625      *
1626      * @see BooleanAttribute
1627      */
setBooleanAttribute(BooleanAttribute key, boolean value)1628     public DateFormat setBooleanAttribute(BooleanAttribute key, boolean value)
1629     {
1630         if(key.equals(DateFormat.BooleanAttribute.PARSE_PARTIAL_MATCH)) {
1631             key = DateFormat.BooleanAttribute.PARSE_PARTIAL_LITERAL_MATCH;
1632         }
1633         if(value)
1634         {
1635             booleanAttributes.add(key);
1636         }
1637         else
1638         {
1639             booleanAttributes.remove(key);
1640         }
1641 
1642         return this;
1643     }
1644 
1645     /**
1646      * Returns the current value for the specified BooleanAttribute for this instance
1647      *
1648      * if attribute is missing false is returned.
1649      *
1650      * @see BooleanAttribute
1651      */
getBooleanAttribute(BooleanAttribute key)1652     public boolean getBooleanAttribute(BooleanAttribute key)
1653     {
1654         if(key == DateFormat.BooleanAttribute.PARSE_PARTIAL_MATCH) {
1655             key = DateFormat.BooleanAttribute.PARSE_PARTIAL_LITERAL_MATCH;
1656         }
1657         return booleanAttributes.contains(key);
1658     }
1659 
1660 
1661     /**
1662      * <strong>[icu]</strong> Set a particular DisplayContext value in the formatter,
1663      * such as CAPITALIZATION_FOR_STANDALONE.
1664      *
1665      * @param context The DisplayContext value to set.
1666      */
setContext(DisplayContext context)1667     public void setContext(DisplayContext context) {
1668         if (context.type() == DisplayContext.Type.CAPITALIZATION) {
1669             capitalizationSetting = context;
1670         }
1671     }
1672 
1673     /**
1674      * <strong>[icu]</strong> Get the formatter's DisplayContext value for the specified DisplayContext.Type,
1675      * such as CAPITALIZATION.
1676      *
1677      * @param type the DisplayContext.Type whose value to return
1678      * @return the current DisplayContext setting for the specified type
1679      */
getContext(DisplayContext.Type type)1680     public DisplayContext getContext(DisplayContext.Type type) {
1681         return (type == DisplayContext.Type.CAPITALIZATION && capitalizationSetting != null)?
1682                 capitalizationSetting: DisplayContext.CAPITALIZATION_NONE;
1683     }
1684 
1685     /**
1686      * Overrides hashCode.
1687      */
1688     ///CLOVER:OFF
1689     // turn off code coverage since all subclasses override this
1690     @Override
hashCode()1691     public int hashCode() {
1692         return numberFormat.hashCode();
1693         // just enough fields for a reasonable distribution
1694     }
1695     ///CLOVER:ON
1696 
1697     /**
1698      * Overrides equals.
1699      */
1700     @Override
equals(Object obj)1701     public boolean equals(Object obj) {
1702         if (this == obj) return true;
1703         if (obj == null || getClass() != obj.getClass()) return false;
1704         DateFormat other = (DateFormat) obj;
1705         return (((calendar==null && other.calendar==null) ||
1706                     (calendar!=null && other.calendar!=null && calendar.isEquivalentTo(other.calendar))) &&
1707                 ((numberFormat==null && other.numberFormat==null) ||
1708                     (numberFormat!=null && other.numberFormat!=null && numberFormat.equals(other.numberFormat))) &&
1709                 capitalizationSetting == other.capitalizationSetting);
1710     }
1711 
1712     /**
1713      * Overrides clone.
1714      */
1715     @Override
clone()1716     public Object clone()
1717     {
1718         DateFormat other = (DateFormat) super.clone();
1719         other.calendar = (Calendar) calendar.clone();
1720         if (numberFormat != null) {
1721             other.numberFormat = (NumberFormat) numberFormat.clone();
1722         }
1723         return other;
1724     }
1725 
1726     /**
1727      * Creates a DateFormat with the given time and/or date style in the given
1728      * locale.
1729      * @param dateStyle a value from 0 to 3 indicating the time format,
1730      * or -1 to indicate no date
1731      * @param timeStyle a value from 0 to 3 indicating the time format,
1732      * or -1 to indicate no time
1733      * @param loc the locale for the format
1734      * @param cal the calendar to be used, or null
1735      */
get(int dateStyle, int timeStyle, ULocale loc, Calendar cal)1736     private static DateFormat get(int dateStyle, int timeStyle, ULocale loc, Calendar cal) {
1737         if((timeStyle != DateFormat.NONE && (timeStyle & RELATIVE)>0) ||
1738            (dateStyle != DateFormat.NONE && (dateStyle & RELATIVE)>0)) {
1739             RelativeDateFormat r = new RelativeDateFormat(timeStyle, dateStyle /* offset? */, loc, cal);
1740             return r;
1741         }
1742 
1743         if (timeStyle < DateFormat.NONE || timeStyle > DateFormat.SHORT) {
1744             throw new IllegalArgumentException("Illegal time style " + timeStyle);
1745         }
1746         if (dateStyle < DateFormat.NONE || dateStyle > DateFormat.SHORT) {
1747             throw new IllegalArgumentException("Illegal date style " + dateStyle);
1748         }
1749 
1750         if (cal == null) {
1751             cal = Calendar.getInstance(loc);
1752         }
1753 
1754         try {
1755             DateFormat result = cal.getDateTimeFormat(dateStyle, timeStyle, loc);
1756             result.setLocale(cal.getLocale(ULocale.VALID_LOCALE),
1757                  cal.getLocale(ULocale.ACTUAL_LOCALE));
1758             return result;
1759         } catch (MissingResourceException e) {
1760             ///CLOVER:OFF
1761             // coverage requires separate run with no data, so skip
1762             return new SimpleDateFormat("M/d/yy h:mm a");
1763             ///CLOVER:ON
1764         }
1765     }
1766 
1767     /**
1768      * First, read in the default serializable data.
1769      *
1770      * Then, if <code>serialVersionOnStream</code> is less than 1, indicating that
1771      * the stream was written by a pre-ICU-53 version,
1772      * set capitalizationSetting to a default value.
1773      * Finally, set serialVersionOnStream back to the maximum allowed value so that
1774      * default serialization will work properly if this object is streamed out again.
1775      */
readObject(ObjectInputStream stream)1776     private void readObject(ObjectInputStream stream)
1777          throws IOException, ClassNotFoundException
1778     {
1779         stream.defaultReadObject();
1780         if (serialVersionOnStream < 1) {
1781             // Didn't have capitalizationSetting, set it to default
1782             capitalizationSetting = DisplayContext.CAPITALIZATION_NONE;
1783         }
1784 
1785         // if deserialized from a release that didn't have booleanAttributes, add them all
1786         if(booleanAttributes == null) {
1787             booleanAttributes = EnumSet.allOf(BooleanAttribute.class);
1788         }
1789 
1790         serialVersionOnStream = currentSerialVersion;
1791     }
1792 
1793     /**
1794      * Creates a new date format.
1795      */
DateFormat()1796     protected DateFormat() {}
1797 
1798     //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1799 
1800     //-------------------------------------------------------------------------
1801     // Public static interface for creating custon DateFormats for different
1802     // types of Calendars.
1803     //-------------------------------------------------------------------------
1804 
1805     /**
1806      * Creates a {@link DateFormat} object that can be used to format dates in
1807      * the calendar system specified by <code>cal</code>.
1808      * <p>
1809      * @param cal   The calendar system for which a date format is desired.
1810      *
1811      * @param dateStyle The type of date format desired.  This can be
1812      *              {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
1813      *              etc.
1814      *
1815      * @param locale The locale for which the date format is desired.
1816      */
getDateInstance(Calendar cal, int dateStyle, Locale locale)1817     static final public DateFormat getDateInstance(Calendar cal, int dateStyle, Locale locale)
1818     {
1819         return getDateTimeInstance(cal, dateStyle, -1, ULocale.forLocale(locale));
1820     }
1821 
1822     /**
1823      * Creates a {@link DateFormat} object that can be used to format dates in
1824      * the calendar system specified by <code>cal</code>.
1825      * <p>
1826      * @param cal   The calendar system for which a date format is desired.
1827      *
1828      * @param dateStyle The type of date format desired.  This can be
1829      *              {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
1830      *              etc.
1831      *
1832      * @param locale The locale for which the date format is desired.
1833      */
getDateInstance(Calendar cal, int dateStyle, ULocale locale)1834     static final public DateFormat getDateInstance(Calendar cal, int dateStyle, ULocale locale)
1835     {
1836         return getDateTimeInstance(cal, dateStyle, -1, locale);
1837     }
1838 
1839     /**
1840      * Creates a {@link DateFormat} object that can be used to format times in
1841      * the calendar system specified by <code>cal</code>.
1842      * @param cal   The calendar system for which a time format is desired.
1843      *
1844      * @param timeStyle The type of time format desired.  This can be
1845      *              {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
1846      *              etc.
1847      *
1848      * @param locale The locale for which the time format is desired.
1849      *
1850      * @see DateFormat#getTimeInstance
1851      */
getTimeInstance(Calendar cal, int timeStyle, Locale locale)1852     static final public DateFormat getTimeInstance(Calendar cal, int timeStyle, Locale locale)
1853     {
1854         return getDateTimeInstance(cal, -1, timeStyle, ULocale.forLocale(locale));
1855     }
1856 
1857     /**
1858      * Creates a {@link DateFormat} object that can be used to format times in
1859      * the calendar system specified by <code>cal</code>.
1860      * @param cal   The calendar system for which a time format is desired.
1861      *
1862      * @param timeStyle The type of time format desired.  This can be
1863      *              {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
1864      *              etc.
1865      *
1866      * @param locale The locale for which the time format is desired.
1867      *
1868      * @see DateFormat#getTimeInstance
1869      */
getTimeInstance(Calendar cal, int timeStyle, ULocale locale)1870     static final public DateFormat getTimeInstance(Calendar cal, int timeStyle, ULocale locale)
1871     {
1872         return getDateTimeInstance(cal, -1, timeStyle, locale);
1873     }
1874 
1875     /**
1876      * Creates a {@link DateFormat} object that can be used to format dates and times in
1877      * the calendar system specified by <code>cal</code>.
1878      * @param cal   The calendar system for which a date/time format is desired.
1879      *
1880      * @param dateStyle The type of date format desired.  This can be
1881      *              {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
1882      *              etc.
1883      *
1884      * @param timeStyle The type of time format desired.  This can be
1885      *              {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
1886      *              etc.
1887      *
1888      * @param locale The locale for which the date/time format is desired.
1889      *
1890      * @see DateFormat#getDateTimeInstance
1891      */
getDateTimeInstance(Calendar cal, int dateStyle, int timeStyle, Locale locale)1892     static final public DateFormat getDateTimeInstance(Calendar cal, int dateStyle,
1893                                                  int timeStyle, Locale locale)
1894     {
1895         return getDateTimeInstance(cal, dateStyle, timeStyle, ULocale.forLocale(locale));
1896     }
1897 
1898     /**
1899      * Creates a {@link DateFormat} object that can be used to format dates and times in
1900      * the calendar system specified by <code>cal</code>.
1901      * @param cal   The calendar system for which a date/time format is desired.
1902      *
1903      * @param dateStyle The type of date format desired.  This can be
1904      *              {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
1905      *              etc.
1906      *
1907      * @param timeStyle The type of time format desired.  This can be
1908      *              {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
1909      *              etc.
1910      *
1911      * @param locale The locale for which the date/time format is desired.
1912      *
1913      * @see DateFormat#getDateTimeInstance
1914      */
getDateTimeInstance(Calendar cal, int dateStyle, int timeStyle, ULocale locale)1915     static final public DateFormat getDateTimeInstance(Calendar cal, int dateStyle,
1916                                                  int timeStyle, ULocale locale)
1917     {
1918         if (cal == null) {
1919             throw new IllegalArgumentException("Calendar must be supplied");
1920         }
1921         return get(dateStyle, timeStyle, locale, cal);
1922     }
1923 
1924     /**
1925      * Returns a date/time formatter that uses the SHORT style
1926      * for both the date and the time.
1927      *
1928      * @param cal   The calendar system for which a date/time format is desired.
1929      * @param locale The locale for which the date/time format is desired.
1930      */
getInstance(Calendar cal, Locale locale)1931     static final public DateFormat getInstance(Calendar cal, Locale locale) {
1932         return getDateTimeInstance(cal, SHORT, SHORT, ULocale.forLocale(locale));
1933     }
1934 
1935     /**
1936      * Returns a date/time formatter that uses the SHORT style
1937      * for both the date and the time.
1938      *
1939      * @param cal   The calendar system for which a date/time format is desired.
1940      * @param locale The locale for which the date/time format is desired.
1941      * @hide draft / provisional / internal are hidden on OHOS
1942      */
getInstance(Calendar cal, ULocale locale)1943     static final public DateFormat getInstance(Calendar cal, ULocale locale) {
1944         return getDateTimeInstance(cal, SHORT, SHORT, locale);
1945     }
1946 
1947     /**
1948      * Returns a default date/time formatter that uses the SHORT style for both the
1949      * date and the time.
1950      *
1951      * @param cal   The calendar system for which a date/time format is desired.
1952      */
getInstance(Calendar cal)1953     static final public DateFormat getInstance(Calendar cal) {
1954         return getInstance(cal, ULocale.getDefault(Category.FORMAT));
1955     }
1956 
1957     /**
1958      * Creates a {@link DateFormat} object for the default locale that can be used
1959      * to format dates in the calendar system specified by <code>cal</code>.
1960      * <p>
1961      * @param cal   The calendar system for which a date format is desired.
1962      *
1963      * @param dateStyle The type of date format desired.  This can be
1964      *              {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
1965      *              etc.
1966      */
getDateInstance(Calendar cal, int dateStyle)1967     static final public DateFormat getDateInstance(Calendar cal, int dateStyle) {
1968         return getDateInstance(cal, dateStyle, ULocale.getDefault(Category.FORMAT));
1969     }
1970 
1971     /**
1972      * Creates a {@link DateFormat} object that can be used to format times in
1973      * the calendar system specified by <code>cal</code>.
1974      * @param cal   The calendar system for which a time format is desired.
1975      *
1976      * @param timeStyle The type of time format desired.  This can be
1977      *              {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
1978      *              etc.
1979      *
1980      * @see DateFormat#getTimeInstance
1981      */
getTimeInstance(Calendar cal, int timeStyle)1982     static final public DateFormat getTimeInstance(Calendar cal, int timeStyle) {
1983         return getTimeInstance(cal, timeStyle, ULocale.getDefault(Category.FORMAT));
1984     }
1985 
1986     /**
1987      * Creates a {@link DateFormat} object for the default locale that can be used to format
1988      * dates and times in the calendar system specified by <code>cal</code>.
1989      * @param cal   The calendar system for which a date/time format is desired.
1990      *
1991      * @param dateStyle The type of date format desired.  This can be
1992      *              {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
1993      *              etc.
1994      *
1995      * @param timeStyle The type of time format desired.  This can be
1996      *              {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
1997      *              etc.
1998      *
1999      * @see DateFormat#getDateTimeInstance
2000      */
getDateTimeInstance(Calendar cal, int dateStyle, int timeStyle)2001     static final public DateFormat getDateTimeInstance(Calendar cal, int dateStyle, int timeStyle) {
2002         return getDateTimeInstance(cal, dateStyle, timeStyle, ULocale.getDefault(Category.FORMAT));
2003     }
2004 
2005     /**
2006      * <strong>[icu]</strong> Returns a {@link DateFormat} object that can be used to format dates and times in
2007      * the default locale.
2008      *
2009      * @param skeleton The skeleton that selects the fields to be formatted. (Uses the
2010      *              {@link DateTimePatternGenerator}.) This can be {@link DateFormat#ABBR_MONTH},
2011      *              {@link DateFormat#MONTH_WEEKDAY_DAY}, etc.
2012      */
getInstanceForSkeleton(String skeleton)2013     public final static DateFormat getInstanceForSkeleton(String skeleton) {
2014         return getPatternInstance(skeleton, ULocale.getDefault(Category.FORMAT));
2015     }
2016 
2017     /**
2018      * <strong>[icu]</strong> Returns a {@link DateFormat} object that can be used to format dates and times in
2019      * the given locale.
2020      *
2021      * @param skeleton The skeleton that selects the fields to be formatted. (Uses the
2022      *              {@link DateTimePatternGenerator}.) This can be {@link DateFormat#ABBR_MONTH},
2023      *              {@link DateFormat#MONTH_WEEKDAY_DAY}, etc.
2024      *
2025      * @param locale The locale for which the date/time format is desired.
2026      */
getInstanceForSkeleton(String skeleton, Locale locale)2027     public final static DateFormat getInstanceForSkeleton(String skeleton, Locale locale) {
2028         return getPatternInstance(skeleton, ULocale.forLocale(locale));
2029     }
2030 
2031     /**
2032      * <strong>[icu]</strong> Returns a {@link DateFormat} object that can be used to format dates and times in
2033      * the given locale.
2034      *
2035      * @param skeleton The skeleton that selects the fields to be formatted. (Uses the
2036      *              {@link DateTimePatternGenerator}.) This can be {@link DateFormat#ABBR_MONTH},
2037      *              {@link DateFormat#MONTH_WEEKDAY_DAY}, etc.
2038      *
2039      * @param locale The locale for which the date/time format is desired.
2040      */
getInstanceForSkeleton(String skeleton, ULocale locale)2041     public final static DateFormat getInstanceForSkeleton(String skeleton, ULocale locale) {
2042         DateTimePatternGenerator generator = DateTimePatternGenerator.getInstance(locale);
2043         final String bestPattern = generator.getBestPattern(skeleton);
2044         return new SimpleDateFormat(bestPattern, locale);
2045     }
2046 
2047     /**
2048      * <strong>[icu]</strong> Creates a {@link DateFormat} object that can be used to format dates and
2049      * times in the calendar system specified by <code>cal</code>.
2050      *
2051      * @param cal   The calendar system for which a date/time format is desired.
2052      *
2053      * @param skeleton The skeleton that selects the fields to be formatted. (Uses the
2054      *              {@link DateTimePatternGenerator}.)  This can be
2055      *              {@link DateFormat#ABBR_MONTH}, {@link DateFormat#MONTH_WEEKDAY_DAY},
2056      *              etc.
2057      *
2058      * @param locale The locale for which the date/time format is desired.
2059      */
getInstanceForSkeleton(Calendar cal, String skeleton, Locale locale)2060     public final static DateFormat getInstanceForSkeleton(Calendar cal, String skeleton, Locale locale) {
2061         return getPatternInstance(cal, skeleton, ULocale.forLocale(locale));
2062     }
2063 
2064     /**
2065      * <strong>[icu]</strong> Creates a {@link DateFormat} object that can be used to format dates and
2066      * times in the calendar system specified by <code>cal</code>.
2067      *
2068      * @param cal   The calendar system for which a date/time format is desired.
2069      *
2070      * @param skeleton The skeleton that selects the fields to be formatted. (Uses the
2071      *              {@link DateTimePatternGenerator}.)  This can be
2072      *              {@link DateFormat#ABBR_MONTH}, {@link DateFormat#MONTH_WEEKDAY_DAY},
2073      *              etc.
2074      *
2075      * @param locale The locale for which the date/time format is desired.
2076      */
getInstanceForSkeleton( Calendar cal, String skeleton, ULocale locale)2077     public final static DateFormat getInstanceForSkeleton(
2078         Calendar cal, String skeleton, ULocale locale) {
2079         if (cal != null) {
2080             locale = locale.setKeywordValue("calendar", cal.getType());
2081         }
2082         DateTimePatternGenerator generator = DateTimePatternGenerator.getInstance(locale);
2083         final String bestPattern = generator.getBestPattern(skeleton);
2084         SimpleDateFormat format = new SimpleDateFormat(bestPattern, locale);
2085         format.setCalendar(cal);
2086         return format;
2087     }
2088 
2089 
2090     /**
2091      * <strong>[icu]</strong> Returns a {@link DateFormat} object that can be used to format dates and times in
2092      * the default locale.
2093      * The getInstanceForSkeleton methods are preferred over the getPatternInstance methods.
2094      *
2095      * @param skeleton The skeleton that selects the fields to be formatted. (Uses the
2096      *              {@link DateTimePatternGenerator}.) This can be {@link DateFormat#ABBR_MONTH},
2097      *              {@link DateFormat#MONTH_WEEKDAY_DAY}, etc.
2098      */
getPatternInstance(String skeleton)2099     public final static DateFormat getPatternInstance(String skeleton) {
2100         return getInstanceForSkeleton(skeleton);
2101     }
2102 
2103     /**
2104      * <strong>[icu]</strong> Returns a {@link DateFormat} object that can be used to format dates and times in
2105      * the given locale.
2106      * The getInstanceForSkeleton methods are preferred over the getPatternInstance methods.
2107      *
2108      * @param skeleton The skeleton that selects the fields to be formatted. (Uses the
2109      *              {@link DateTimePatternGenerator}.) This can be {@link DateFormat#ABBR_MONTH},
2110      *              {@link DateFormat#MONTH_WEEKDAY_DAY}, etc.
2111      *
2112      * @param locale The locale for which the date/time format is desired.
2113      */
getPatternInstance(String skeleton, Locale locale)2114     public final static DateFormat getPatternInstance(String skeleton, Locale locale) {
2115         return getInstanceForSkeleton(skeleton, locale);
2116     }
2117 
2118     /**
2119      * <strong>[icu]</strong> Returns a {@link DateFormat} object that can be used to format dates and times in
2120      * the given locale.
2121      * The getInstanceForSkeleton methods are preferred over the getPatternInstance methods.
2122      *
2123      * @param skeleton The skeleton that selects the fields to be formatted. (Uses the
2124      *              {@link DateTimePatternGenerator}.) This can be {@link DateFormat#ABBR_MONTH},
2125      *              {@link DateFormat#MONTH_WEEKDAY_DAY}, etc.
2126      *
2127      * @param locale The locale for which the date/time format is desired.
2128      */
getPatternInstance(String skeleton, ULocale locale)2129     public final static DateFormat getPatternInstance(String skeleton, ULocale locale) {
2130         return getInstanceForSkeleton(skeleton, locale);
2131     }
2132 
2133     /**
2134      * <strong>[icu]</strong> Creates a {@link DateFormat} object that can be used to format dates and
2135      * times in the calendar system specified by <code>cal</code>.
2136      * The getInstanceForSkeleton methods are preferred over the getPatternInstance methods.
2137      *
2138      * @param cal   The calendar system for which a date/time format is desired.
2139      *
2140      * @param skeleton The skeleton that selects the fields to be formatted. (Uses the
2141      *              {@link DateTimePatternGenerator}.)  This can be
2142      *              {@link DateFormat#ABBR_MONTH}, {@link DateFormat#MONTH_WEEKDAY_DAY},
2143      *              etc.
2144      *
2145      * @param locale The locale for which the date/time format is desired.
2146      */
getPatternInstance(Calendar cal, String skeleton, Locale locale)2147     public final static DateFormat getPatternInstance(Calendar cal, String skeleton, Locale locale) {
2148         return getInstanceForSkeleton(cal, skeleton, locale);
2149     }
2150 
2151     /**
2152      * <strong>[icu]</strong> Creates a {@link DateFormat} object that can be used to format dates and
2153      * times in the calendar system specified by <code>cal</code>.
2154      * The getInstanceForSkeleton methods are preferred over the getPatternInstance methods.
2155      *
2156      * @param cal   The calendar system for which a date/time format is desired.
2157      *
2158      * @param skeleton The skeleton that selects the fields to be formatted. (Uses the
2159      *              {@link DateTimePatternGenerator}.)  This can be
2160      *              {@link DateFormat#ABBR_MONTH}, {@link DateFormat#MONTH_WEEKDAY_DAY},
2161      *              etc.
2162      *
2163      * @param locale The locale for which the date/time format is desired.
2164      */
getPatternInstance( Calendar cal, String skeleton, ULocale locale)2165     public final static DateFormat getPatternInstance(
2166         Calendar cal, String skeleton, ULocale locale) {
2167         return getInstanceForSkeleton(cal, skeleton, locale);
2168     }
2169 
2170     /**
2171      * The instances of this inner class are used as attribute keys and values
2172      * in AttributedCharacterIterator that
2173      * DateFormat.formatToCharacterIterator() method returns.
2174      *
2175      * <p>There is no public constructor to this class, the only instances are the
2176      * constants defined here.
2177      * <p>
2178      */
2179     public static class Field extends Format.Field {
2180 
2181         private static final long serialVersionUID = -3627456821000730829L;
2182 
2183         // Max number of calendar fields
2184         private static final int CAL_FIELD_COUNT;
2185 
2186         // Table for mapping calendar field number to DateFormat.Field
2187         private static final Field[] CAL_FIELDS;
2188 
2189         // Map for resolving DateFormat.Field by name
2190         private static final Map<String, Field> FIELD_NAME_MAP;
2191 
2192         static {
2193             GregorianCalendar cal = new GregorianCalendar();
2194             CAL_FIELD_COUNT = cal.getFieldCount();
2195             CAL_FIELDS = new Field[CAL_FIELD_COUNT];
2196             FIELD_NAME_MAP = new HashMap<String, Field>(CAL_FIELD_COUNT);
2197         }
2198 
2199         // Java fields -------------------
2200 
2201         /**
2202          * Constant identifying the time of day indicator(am/pm).
2203          */
2204         public static final Field AM_PM = new Field("am pm", Calendar.AM_PM);
2205 
2206         /**
2207          * Constant identifying the day of month field.
2208          */
2209         public static final Field DAY_OF_MONTH = new Field("day of month", Calendar.DAY_OF_MONTH);
2210 
2211         /**
2212          * Constant identifying the day of week field.
2213          */
2214         public static final Field DAY_OF_WEEK = new Field("day of week", Calendar.DAY_OF_WEEK);
2215 
2216         /**
2217          * Constant identifying the day of week in month field.
2218          */
2219         public static final Field DAY_OF_WEEK_IN_MONTH =
2220             new Field("day of week in month", Calendar.DAY_OF_WEEK_IN_MONTH);
2221 
2222         /**
2223          * Constant identifying the day of year field.
2224          */
2225         public static final Field DAY_OF_YEAR = new Field("day of year", Calendar.DAY_OF_YEAR);
2226 
2227         /**
2228          * Constant identifying the era field.
2229          */
2230         public static final Field ERA = new Field("era", Calendar.ERA);
2231 
2232         /**
2233          * Constant identifying the hour(0-23) of day field.
2234          */
2235         public static final Field HOUR_OF_DAY0 = new Field("hour of day", Calendar.HOUR_OF_DAY);
2236 
2237         /**
2238          * Constant identifying the hour(1-24) of day field.
2239          */
2240         public static final Field HOUR_OF_DAY1 = new Field("hour of day 1", -1);
2241 
2242         /**
2243          * Constant identifying the hour(0-11) field.
2244          */
2245         public static final Field HOUR0 = new Field("hour", Calendar.HOUR);
2246 
2247         /**
2248          * Constant identifying the hour(1-12) field.
2249          */
2250         public static final Field HOUR1 = new Field("hour 1", -1);
2251 
2252         /**
2253          * Constant identifying the millisecond field.
2254          */
2255         public static final Field MILLISECOND = new Field("millisecond", Calendar.MILLISECOND);
2256 
2257         /**
2258          * Constant identifying the minute field.
2259          */
2260         public static final Field MINUTE = new Field("minute", Calendar.MINUTE);
2261 
2262         /**
2263          * Constant identifying the month field.
2264          */
2265         public static final Field MONTH = new Field("month", Calendar.MONTH);
2266 
2267         /**
2268          * Constant identifying the second field.
2269          */
2270         public static final Field SECOND = new Field("second", Calendar.SECOND);
2271 
2272         /**
2273          * Constant identifying the time zone field.
2274          */
2275         public static final Field TIME_ZONE = new Field("time zone", -1);
2276 
2277         /**
2278          * Constant identifying the week of month field.
2279          */
2280         public static final Field WEEK_OF_MONTH =
2281             new Field("week of month", Calendar.WEEK_OF_MONTH);
2282 
2283         /**
2284          * Constant identifying the week of year field.
2285          */
2286         public static final Field WEEK_OF_YEAR = new Field("week of year", Calendar.WEEK_OF_YEAR);
2287 
2288         /**
2289          * Constant identifying the year field.
2290          */
2291         public static final Field YEAR = new Field("year", Calendar.YEAR);
2292 
2293 
2294         // ICU only fields -------------------
2295 
2296         /**
2297          * Constant identifying the local day of week field.
2298          */
2299         public static final Field DOW_LOCAL = new Field("local day of week", Calendar.DOW_LOCAL);
2300 
2301         /**
2302          * Constant identifying the extended year field.
2303          */
2304         public static final Field EXTENDED_YEAR = new Field("extended year",
2305                                                             Calendar.EXTENDED_YEAR);
2306 
2307         /**
2308          * Constant identifying the Julian day field.
2309          */
2310         public static final Field JULIAN_DAY = new Field("Julian day", Calendar.JULIAN_DAY);
2311 
2312         /**
2313          * Constant identifying the milliseconds in day field.
2314          */
2315         public static final Field MILLISECONDS_IN_DAY =
2316             new Field("milliseconds in day", Calendar.MILLISECONDS_IN_DAY);
2317 
2318         /**
2319          * Constant identifying the year used with week of year field.
2320          */
2321         public static final Field YEAR_WOY = new Field("year for week of year", Calendar.YEAR_WOY);
2322 
2323         /**
2324          * Constant identifying the quarter field.
2325          */
2326         public static final Field QUARTER = new Field("quarter", -1);
2327 
2328         /**
2329          * Constant identifying the related year field.
2330          * @deprecated This API is ICU internal only.
2331          * @hide draft / provisional / internal are hidden on OHOS
2332          */
2333         @Deprecated
2334         public static final Field RELATED_YEAR = new Field("related year", -1);
2335 
2336         /**
2337          * <strong>[icu]</strong> Constant identifying the am/pm/midnight/noon field.
2338          */
2339         public static final Field AM_PM_MIDNIGHT_NOON = new Field("am/pm/midnight/noon", -1);
2340 
2341         /**
2342          * <strong>[icu]</strong> Constant identifying the flexible day period field.
2343          */
2344         public static final Field FLEXIBLE_DAY_PERIOD = new Field("flexible day period", -1);
2345 
2346         /**
2347          * Constant identifying the time separator field.
2348          * @deprecated This API is ICU internal only.
2349          * @hide draft / provisional / internal are hidden on OHOS
2350          */
2351         @Deprecated
2352         public static final Field TIME_SEPARATOR = new Field("time separator", -1);
2353 
2354         // Stand alone types are variants for its base types.  So we do not define Field for
2355         // them.
2356         /*
2357         public static final Field STANDALONE_DAY =
2358             new Field("stand alone day of week", Calendar.DAY_OF_WEEK);
2359         public static final Field STANDALONE_MONTH = new Field("stand alone month", Calendar.MONTH);
2360         public static final Field STANDALONE_QUARTER = new Field("stand alone quarter", -1);
2361         */
2362 
2363         // Corresponding calendar field
2364         private final int calendarField;
2365 
2366         /**
2367          * Constructs a <code>DateFormat.Field</code> with the given name and
2368          * the <code>Calendar</code> field which this attribute represents.  Use -1 for
2369          * <code>calendarField</code> if this field does not have a corresponding
2370          * <code>Calendar</code> field.
2371          *
2372          * @param name          Name of the attribute
2373          * @param calendarField <code>Calendar</code> field constant
2374          */
Field(String name, int calendarField)2375         protected Field(String name, int calendarField) {
2376             super(name);
2377             this.calendarField = calendarField;
2378             if (this.getClass() == DateFormat.Field.class) {
2379                 FIELD_NAME_MAP.put(name, this);
2380                 if (calendarField >= 0 && calendarField < CAL_FIELD_COUNT) {
2381                     CAL_FIELDS[calendarField] = this;
2382                 }
2383             }
2384         }
2385 
2386         /**
2387          * Returns the <code>Field</code> constant that corresponds to the <code>
2388          * Calendar</code> field <code>calendarField</code>.  If there is no
2389          * corresponding <code>Field</code> is available, null is returned.
2390          *
2391          * @param calendarField <code>Calendar</code> field constant
2392          * @return <code>Field</code> associated with the <code>calendarField</code>,
2393          * or null if no associated <code>Field</code> is available.
2394          * @throws IllegalArgumentException if <code>calendarField</code> is not
2395          * a valid <code>Calendar</code> field constant.
2396          */
ofCalendarField(int calendarField)2397         public static DateFormat.Field ofCalendarField(int calendarField) {
2398             if (calendarField < 0 || calendarField >= CAL_FIELD_COUNT) {
2399                 throw new IllegalArgumentException("Calendar field number is out of range");
2400             }
2401             return CAL_FIELDS[calendarField];
2402         }
2403 
2404         /**
2405          * Returns the <code>Calendar</code> field associated with this attribute.
2406          * If there is no corresponding <code>Calendar</code> available, this will
2407          * return -1.
2408          *
2409          * @return <code>Calendar</code> constant for this attribute.
2410          */
getCalendarField()2411         public int getCalendarField() {
2412             return calendarField;
2413         }
2414 
2415         /**
2416          * Resolves instances being deserialized to the predefined constants.
2417          *
2418          * @throws InvalidObjectException if the constant could not be resolved.
2419          */
2420         @Override
readResolve()2421         protected Object readResolve() throws InvalidObjectException {
2422             ///CLOVER:OFF
2423             if (this.getClass() != DateFormat.Field.class) {
2424                 throw new InvalidObjectException(
2425                     "A subclass of DateFormat.Field must implement readResolve.");
2426             }
2427             ///CLOVER:ON
2428             Object o = FIELD_NAME_MAP.get(this.getName());
2429             ///CLOVER:OFF
2430             if (o == null) {
2431                 throw new InvalidObjectException("Unknown attribute name.");
2432             }
2433             ///CLOVER:ON
2434             return o;
2435         }
2436     }
2437 }
2438