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