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