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