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