1 /*
   2  * Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * (C) Copyright Taligent, Inc. 1996 - All Rights Reserved
  28  * (C) Copyright IBM Corp. 1996 - All Rights Reserved
  29  *
  30  *   The original version of this source code and documentation is copyrighted
  31  * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
  32  * materials are provided under terms of a License Agreement between Taligent
  33  * and Sun. This technology is protected by multiple US and International
  34  * patents. This notice and attribution to Taligent may not be removed.
  35  *   Taligent is a registered trademark of Taligent, Inc.
  36  *
  37  */
  38 
  39 package java.text;
  40 
  41 import java.io.InvalidObjectException;
  42 import java.text.spi.DateFormatProvider;
  43 import java.util.Calendar;
  44 import java.util.Date;
  45 import java.util.GregorianCalendar;
  46 import java.util.HashMap;
  47 import java.util.Locale;
  48 import java.util.Map;
  49 import java.util.MissingResourceException;
  50 import java.util.ResourceBundle;
  51 import java.util.TimeZone;
  52 import java.util.spi.LocaleServiceProvider;
  53 import sun.util.locale.provider.LocaleProviderAdapter;
  54 import sun.util.locale.provider.LocaleServiceProviderPool;
  55 
  56 /**
  57  * {@code DateFormat} is an abstract class for date/time formatting subclasses which
  58  * formats and parses dates or time in a language-independent manner.
  59  * The date/time formatting subclass, such as {@link SimpleDateFormat}, allows for
  60  * formatting (i.e., date → text), parsing (text → date), and
  61  * normalization.  The date is represented as a <code>Date</code> object or
  62  * as the milliseconds since January 1, 1970, 00:00:00 GMT.
  63  *
  64  * <p>{@code DateFormat} provides many class methods for obtaining default date/time
  65  * formatters based on the default or a given locale and a number of formatting
  66  * styles. The formatting styles include {@link #FULL}, {@link #LONG}, {@link #MEDIUM}, and {@link #SHORT}. More
  67  * detail and examples of using these styles are provided in the method
  68  * descriptions.
  69  *
  70  * <p>{@code DateFormat} helps you to format and parse dates for any locale.
  71  * Your code can be completely independent of the locale conventions for
  72  * months, days of the week, or even the calendar format: lunar vs. solar.
  73  *
  74  * <p>To format a date for the current Locale, use one of the
  75  * static factory methods:
  76  * <blockquote>
  77  * <pre>{@code
  78  * myString = DateFormat.getDateInstance().format(myDate);
  79  * }</pre>
  80  * </blockquote>
  81  * <p>If you are formatting multiple dates, it is
  82  * more efficient to get the format and use it multiple times so that
  83  * the system doesn't have to fetch the information about the local
  84  * language and country conventions multiple times.
  85  * <blockquote>
  86  * <pre>{@code
  87  * DateFormat df = DateFormat.getDateInstance();
  88  * for (int i = 0; i < myDate.length; ++i) {
  89  *     output.println(df.format(myDate[i]) + "; ");
  90  * }
  91  * }</pre>
  92  * </blockquote>
  93  * <p>To format a date for a different Locale, specify it in the
  94  * call to {@link #getDateInstance(int, Locale) getDateInstance()}.
  95  * <blockquote>
  96  * <pre>{@code
  97  * DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);
  98  * }</pre>
  99  * </blockquote>
 100  *
 101  * <p>If the specified locale contains "ca" (calendar), "rg" (region override),
 102  * and/or "tz" (timezone) <a href="../util/Locale.html#def_locale_extension">Unicode
 103  * extensions</a>, the calendar, the country and/or the time zone for formatting
 104  * are overridden. If both "ca" and "rg" are specified, the calendar from the "ca"
 105  * extension supersedes the implicit one from the "rg" extension.
 106  *
 107  * <p>You can use a DateFormat to parse also.
 108  * <blockquote>
 109  * <pre>{@code
 110  * myDate = df.parse(myString);
 111  * }</pre>
 112  * </blockquote>
 113  * <p>Use {@code getDateInstance} to get the normal date format for that country.
 114  * There are other static factory methods available.
 115  * Use {@code getTimeInstance} to get the time format for that country.
 116  * Use {@code getDateTimeInstance} to get a date and time format. You can pass in
 117  * different options to these factory methods to control the length of the
 118  * result; from {@link #SHORT} to {@link #MEDIUM} to {@link #LONG} to {@link #FULL}. The exact result depends
 119  * on the locale, but generally:
 120  * <ul><li>{@link #SHORT} is completely numeric, such as {@code 12.13.52} or {@code 3:30pm}
 121  * <li>{@link #MEDIUM} is longer, such as {@code Jan 12, 1952}
 122  * <li>{@link #LONG} is longer, such as {@code January 12, 1952} or {@code 3:30:32pm}
 123  * <li>{@link #FULL} is pretty completely specified, such as
 124  * {@code Tuesday, April 12, 1952 AD or 3:30:42pm PST}.
 125  * </ul>
 126  *
 127  * <p>You can also set the time zone on the format if you wish.
 128  * If you want even more control over the format or parsing,
 129  * (or want to give your users more control),
 130  * you can try casting the {@code DateFormat} you get from the factory methods
 131  * to a {@link SimpleDateFormat}. This will work for the majority
 132  * of countries; just remember to put it in a {@code try} block in case you
 133  * encounter an unusual one.
 134  *
 135  * <p>You can also use forms of the parse and format methods with
 136  * {@link ParsePosition} and {@link FieldPosition} to
 137  * allow you to
 138  * <ul><li>progressively parse through pieces of a string.
 139  * <li>align any particular field, or find out where it is for selection
 140  * on the screen.
 141  * </ul>
 142  *
 143  * <h2><a id="synchronization">Synchronization</a></h2>
 144  *
 145  * <p>
 146  * Date formats are not synchronized.
 147  * It is recommended to create separate format instances for each thread.
 148  * If multiple threads access a format concurrently, it must be synchronized
 149  * externally.
 150  *
 151  * @implSpec
 152  * <ul><li>The {@link #format(Date, StringBuffer, FieldPosition)} and
 153  * {@link #parse(String, ParsePosition)} methods may throw
 154  * {@code NullPointerException}, if any of their parameter is {@code null}.
 155  * The subclass may provide its own implementation and specification about
 156  * {@code NullPointerException}.</li>
 157  * <li>The {@link #setCalendar(Calendar)}, {@link
 158  * #setNumberFormat(NumberFormat)} and {@link #setTimeZone(TimeZone)} methods
 159  * do not throw {@code NullPointerException} when their parameter is
 160  * {@code null}, but any subsequent operations on the same instance may throw
 161  * {@code NullPointerException}.</li>
 162  * <li>The {@link #getCalendar()}, {@link #getNumberFormat()} and
 163  * {@link getTimeZone()} methods may return {@code null}, if the respective
 164  * values of this instance is set to {@code null} through the corresponding
 165  * setter methods. For Example: {@link #getTimeZone()} may return {@code null},
 166  * if the {@code TimeZone} value of this instance is set as
 167  * {@link #setTimeZone(java.util.TimeZone) setTimeZone(null)}.</li>
 168  * </ul>
 169  *
 170  * @see          Format
 171  * @see          NumberFormat
 172  * @see          SimpleDateFormat
 173  * @see          java.util.Calendar
 174  * @see          java.util.GregorianCalendar
 175  * @see          java.util.TimeZone
 176  * @author       Mark Davis, Chen-Lieh Huang, Alan Liu
 177  * @since 1.1
 178  */
 179 public abstract class DateFormat extends Format {
 180 
 181     /**
 182      * The {@link Calendar} instance used for calculating the date-time fields
 183      * and the instant of time. This field is used for both formatting and
 184      * parsing.
 185      *
 186      * <p>Subclasses should initialize this field to a {@link Calendar}
 187      * appropriate for the {@link Locale} associated with this
 188      * <code>DateFormat</code>.
 189      * @serial
 190      */
 191     protected Calendar calendar;
 192 
 193     /**
 194      * The number formatter that <code>DateFormat</code> uses to format numbers
 195      * in dates and times.  Subclasses should initialize this to a number format
 196      * appropriate for the locale associated with this <code>DateFormat</code>.
 197      * @serial
 198      */
 199     protected NumberFormat numberFormat;
 200 
 201     /**
 202      * Useful constant for ERA field alignment.
 203      * Used in FieldPosition of date/time formatting.
 204      */
 205     public static final int ERA_FIELD = 0;
 206     /**
 207      * Useful constant for YEAR field alignment.
 208      * Used in FieldPosition of date/time formatting.
 209      */
 210     public static final int YEAR_FIELD = 1;
 211     /**
 212      * Useful constant for MONTH field alignment.
 213      * Used in FieldPosition of date/time formatting.
 214      */
 215     public static final int MONTH_FIELD = 2;
 216     /**
 217      * Useful constant for DATE field alignment.
 218      * Used in FieldPosition of date/time formatting.
 219      */
 220     public static final int DATE_FIELD = 3;
 221     /**
 222      * Useful constant for one-based HOUR_OF_DAY field alignment.
 223      * Used in FieldPosition of date/time formatting.
 224      * HOUR_OF_DAY1_FIELD is used for the one-based 24-hour clock.
 225      * For example, 23:59 + 01:00 results in 24:59.
 226      */
 227     public static final int HOUR_OF_DAY1_FIELD = 4;
 228     /**
 229      * Useful constant for zero-based HOUR_OF_DAY field alignment.
 230      * Used in FieldPosition of date/time formatting.
 231      * HOUR_OF_DAY0_FIELD is used for the zero-based 24-hour clock.
 232      * For example, 23:59 + 01:00 results in 00:59.
 233      */
 234     public static final int HOUR_OF_DAY0_FIELD = 5;
 235     /**
 236      * Useful constant for MINUTE field alignment.
 237      * Used in FieldPosition of date/time formatting.
 238      */
 239     public static final int MINUTE_FIELD = 6;
 240     /**
 241      * Useful constant for SECOND field alignment.
 242      * Used in FieldPosition of date/time formatting.
 243      */
 244     public static final int SECOND_FIELD = 7;
 245     /**
 246      * Useful constant for MILLISECOND field alignment.
 247      * Used in FieldPosition of date/time formatting.
 248      */
 249     public static final int MILLISECOND_FIELD = 8;
 250     /**
 251      * Useful constant for DAY_OF_WEEK field alignment.
 252      * Used in FieldPosition of date/time formatting.
 253      */
 254     public static final int DAY_OF_WEEK_FIELD = 9;
 255     /**
 256      * Useful constant for DAY_OF_YEAR field alignment.
 257      * Used in FieldPosition of date/time formatting.
 258      */
 259     public static final int DAY_OF_YEAR_FIELD = 10;
 260     /**
 261      * Useful constant for DAY_OF_WEEK_IN_MONTH field alignment.
 262      * Used in FieldPosition of date/time formatting.
 263      */
 264     public static final int DAY_OF_WEEK_IN_MONTH_FIELD = 11;
 265     /**
 266      * Useful constant for WEEK_OF_YEAR field alignment.
 267      * Used in FieldPosition of date/time formatting.
 268      */
 269     public static final int WEEK_OF_YEAR_FIELD = 12;
 270     /**
 271      * Useful constant for WEEK_OF_MONTH field alignment.
 272      * Used in FieldPosition of date/time formatting.
 273      */
 274     public static final int WEEK_OF_MONTH_FIELD = 13;
 275     /**
 276      * Useful constant for AM_PM field alignment.
 277      * Used in FieldPosition of date/time formatting.
 278      */
 279     public static final int AM_PM_FIELD = 14;
 280     /**
 281      * Useful constant for one-based HOUR field alignment.
 282      * Used in FieldPosition of date/time formatting.
 283      * HOUR1_FIELD is used for the one-based 12-hour clock.
 284      * For example, 11:30 PM + 1 hour results in 12:30 AM.
 285      */
 286     public static final int HOUR1_FIELD = 15;
 287     /**
 288      * Useful constant for zero-based HOUR field alignment.
 289      * Used in FieldPosition of date/time formatting.
 290      * HOUR0_FIELD is used for the zero-based 12-hour clock.
 291      * For example, 11:30 PM + 1 hour results in 00:30 AM.
 292      */
 293     public static final int HOUR0_FIELD = 16;
 294     /**
 295      * Useful constant for TIMEZONE field alignment.
 296      * Used in FieldPosition of date/time formatting.
 297      */
 298     public static final int TIMEZONE_FIELD = 17;
 299 
 300     // Proclaim serial compatibility with 1.1 FCS
 301     @java.io.Serial
 302     private static final long serialVersionUID = 7218322306649953788L;
 303 
 304     /**
 305      * Formats the given {@code Object} into a date-time string. The formatted
 306      * string is appended to the given {@code StringBuffer}.
 307      *
 308      * @param obj Must be a {@code Date} or a {@code Number} representing a
 309      * millisecond offset from the <a href="../util/Calendar.html#Epoch">Epoch</a>.
 310      * @param toAppendTo The string buffer for the returning date-time string.
 311      * @param fieldPosition keeps track on the position of the field within
 312      * the returned string. For example, given a date-time text
 313      * {@code "1996.07.10 AD at 15:08:56 PDT"}, if the given {@code fieldPosition}
 314      * is {@link DateFormat#YEAR_FIELD}, the begin index and end index of
 315      * {@code fieldPosition} will be set to 0 and 4, respectively.
 316      * Notice that if the same date-time field appears more than once in a
 317      * pattern, the {@code fieldPosition} will be set for the first occurrence
 318      * of that date-time field. For instance, formatting a {@code Date} to the
 319      * date-time string {@code "1 PM PDT (Pacific Daylight Time)"} using the
 320      * pattern {@code "h a z (zzzz)"} and the alignment field
 321      * {@link DateFormat#TIMEZONE_FIELD}, the begin index and end index of
 322      * {@code fieldPosition} will be set to 5 and 8, respectively, for the
 323      * first occurrence of the timezone pattern character {@code 'z'}.
 324      * @return the string buffer passed in as {@code toAppendTo},
 325      *         with formatted text appended.
 326      * @throws    IllegalArgumentException if the {@code Format} cannot format
 327      *            the given {@code obj}.
 328      * @see java.text.Format
 329      */
 330     public final StringBuffer format(Object obj, StringBuffer toAppendTo,
 331                                      FieldPosition fieldPosition)
 332     {
 333         if (obj instanceof Date)
 334             return format( (Date)obj, toAppendTo, fieldPosition );
 335         else if (obj instanceof Number)
 336             return format( new Date(((Number)obj).longValue()),
 337                           toAppendTo, fieldPosition );
 338         else
 339             throw new IllegalArgumentException("Cannot format given Object as a Date");
 340     }
 341 
 342     /**
 343      * Formats a {@link Date} into a date-time string. The formatted
 344      * string is appended to the given {@code StringBuffer}.
 345      *
 346      * @param date a Date to be formatted into a date-time string.
 347      * @param toAppendTo the string buffer for the returning date-time string.
 348      * @param fieldPosition keeps track on the position of the field within
 349      * the returned string. For example, given a date-time text
 350      * {@code "1996.07.10 AD at 15:08:56 PDT"}, if the given {@code fieldPosition}
 351      * is {@link DateFormat#YEAR_FIELD}, the begin index and end index of
 352      * {@code fieldPosition} will be set to 0 and 4, respectively.
 353      * Notice that if the same date-time field appears more than once in a
 354      * pattern, the {@code fieldPosition} will be set for the first occurrence
 355      * of that date-time field. For instance, formatting a {@code Date} to the
 356      * date-time string {@code "1 PM PDT (Pacific Daylight Time)"} using the
 357      * pattern {@code "h a z (zzzz)"} and the alignment field
 358      * {@link DateFormat#TIMEZONE_FIELD}, the begin index and end index of
 359      * {@code fieldPosition} will be set to 5 and 8, respectively, for the
 360      * first occurrence of the timezone pattern character {@code 'z'}.
 361      * @return the string buffer passed in as {@code toAppendTo}, with formatted
 362      * text appended.
 363      */
 364     public abstract StringBuffer format(Date date, StringBuffer toAppendTo,
 365                                         FieldPosition fieldPosition);
 366 
 367     /**
 368       * Formats a {@link Date} into a date-time string.
 369       *
 370       * @param date the time value to be formatted into a date-time string.
 371       * @return the formatted date-time string.
 372      */
 373     public final String format(Date date)
 374     {
 375         return format(date, new StringBuffer(),
 376                       DontCareFieldPosition.INSTANCE).toString();
 377     }
 378 
 379     /**
 380      * Parses text from the beginning of the given string to produce a date.
 381      * The method may not use the entire text of the given string.
 382      * <p>
 383      * See the {@link #parse(String, ParsePosition)} method for more information
 384      * on date parsing.
 385      *
 386      * @param source A <code>String</code> whose beginning should be parsed.
 387      * @return A <code>Date</code> parsed from the string.
 388      * @throws    ParseException if the beginning of the specified string
 389      *            cannot be parsed.
 390      */
 391     public Date parse(String source) throws ParseException
 392     {
 393         ParsePosition pos = new ParsePosition(0);
 394         Date result = parse(source, pos);
 395         if (pos.index == 0)
 396             throw new ParseException("Unparseable date: \"" + source + "\"" ,
 397                 pos.errorIndex);
 398         return result;
 399     }
 400 
 401     /**
 402      * Parse a date/time string according to the given parse position.  For
 403      * example, a time text {@code "07/10/96 4:5 PM, PDT"} will be parsed into a {@code Date}
 404      * that is equivalent to {@code Date(837039900000L)}.
 405      *
 406      * <p> By default, parsing is lenient: If the input is not in the form used
 407      * by this object's format method but can still be parsed as a date, then
 408      * the parse succeeds.  Clients may insist on strict adherence to the
 409      * format by calling {@link #setLenient(boolean) setLenient(false)}.
 410      *
 411      * <p>This parsing operation uses the {@link #calendar} to produce
 412      * a {@code Date}. As a result, the {@code calendar}'s date-time
 413      * fields and the {@code TimeZone} value may have been
 414      * overwritten, depending on subclass implementations. Any {@code
 415      * TimeZone} value that has previously been set by a call to
 416      * {@link #setTimeZone(java.util.TimeZone) setTimeZone} may need
 417      * to be restored for further operations.
 418      *
 419      * @param source  The date/time string to be parsed
 420      *
 421      * @param pos   On input, the position at which to start parsing; on
 422      *              output, the position at which parsing terminated, or the
 423      *              start position if the parse failed.
 424      *
 425      * @return      A {@code Date}, or {@code null} if the input could not be parsed
 426      */
 427     public abstract Date parse(String source, ParsePosition pos);
 428 
 429     /**
 430      * Parses text from a string to produce a <code>Date</code>.
 431      * <p>
 432      * The method attempts to parse text starting at the index given by
 433      * <code>pos</code>.
 434      * If parsing succeeds, then the index of <code>pos</code> is updated
 435      * to the index after the last character used (parsing does not necessarily
 436      * use all characters up to the end of the string), and the parsed
 437      * date is returned. The updated <code>pos</code> can be used to
 438      * indicate the starting point for the next call to this method.
 439      * If an error occurs, then the index of <code>pos</code> is not
 440      * changed, the error index of <code>pos</code> is set to the index of
 441      * the character where the error occurred, and null is returned.
 442      * <p>
 443      * See the {@link #parse(String, ParsePosition)} method for more information
 444      * on date parsing.
 445      *
 446      * @param source A <code>String</code>, part of which should be parsed.
 447      * @param pos A <code>ParsePosition</code> object with index and error
 448      *            index information as described above.
 449      * @return A <code>Date</code> parsed from the string. In case of
 450      *         error, returns null.
 451      * @throws NullPointerException if {@code source} or {@code pos} is null.
 452      */
 453     public Object parseObject(String source, ParsePosition pos) {
 454         return parse(source, pos);
 455     }
 456 
 457     /**
 458      * Constant for full style pattern.
 459      */
 460     public static final int FULL = 0;
 461     /**
 462      * Constant for long style pattern.
 463      */
 464     public static final int LONG = 1;
 465     /**
 466      * Constant for medium style pattern.
 467      */
 468     public static final int MEDIUM = 2;
 469     /**
 470      * Constant for short style pattern.
 471      */
 472     public static final int SHORT = 3;
 473     /**
 474      * Constant for default style pattern.  Its value is MEDIUM.
 475      */
 476     public static final int DEFAULT = MEDIUM;
 477 
 478     /**
 479      * Gets the time formatter with the default formatting style
 480      * for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.
 481      * <p>This is equivalent to calling
 482      * {@link #getTimeInstance(int, Locale) getTimeInstance(DEFAULT,
 483      *     Locale.getDefault(Locale.Category.FORMAT))}.
 484      * @see java.util.Locale#getDefault(java.util.Locale.Category)
 485      * @see java.util.Locale.Category#FORMAT
 486      * @return a time formatter.
 487      */
 488     public static final DateFormat getTimeInstance()
 489     {
 490         return get(DEFAULT, 0, 1, Locale.getDefault(Locale.Category.FORMAT));
 491     }
 492 
 493     /**
 494      * Gets the time formatter with the given formatting style
 495      * for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.
 496      * <p>This is equivalent to calling
 497      * {@link #getTimeInstance(int, Locale) getTimeInstance(style,
 498      *     Locale.getDefault(Locale.Category.FORMAT))}.
 499      * @see java.util.Locale#getDefault(java.util.Locale.Category)
 500      * @see java.util.Locale.Category#FORMAT
 501      * @param style the given formatting style. For example,
 502      * SHORT for "h:mm a" in the US locale.
 503      * @return a time formatter.
 504      */
 505     public static final DateFormat getTimeInstance(int style)
 506     {
 507         return get(style, 0, 1, Locale.getDefault(Locale.Category.FORMAT));
 508     }
 509 
 510     /**
 511      * Gets the time formatter with the given formatting style
 512      * for the given locale.
 513      * @param style the given formatting style. For example,
 514      * SHORT for "h:mm a" in the US locale.
 515      * @param aLocale the given locale.
 516      * @return a time formatter.
 517      */
 518     public static final DateFormat getTimeInstance(int style,
 519                                                  Locale aLocale)
 520     {
 521         return get(style, 0, 1, aLocale);
 522     }
 523 
 524     /**
 525      * Gets the date formatter with the default formatting style
 526      * for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.
 527      * <p>This is equivalent to calling
 528      * {@link #getDateInstance(int, Locale) getDateInstance(DEFAULT,
 529      *     Locale.getDefault(Locale.Category.FORMAT))}.
 530      * @see java.util.Locale#getDefault(java.util.Locale.Category)
 531      * @see java.util.Locale.Category#FORMAT
 532      * @return a date formatter.
 533      */
 534     public static final DateFormat getDateInstance()
 535     {
 536         return get(0, DEFAULT, 2, Locale.getDefault(Locale.Category.FORMAT));
 537     }
 538 
 539     /**
 540      * Gets the date formatter with the given formatting style
 541      * for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.
 542      * <p>This is equivalent to calling
 543      * {@link #getDateInstance(int, Locale) getDateInstance(style,
 544      *     Locale.getDefault(Locale.Category.FORMAT))}.
 545      * @see java.util.Locale#getDefault(java.util.Locale.Category)
 546      * @see java.util.Locale.Category#FORMAT
 547      * @param style the given formatting style. For example,
 548      * SHORT for "M/d/yy" in the US locale.
 549      * @return a date formatter.
 550      */
 551     public static final DateFormat getDateInstance(int style)
 552     {
 553         return get(0, style, 2, Locale.getDefault(Locale.Category.FORMAT));
 554     }
 555 
 556     /**
 557      * Gets the date formatter with the given formatting style
 558      * for the given locale.
 559      * @param style the given formatting style. For example,
 560      * SHORT for "M/d/yy" in the US locale.
 561      * @param aLocale the given locale.
 562      * @return a date formatter.
 563      */
 564     public static final DateFormat getDateInstance(int style,
 565                                                  Locale aLocale)
 566     {
 567         return get(0, style, 2, aLocale);
 568     }
 569 
 570     /**
 571      * Gets the date/time formatter with the default formatting style
 572      * for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.
 573      * <p>This is equivalent to calling
 574      * {@link #getDateTimeInstance(int, int, Locale) getDateTimeInstance(DEFAULT,
 575      *     DEFAULT, Locale.getDefault(Locale.Category.FORMAT))}.
 576      * @see java.util.Locale#getDefault(java.util.Locale.Category)
 577      * @see java.util.Locale.Category#FORMAT
 578      * @return a date/time formatter.
 579      */
 580     public static final DateFormat getDateTimeInstance()
 581     {
 582         return get(DEFAULT, DEFAULT, 3, Locale.getDefault(Locale.Category.FORMAT));
 583     }
 584 
 585     /**
 586      * Gets the date/time formatter with the given date and time
 587      * formatting styles for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.
 588      * <p>This is equivalent to calling
 589      * {@link #getDateTimeInstance(int, int, Locale) getDateTimeInstance(dateStyle,
 590      *     timeStyle, Locale.getDefault(Locale.Category.FORMAT))}.
 591      * @see java.util.Locale#getDefault(java.util.Locale.Category)
 592      * @see java.util.Locale.Category#FORMAT
 593      * @param dateStyle the given date formatting style. For example,
 594      * SHORT for "M/d/yy" in the US locale.
 595      * @param timeStyle the given time formatting style. For example,
 596      * SHORT for "h:mm a" in the US locale.
 597      * @return a date/time formatter.
 598      */
 599     public static final DateFormat getDateTimeInstance(int dateStyle,
 600                                                        int timeStyle)
 601     {
 602         return get(timeStyle, dateStyle, 3, Locale.getDefault(Locale.Category.FORMAT));
 603     }
 604 
 605     /**
 606      * Gets the date/time formatter with the given formatting styles
 607      * for the given locale.
 608      * @param dateStyle the given date formatting style.
 609      * @param timeStyle the given time formatting style.
 610      * @param aLocale the given locale.
 611      * @return a date/time formatter.
 612      */
 613     public static final DateFormat
 614         getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale)
 615     {
 616         return get(timeStyle, dateStyle, 3, aLocale);
 617     }
 618 
 619     /**
 620      * Get a default date/time formatter that uses the SHORT style for both the
 621      * date and the time.
 622      *
 623      * @return a date/time formatter
 624      */
 625     public static final DateFormat getInstance() {
 626         return getDateTimeInstance(SHORT, SHORT);
 627     }
 628 
 629     /**
 630      * Returns an array of all locales for which the
 631      * <code>get*Instance</code> methods of this class can return
 632      * localized instances.
 633      * The returned array represents the union of locales supported by the Java
 634      * runtime and by installed
 635      * {@link java.text.spi.DateFormatProvider DateFormatProvider} implementations.
 636      * It must contain at least a <code>Locale</code> instance equal to
 637      * {@link java.util.Locale#US Locale.US}.
 638      *
 639      * @return An array of locales for which localized
 640      *         <code>DateFormat</code> instances are available.
 641      */
 642     public static Locale[] getAvailableLocales()
 643     {
 644         LocaleServiceProviderPool pool =
 645             LocaleServiceProviderPool.getPool(DateFormatProvider.class);
 646         return pool.getAvailableLocales();
 647     }
 648 
 649     /**
 650      * Set the calendar to be used by this date format.  Initially, the default
 651      * calendar for the specified or default locale is used.
 652      *
 653      * <p>Any {@link java.util.TimeZone TimeZone} and {@linkplain
 654      * #isLenient() leniency} values that have previously been set are
 655      * overwritten by {@code newCalendar}'s values.
 656      *
 657      * @param newCalendar the new {@code Calendar} to be used by the date format
 658      */
 659     public void setCalendar(Calendar newCalendar)
 660     {
 661         this.calendar = newCalendar;
 662     }
 663 
 664     /**
 665      * Gets the calendar associated with this date/time formatter.
 666      *
 667      * @return the calendar associated with this date/time formatter.
 668      */
 669     public Calendar getCalendar()
 670     {
 671         return calendar;
 672     }
 673 
 674     /**
 675      * Allows you to set the number formatter.
 676      * @param newNumberFormat the given new NumberFormat.
 677      */
 678     public void setNumberFormat(NumberFormat newNumberFormat)
 679     {
 680         this.numberFormat = newNumberFormat;
 681     }
 682 
 683     /**
 684      * Gets the number formatter which this date/time formatter uses to
 685      * format and parse a time.
 686      * @return the number formatter which this date/time formatter uses.
 687      */
 688     public NumberFormat getNumberFormat()
 689     {
 690         return numberFormat;
 691     }
 692 
 693     /**
 694      * Sets the time zone for the calendar of this {@code DateFormat} object.
 695      * This method is equivalent to the following call.
 696      * <blockquote><pre>{@code
 697      * getCalendar().setTimeZone(zone)
 698      * }</pre></blockquote>
 699      *
 700      * <p>The {@code TimeZone} set by this method is overwritten by a
 701      * {@link #setCalendar(java.util.Calendar) setCalendar} call.
 702      *
 703      * <p>The {@code TimeZone} set by this method may be overwritten as
 704      * a result of a call to the parse method.
 705      *
 706      * @param zone the given new time zone.
 707      */
 708     public void setTimeZone(TimeZone zone)
 709     {
 710         calendar.setTimeZone(zone);
 711     }
 712 
 713     /**
 714      * Gets the time zone.
 715      * This method is equivalent to the following call.
 716      * <blockquote><pre>{@code
 717      * getCalendar().getTimeZone()
 718      * }</pre></blockquote>
 719      *
 720      * @return the time zone associated with the calendar of DateFormat.
 721      */
 722     public TimeZone getTimeZone()
 723     {
 724         return calendar.getTimeZone();
 725     }
 726 
 727     /**
 728      * Specify whether or not date/time parsing is to be lenient.  With
 729      * lenient parsing, the parser may use heuristics to interpret inputs that
 730      * do not precisely match this object's format.  With strict parsing,
 731      * inputs must match this object's format.
 732      *
 733      * <p>This method is equivalent to the following call.
 734      * <blockquote><pre>{@code
 735      * getCalendar().setLenient(lenient)
 736      * }</pre></blockquote>
 737      *
 738      * <p>This leniency value is overwritten by a call to {@link
 739      * #setCalendar(java.util.Calendar) setCalendar()}.
 740      *
 741      * @param lenient when {@code true}, parsing is lenient
 742      * @see java.util.Calendar#setLenient(boolean)
 743      */
 744     public void setLenient(boolean lenient)
 745     {
 746         calendar.setLenient(lenient);
 747     }
 748 
 749     /**
 750      * Tell whether date/time parsing is to be lenient.
 751      * This method is equivalent to the following call.
 752      * <blockquote><pre>{@code
 753      * getCalendar().isLenient()
 754      * }</pre></blockquote>
 755      *
 756      * @return {@code true} if the {@link #calendar} is lenient;
 757      *         {@code false} otherwise.
 758      * @see java.util.Calendar#isLenient()
 759      */
 760     public boolean isLenient()
 761     {
 762         return calendar.isLenient();
 763     }
 764 
 765     /**
 766      * Overrides hashCode
 767      */
 768     public int hashCode() {
 769         return numberFormat.hashCode();
 770         // just enough fields for a reasonable distribution
 771     }
 772 
 773     /**
 774      * Overrides equals
 775      */
 776     public boolean equals(Object obj) {
 777         if (this == obj) return true;
 778         if (obj == null || getClass() != obj.getClass()) return false;
 779         DateFormat other = (DateFormat) obj;
 780         return (// calendar.equivalentTo(other.calendar) // THIS API DOESN'T EXIST YET!
 781                 calendar.getFirstDayOfWeek() == other.calendar.getFirstDayOfWeek() &&
 782                 calendar.getMinimalDaysInFirstWeek() == other.calendar.getMinimalDaysInFirstWeek() &&
 783                 calendar.isLenient() == other.calendar.isLenient() &&
 784                 calendar.getTimeZone().equals(other.calendar.getTimeZone()) &&
 785                 numberFormat.equals(other.numberFormat));
 786     }
 787 
 788     /**
 789      * Overrides Cloneable
 790      */
 791     public Object clone()
 792     {
 793         DateFormat other = (DateFormat) super.clone();
 794         other.calendar = (Calendar) calendar.clone();
 795         other.numberFormat = (NumberFormat) numberFormat.clone();
 796         return other;
 797     }
 798 
 799     /**
 800      * Creates a DateFormat with the given time and/or date style in the given
 801      * locale.
 802      * @param timeStyle a value from 0 to 3 indicating the time format,
 803      * ignored if flags is 2
 804      * @param dateStyle a value from 0 to 3 indicating the time format,
 805      * ignored if flags is 1
 806      * @param flags either 1 for a time format, 2 for a date format,
 807      * or 3 for a date/time format
 808      * @param loc the locale for the format
 809      */
 810     private static DateFormat get(int timeStyle, int dateStyle,
 811                                   int flags, Locale loc) {
 812         if ((flags & 1) != 0) {
 813             if (timeStyle < 0 || timeStyle > 3) {
 814                 throw new IllegalArgumentException("Illegal time style " + timeStyle);
 815             }
 816         } else {
 817             timeStyle = -1;
 818         }
 819         if ((flags & 2) != 0) {
 820             if (dateStyle < 0 || dateStyle > 3) {
 821                 throw new IllegalArgumentException("Illegal date style " + dateStyle);
 822             }
 823         } else {
 824             dateStyle = -1;
 825         }
 826 
 827         LocaleProviderAdapter adapter = LocaleProviderAdapter.getAdapter(DateFormatProvider.class, loc);
 828         DateFormat dateFormat = get(adapter, timeStyle, dateStyle, loc);
 829         if (dateFormat == null) {
 830             dateFormat = get(LocaleProviderAdapter.forJRE(), timeStyle, dateStyle, loc);
 831         }
 832         return dateFormat;
 833     }
 834 
 835     private static DateFormat get(LocaleProviderAdapter adapter, int timeStyle, int dateStyle, Locale loc) {
 836         DateFormatProvider provider = adapter.getDateFormatProvider();
 837         DateFormat dateFormat;
 838         if (timeStyle == -1) {
 839             dateFormat = provider.getDateInstance(dateStyle, loc);
 840         } else {
 841             if (dateStyle == -1) {
 842                 dateFormat = provider.getTimeInstance(timeStyle, loc);
 843             } else {
 844                 dateFormat = provider.getDateTimeInstance(dateStyle, timeStyle, loc);
 845             }
 846         }
 847         return dateFormat;
 848     }
 849 
 850     /**
 851      * Create a new date format.
 852      */
 853     protected DateFormat() {}
 854 
 855     /**
 856      * Defines constants that are used as attribute keys in the
 857      * <code>AttributedCharacterIterator</code> returned
 858      * from <code>DateFormat.formatToCharacterIterator</code> and as
 859      * field identifiers in <code>FieldPosition</code>.
 860      * <p>
 861      * The class also provides two methods to map
 862      * between its constants and the corresponding Calendar constants.
 863      *
 864      * @since 1.4
 865      * @see java.util.Calendar
 866      */
 867     public static class Field extends Format.Field {
 868 
 869         // Proclaim serial compatibility with 1.4 FCS
 870         @java.io.Serial
 871         private static final long serialVersionUID = 7441350119349544720L;
 872 
 873         // table of all instances in this class, used by readResolve
 874         private static final Map<String, Field> instanceMap = new HashMap<>(18);
 875         // Maps from Calendar constant (such as Calendar.ERA) to Field
 876         // constant (such as Field.ERA).
 877         private static final Field[] calendarToFieldMapping =
 878                                              new Field[Calendar.FIELD_COUNT];
 879 
 880         /** Calendar field. */
 881         private int calendarField;
 882 
 883         /**
 884          * Returns the <code>Field</code> constant that corresponds to
 885          * the <code>Calendar</code> constant <code>calendarField</code>.
 886          * If there is no direct mapping between the <code>Calendar</code>
 887          * constant and a <code>Field</code>, null is returned.
 888          *
 889          * @throws IllegalArgumentException if <code>calendarField</code> is
 890          *         not the value of a <code>Calendar</code> field constant.
 891          * @param calendarField Calendar field constant
 892          * @return Field instance representing calendarField.
 893          * @see java.util.Calendar
 894          */
 895         public static Field ofCalendarField(int calendarField) {
 896             if (calendarField < 0 || calendarField >=
 897                         calendarToFieldMapping.length) {
 898                 throw new IllegalArgumentException("Unknown Calendar constant "
 899                                                    + calendarField);
 900             }
 901             return calendarToFieldMapping[calendarField];
 902         }
 903 
 904         /**
 905          * Creates a <code>Field</code>.
 906          *
 907          * @param name the name of the <code>Field</code>
 908          * @param calendarField the <code>Calendar</code> constant this
 909          *        <code>Field</code> corresponds to; any value, even one
 910          *        outside the range of legal <code>Calendar</code> values may
 911          *        be used, but <code>-1</code> should be used for values
 912          *        that don't correspond to legal <code>Calendar</code> values
 913          */
 914         protected Field(String name, int calendarField) {
 915             super(name);
 916             this.calendarField = calendarField;
 917             if (this.getClass() == DateFormat.Field.class) {
 918                 instanceMap.put(name, this);
 919                 if (calendarField >= 0) {
 920                     // assert(calendarField < Calendar.FIELD_COUNT);
 921                     calendarToFieldMapping[calendarField] = this;
 922                 }
 923             }
 924         }
 925 
 926         /**
 927          * Returns the <code>Calendar</code> field associated with this
 928          * attribute. For example, if this represents the hours field of
 929          * a <code>Calendar</code>, this would return
 930          * <code>Calendar.HOUR</code>. If there is no corresponding
 931          * <code>Calendar</code> constant, this will return -1.
 932          *
 933          * @return Calendar constant for this field
 934          * @see java.util.Calendar
 935          */
 936         public int getCalendarField() {
 937             return calendarField;
 938         }
 939 
 940         /**
 941          * Resolves instances being deserialized to the predefined constants.
 942          *
 943          * @throws InvalidObjectException if the constant could not be
 944          *         resolved.
 945          * @return resolved DateFormat.Field constant
 946          */
 947         @Override
 948         @java.io.Serial
 949         protected Object readResolve() throws InvalidObjectException {
 950             if (this.getClass() != DateFormat.Field.class) {
 951                 throw new InvalidObjectException("subclass didn't correctly implement readResolve");
 952             }
 953 
 954             Object instance = instanceMap.get(getName());
 955             if (instance != null) {
 956                 return instance;
 957             } else {
 958                 throw new InvalidObjectException("unknown attribute name");
 959             }
 960         }
 961 
 962         //
 963         // The constants
 964         //
 965 
 966         /**
 967          * Constant identifying the era field.
 968          */
 969         public static final Field ERA = new Field("era", Calendar.ERA);
 970 
 971         /**
 972          * Constant identifying the year field.
 973          */
 974         public static final Field YEAR = new Field("year", Calendar.YEAR);
 975 
 976         /**
 977          * Constant identifying the month field.
 978          */
 979         public static final Field MONTH = new Field("month", Calendar.MONTH);
 980 
 981         /**
 982          * Constant identifying the day of month field.
 983          */
 984         public static final Field DAY_OF_MONTH = new
 985                             Field("day of month", Calendar.DAY_OF_MONTH);
 986 
 987         /**
 988          * Constant identifying the hour of day field, where the legal values
 989          * are 1 to 24.
 990          */
 991         public static final Field HOUR_OF_DAY1 = new Field("hour of day 1",-1);
 992 
 993         /**
 994          * Constant identifying the hour of day field, where the legal values
 995          * are 0 to 23.
 996          */
 997         public static final Field HOUR_OF_DAY0 = new
 998                Field("hour of day", Calendar.HOUR_OF_DAY);
 999 
1000         /**
1001          * Constant identifying the minute field.
1002          */
1003         public static final Field MINUTE =new Field("minute", Calendar.MINUTE);
1004 
1005         /**
1006          * Constant identifying the second field.
1007          */
1008         public static final Field SECOND =new Field("second", Calendar.SECOND);
1009 
1010         /**
1011          * Constant identifying the millisecond field.
1012          */
1013         public static final Field MILLISECOND = new
1014                 Field("millisecond", Calendar.MILLISECOND);
1015 
1016         /**
1017          * Constant identifying the day of week field.
1018          */
1019         public static final Field DAY_OF_WEEK = new
1020                 Field("day of week", Calendar.DAY_OF_WEEK);
1021 
1022         /**
1023          * Constant identifying the day of year field.
1024          */
1025         public static final Field DAY_OF_YEAR = new
1026                 Field("day of year", Calendar.DAY_OF_YEAR);
1027 
1028         /**
1029          * Constant identifying the day of week field.
1030          */
1031         public static final Field DAY_OF_WEEK_IN_MONTH =
1032                      new Field("day of week in month",
1033                                             Calendar.DAY_OF_WEEK_IN_MONTH);
1034 
1035         /**
1036          * Constant identifying the week of year field.
1037          */
1038         public static final Field WEEK_OF_YEAR = new
1039               Field("week of year", Calendar.WEEK_OF_YEAR);
1040 
1041         /**
1042          * Constant identifying the week of month field.
1043          */
1044         public static final Field WEEK_OF_MONTH = new
1045             Field("week of month", Calendar.WEEK_OF_MONTH);
1046 
1047         /**
1048          * Constant identifying the time of day indicator
1049          * (e.g. "a.m." or "p.m.") field.
1050          */
1051         public static final Field AM_PM = new
1052                             Field("am pm", Calendar.AM_PM);
1053 
1054         /**
1055          * Constant identifying the hour field, where the legal values are
1056          * 1 to 12.
1057          */
1058         public static final Field HOUR1 = new Field("hour 1", -1);
1059 
1060         /**
1061          * Constant identifying the hour field, where the legal values are
1062          * 0 to 11.
1063          */
1064         public static final Field HOUR0 = new
1065                             Field("hour", Calendar.HOUR);
1066 
1067         /**
1068          * Constant identifying the time zone field.
1069          */
1070         public static final Field TIME_ZONE = new Field("time zone", -1);
1071     }
1072 }