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