Path: blob/master/src/java.base/share/classes/java/text/DateFormat.java
41152 views
/*1* Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved27* (C) Copyright IBM Corp. 1996 - All Rights Reserved28*29* The original version of this source code and documentation is copyrighted30* and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These31* materials are provided under terms of a License Agreement between Taligent32* and Sun. This technology is protected by multiple US and International33* patents. This notice and attribution to Taligent may not be removed.34* Taligent is a registered trademark of Taligent, Inc.35*36*/3738package java.text;3940import java.io.InvalidObjectException;41import java.text.spi.DateFormatProvider;42import java.util.Calendar;43import java.util.Date;44import java.util.GregorianCalendar;45import java.util.HashMap;46import java.util.Locale;47import java.util.Map;48import java.util.MissingResourceException;49import java.util.ResourceBundle;50import java.util.TimeZone;51import java.util.spi.LocaleServiceProvider;52import sun.util.locale.provider.LocaleProviderAdapter;53import sun.util.locale.provider.LocaleServiceProviderPool;5455/**56* {@code DateFormat} is an abstract class for date/time formatting subclasses which57* formats and parses dates or time in a language-independent manner.58* The date/time formatting subclass, such as {@link SimpleDateFormat}, allows for59* formatting (i.e., date → text), parsing (text → date), and60* normalization. The date is represented as a {@code Date} object or61* as the milliseconds since January 1, 1970, 00:00:00 GMT.62*63* <p>{@code DateFormat} provides many class methods for obtaining default date/time64* formatters based on the default or a given locale and a number of formatting65* styles. The formatting styles include {@link #FULL}, {@link #LONG}, {@link #MEDIUM}, and {@link #SHORT}. More66* detail and examples of using these styles are provided in the method67* descriptions.68*69* <p>{@code DateFormat} helps you to format and parse dates for any locale.70* Your code can be completely independent of the locale conventions for71* months, days of the week, or even the calendar format: lunar vs. solar.72*73* <p>To format a date for the current Locale, use one of the74* static factory methods:75* <blockquote>76* <pre>{@code77* myString = DateFormat.getDateInstance().format(myDate);78* }</pre>79* </blockquote>80* <p>If you are formatting multiple dates, it is81* more efficient to get the format and use it multiple times so that82* the system doesn't have to fetch the information about the local83* language and country conventions multiple times.84* <blockquote>85* <pre>{@code86* DateFormat df = DateFormat.getDateInstance();87* for (int i = 0; i < myDate.length; ++i) {88* output.println(df.format(myDate[i]) + "; ");89* }90* }</pre>91* </blockquote>92* <p>To format a date for a different Locale, specify it in the93* call to {@link #getDateInstance(int, Locale) getDateInstance()}.94* <blockquote>95* <pre>{@code96* DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);97* }</pre>98* </blockquote>99*100* <p>If the specified locale contains "ca" (calendar), "rg" (region override),101* and/or "tz" (timezone) <a href="../util/Locale.html#def_locale_extension">Unicode102* extensions</a>, the calendar, the country and/or the time zone for formatting103* are overridden. If both "ca" and "rg" are specified, the calendar from the "ca"104* extension supersedes the implicit one from the "rg" extension.105*106* <p>You can use a DateFormat to parse also.107* <blockquote>108* <pre>{@code109* myDate = df.parse(myString);110* }</pre>111* </blockquote>112* <p>Use {@code getDateInstance} to get the normal date format for that country.113* There are other static factory methods available.114* Use {@code getTimeInstance} to get the time format for that country.115* Use {@code getDateTimeInstance} to get a date and time format. You can pass in116* different options to these factory methods to control the length of the117* result; from {@link #SHORT} to {@link #MEDIUM} to {@link #LONG} to {@link #FULL}. The exact result depends118* on the locale, but generally:119* <ul><li>{@link #SHORT} is completely numeric, such as {@code 12.13.52} or {@code 3:30pm}120* <li>{@link #MEDIUM} is longer, such as {@code Jan 12, 1952}121* <li>{@link #LONG} is longer, such as {@code January 12, 1952} or {@code 3:30:32pm}122* <li>{@link #FULL} is pretty completely specified, such as123* {@code Tuesday, April 12, 1952 AD or 3:30:42pm PST}.124* </ul>125*126* <p>You can also set the time zone on the format if you wish.127* If you want even more control over the format or parsing,128* (or want to give your users more control),129* you can try casting the {@code DateFormat} you get from the factory methods130* to a {@link SimpleDateFormat}. This will work for the majority131* of countries; just remember to put it in a {@code try} block in case you132* encounter an unusual one.133*134* <p>You can also use forms of the parse and format methods with135* {@link ParsePosition} and {@link FieldPosition} to136* allow you to137* <ul><li>progressively parse through pieces of a string.138* <li>align any particular field, or find out where it is for selection139* on the screen.140* </ul>141*142* <h2><a id="synchronization">Synchronization</a></h2>143*144* <p>145* Date formats are not synchronized.146* It is recommended to create separate format instances for each thread.147* If multiple threads access a format concurrently, it must be synchronized148* externally.149* @apiNote Consider using {@link java.time.format.DateTimeFormatter} as an150* immutable and thread-safe alternative.151*152* @implSpec153* <ul><li>The {@link #format(Date, StringBuffer, FieldPosition)} and154* {@link #parse(String, ParsePosition)} methods may throw155* {@code NullPointerException}, if any of their parameter is {@code null}.156* The subclass may provide its own implementation and specification about157* {@code NullPointerException}.</li>158* <li>The {@link #setCalendar(Calendar)}, {@link159* #setNumberFormat(NumberFormat)} and {@link #setTimeZone(TimeZone)} methods160* do not throw {@code NullPointerException} when their parameter is161* {@code null}, but any subsequent operations on the same instance may throw162* {@code NullPointerException}.</li>163* <li>The {@link #getCalendar()}, {@link #getNumberFormat()} and164* {@link getTimeZone()} methods may return {@code null}, if the respective165* values of this instance is set to {@code null} through the corresponding166* setter methods. For Example: {@link #getTimeZone()} may return {@code null},167* if the {@code TimeZone} value of this instance is set as168* {@link #setTimeZone(java.util.TimeZone) setTimeZone(null)}.</li>169* </ul>170*171* @see Format172* @see NumberFormat173* @see SimpleDateFormat174* @see java.util.Calendar175* @see java.util.GregorianCalendar176* @see java.util.TimeZone177* @see java.time.format.DateTimeFormatter178* @author Mark Davis, Chen-Lieh Huang, Alan Liu179* @since 1.1180*/181public abstract class DateFormat extends Format {182183/**184* The {@link Calendar} instance used for calculating the date-time fields185* and the instant of time. This field is used for both formatting and186* parsing.187*188* <p>Subclasses should initialize this field to a {@link Calendar}189* appropriate for the {@link Locale} associated with this190* {@code DateFormat}.191* @serial192*/193protected Calendar calendar;194195/**196* The number formatter that {@code DateFormat} uses to format numbers197* in dates and times. Subclasses should initialize this to a number format198* appropriate for the locale associated with this {@code DateFormat}.199* @serial200*/201protected NumberFormat numberFormat;202203/**204* Useful constant for ERA field alignment.205* Used in FieldPosition of date/time formatting.206*/207public static final int ERA_FIELD = 0;208/**209* Useful constant for YEAR field alignment.210* Used in FieldPosition of date/time formatting.211*/212public static final int YEAR_FIELD = 1;213/**214* Useful constant for MONTH field alignment.215* Used in FieldPosition of date/time formatting.216*/217public static final int MONTH_FIELD = 2;218/**219* Useful constant for DATE field alignment.220* Used in FieldPosition of date/time formatting.221*/222public static final int DATE_FIELD = 3;223/**224* Useful constant for one-based HOUR_OF_DAY field alignment.225* Used in FieldPosition of date/time formatting.226* HOUR_OF_DAY1_FIELD is used for the one-based 24-hour clock.227* For example, 23:59 + 01:00 results in 24:59.228*/229public static final int HOUR_OF_DAY1_FIELD = 4;230/**231* Useful constant for zero-based HOUR_OF_DAY field alignment.232* Used in FieldPosition of date/time formatting.233* HOUR_OF_DAY0_FIELD is used for the zero-based 24-hour clock.234* For example, 23:59 + 01:00 results in 00:59.235*/236public static final int HOUR_OF_DAY0_FIELD = 5;237/**238* Useful constant for MINUTE field alignment.239* Used in FieldPosition of date/time formatting.240*/241public static final int MINUTE_FIELD = 6;242/**243* Useful constant for SECOND field alignment.244* Used in FieldPosition of date/time formatting.245*/246public static final int SECOND_FIELD = 7;247/**248* Useful constant for MILLISECOND field alignment.249* Used in FieldPosition of date/time formatting.250*/251public static final int MILLISECOND_FIELD = 8;252/**253* Useful constant for DAY_OF_WEEK field alignment.254* Used in FieldPosition of date/time formatting.255*/256public static final int DAY_OF_WEEK_FIELD = 9;257/**258* Useful constant for DAY_OF_YEAR field alignment.259* Used in FieldPosition of date/time formatting.260*/261public static final int DAY_OF_YEAR_FIELD = 10;262/**263* Useful constant for DAY_OF_WEEK_IN_MONTH field alignment.264* Used in FieldPosition of date/time formatting.265*/266public static final int DAY_OF_WEEK_IN_MONTH_FIELD = 11;267/**268* Useful constant for WEEK_OF_YEAR field alignment.269* Used in FieldPosition of date/time formatting.270*/271public static final int WEEK_OF_YEAR_FIELD = 12;272/**273* Useful constant for WEEK_OF_MONTH field alignment.274* Used in FieldPosition of date/time formatting.275*/276public static final int WEEK_OF_MONTH_FIELD = 13;277/**278* Useful constant for AM_PM field alignment.279* Used in FieldPosition of date/time formatting.280*/281public static final int AM_PM_FIELD = 14;282/**283* Useful constant for one-based HOUR field alignment.284* Used in FieldPosition of date/time formatting.285* HOUR1_FIELD is used for the one-based 12-hour clock.286* For example, 11:30 PM + 1 hour results in 12:30 AM.287*/288public static final int HOUR1_FIELD = 15;289/**290* Useful constant for zero-based HOUR field alignment.291* Used in FieldPosition of date/time formatting.292* HOUR0_FIELD is used for the zero-based 12-hour clock.293* For example, 11:30 PM + 1 hour results in 00:30 AM.294*/295public static final int HOUR0_FIELD = 16;296/**297* Useful constant for TIMEZONE field alignment.298* Used in FieldPosition of date/time formatting.299*/300public static final int TIMEZONE_FIELD = 17;301302// Proclaim serial compatibility with 1.1 FCS303@java.io.Serial304private static final long serialVersionUID = 7218322306649953788L;305306/**307* Formats the given {@code Object} into a date-time string. The formatted308* string is appended to the given {@code StringBuffer}.309*310* @param obj Must be a {@code Date} or a {@code Number} representing a311* millisecond offset from the <a href="../util/Calendar.html#Epoch">Epoch</a>.312* @param toAppendTo The string buffer for the returning date-time string.313* @param fieldPosition keeps track on the position of the field within314* the returned string. For example, given a date-time text315* {@code "1996.07.10 AD at 15:08:56 PDT"}, if the given {@code fieldPosition}316* is {@link DateFormat#YEAR_FIELD}, the begin index and end index of317* {@code fieldPosition} will be set to 0 and 4, respectively.318* Notice that if the same date-time field appears more than once in a319* pattern, the {@code fieldPosition} will be set for the first occurrence320* of that date-time field. For instance, formatting a {@code Date} to the321* date-time string {@code "1 PM PDT (Pacific Daylight Time)"} using the322* pattern {@code "h a z (zzzz)"} and the alignment field323* {@link DateFormat#TIMEZONE_FIELD}, the begin index and end index of324* {@code fieldPosition} will be set to 5 and 8, respectively, for the325* first occurrence of the timezone pattern character {@code 'z'}.326* @return the string buffer passed in as {@code toAppendTo},327* with formatted text appended.328* @throws IllegalArgumentException if the {@code Format} cannot format329* the given {@code obj}.330* @see java.text.Format331*/332public final StringBuffer format(Object obj, StringBuffer toAppendTo,333FieldPosition fieldPosition)334{335if (obj instanceof Date)336return format( (Date)obj, toAppendTo, fieldPosition );337else if (obj instanceof Number)338return format( new Date(((Number)obj).longValue()),339toAppendTo, fieldPosition );340else341throw new IllegalArgumentException("Cannot format given Object as a Date");342}343344/**345* Formats a {@link Date} into a date-time string. The formatted346* string is appended to the given {@code StringBuffer}.347*348* @param date a Date to be formatted into a date-time string.349* @param toAppendTo the string buffer for the returning date-time string.350* @param fieldPosition keeps track on the position of the field within351* the returned string. For example, given a date-time text352* {@code "1996.07.10 AD at 15:08:56 PDT"}, if the given {@code fieldPosition}353* is {@link DateFormat#YEAR_FIELD}, the begin index and end index of354* {@code fieldPosition} will be set to 0 and 4, respectively.355* Notice that if the same date-time field appears more than once in a356* pattern, the {@code fieldPosition} will be set for the first occurrence357* of that date-time field. For instance, formatting a {@code Date} to the358* date-time string {@code "1 PM PDT (Pacific Daylight Time)"} using the359* pattern {@code "h a z (zzzz)"} and the alignment field360* {@link DateFormat#TIMEZONE_FIELD}, the begin index and end index of361* {@code fieldPosition} will be set to 5 and 8, respectively, for the362* first occurrence of the timezone pattern character {@code 'z'}.363* @return the string buffer passed in as {@code toAppendTo}, with formatted364* text appended.365*/366public abstract StringBuffer format(Date date, StringBuffer toAppendTo,367FieldPosition fieldPosition);368369/**370* Formats a {@link Date} into a date-time string.371*372* @param date the time value to be formatted into a date-time string.373* @return the formatted date-time string.374*/375public final String format(Date date)376{377return format(date, new StringBuffer(),378DontCareFieldPosition.INSTANCE).toString();379}380381/**382* Parses text from the beginning of the given string to produce a date.383* The method may not use the entire text of the given string.384* <p>385* See the {@link #parse(String, ParsePosition)} method for more information386* on date parsing.387*388* @param source A {@code String} whose beginning should be parsed.389* @return A {@code Date} parsed from the string.390* @throws ParseException if the beginning of the specified string391* cannot be parsed.392*/393public Date parse(String source) throws ParseException394{395ParsePosition pos = new ParsePosition(0);396Date result = parse(source, pos);397if (pos.index == 0)398throw new ParseException("Unparseable date: \"" + source + "\"" ,399pos.errorIndex);400return result;401}402403/**404* Parse a date/time string according to the given parse position. For405* example, a time text {@code "07/10/96 4:5 PM, PDT"} will be parsed into a {@code Date}406* that is equivalent to {@code Date(837039900000L)}.407*408* <p> By default, parsing is lenient: If the input is not in the form used409* by this object's format method but can still be parsed as a date, then410* the parse succeeds. Clients may insist on strict adherence to the411* format by calling {@link #setLenient(boolean) setLenient(false)}.412*413* <p>This parsing operation uses the {@link #calendar} to produce414* a {@code Date}. As a result, the {@code calendar}'s date-time415* fields and the {@code TimeZone} value may have been416* overwritten, depending on subclass implementations. Any {@code417* TimeZone} value that has previously been set by a call to418* {@link #setTimeZone(java.util.TimeZone) setTimeZone} may need419* to be restored for further operations.420*421* @param source The date/time string to be parsed422*423* @param pos On input, the position at which to start parsing; on424* output, the position at which parsing terminated, or the425* start position if the parse failed.426*427* @return A {@code Date}, or {@code null} if the input could not be parsed428*/429public abstract Date parse(String source, ParsePosition pos);430431/**432* Parses text from a string to produce a {@code Date}.433* <p>434* The method attempts to parse text starting at the index given by435* {@code pos}.436* If parsing succeeds, then the index of {@code pos} is updated437* to the index after the last character used (parsing does not necessarily438* use all characters up to the end of the string), and the parsed439* date is returned. The updated {@code pos} can be used to440* indicate the starting point for the next call to this method.441* If an error occurs, then the index of {@code pos} is not442* changed, the error index of {@code pos} is set to the index of443* the character where the error occurred, and null is returned.444* <p>445* See the {@link #parse(String, ParsePosition)} method for more information446* on date parsing.447*448* @param source A {@code String}, part of which should be parsed.449* @param pos A {@code ParsePosition} object with index and error450* index information as described above.451* @return A {@code Date} parsed from the string. In case of452* error, returns null.453* @throws NullPointerException if {@code source} or {@code pos} is null.454*/455public Object parseObject(String source, ParsePosition pos) {456return parse(source, pos);457}458459/**460* Constant for full style pattern.461*/462public static final int FULL = 0;463/**464* Constant for long style pattern.465*/466public static final int LONG = 1;467/**468* Constant for medium style pattern.469*/470public static final int MEDIUM = 2;471/**472* Constant for short style pattern.473*/474public static final int SHORT = 3;475/**476* Constant for default style pattern. Its value is MEDIUM.477*/478public static final int DEFAULT = MEDIUM;479480/**481* Gets the time formatter with the default formatting style482* for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.483* <p>This is equivalent to calling484* {@link #getTimeInstance(int, Locale) getTimeInstance(DEFAULT,485* Locale.getDefault(Locale.Category.FORMAT))}.486* @see java.util.Locale#getDefault(java.util.Locale.Category)487* @see java.util.Locale.Category#FORMAT488* @return a time formatter.489*/490public static final DateFormat getTimeInstance()491{492return get(DEFAULT, 0, 1, Locale.getDefault(Locale.Category.FORMAT));493}494495/**496* Gets the time formatter with the given formatting style497* for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.498* <p>This is equivalent to calling499* {@link #getTimeInstance(int, Locale) getTimeInstance(style,500* Locale.getDefault(Locale.Category.FORMAT))}.501* @see java.util.Locale#getDefault(java.util.Locale.Category)502* @see java.util.Locale.Category#FORMAT503* @param style the given formatting style. For example,504* SHORT for "h:mm a" in the US locale.505* @return a time formatter.506*/507public static final DateFormat getTimeInstance(int style)508{509return get(style, 0, 1, Locale.getDefault(Locale.Category.FORMAT));510}511512/**513* Gets the time formatter with the given formatting style514* for the given locale.515* @param style the given formatting style. For example,516* SHORT for "h:mm a" in the US locale.517* @param aLocale the given locale.518* @return a time formatter.519*/520public static final DateFormat getTimeInstance(int style,521Locale aLocale)522{523return get(style, 0, 1, aLocale);524}525526/**527* Gets the date formatter with the default formatting style528* for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.529* <p>This is equivalent to calling530* {@link #getDateInstance(int, Locale) getDateInstance(DEFAULT,531* Locale.getDefault(Locale.Category.FORMAT))}.532* @see java.util.Locale#getDefault(java.util.Locale.Category)533* @see java.util.Locale.Category#FORMAT534* @return a date formatter.535*/536public static final DateFormat getDateInstance()537{538return get(0, DEFAULT, 2, Locale.getDefault(Locale.Category.FORMAT));539}540541/**542* Gets the date formatter with the given formatting style543* for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.544* <p>This is equivalent to calling545* {@link #getDateInstance(int, Locale) getDateInstance(style,546* Locale.getDefault(Locale.Category.FORMAT))}.547* @see java.util.Locale#getDefault(java.util.Locale.Category)548* @see java.util.Locale.Category#FORMAT549* @param style the given formatting style. For example,550* SHORT for "M/d/yy" in the US locale.551* @return a date formatter.552*/553public static final DateFormat getDateInstance(int style)554{555return get(0, style, 2, Locale.getDefault(Locale.Category.FORMAT));556}557558/**559* Gets the date formatter with the given formatting style560* for the given locale.561* @param style the given formatting style. For example,562* SHORT for "M/d/yy" in the US locale.563* @param aLocale the given locale.564* @return a date formatter.565*/566public static final DateFormat getDateInstance(int style,567Locale aLocale)568{569return get(0, style, 2, aLocale);570}571572/**573* Gets the date/time formatter with the default formatting style574* for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.575* <p>This is equivalent to calling576* {@link #getDateTimeInstance(int, int, Locale) getDateTimeInstance(DEFAULT,577* DEFAULT, Locale.getDefault(Locale.Category.FORMAT))}.578* @see java.util.Locale#getDefault(java.util.Locale.Category)579* @see java.util.Locale.Category#FORMAT580* @return a date/time formatter.581*/582public static final DateFormat getDateTimeInstance()583{584return get(DEFAULT, DEFAULT, 3, Locale.getDefault(Locale.Category.FORMAT));585}586587/**588* Gets the date/time formatter with the given date and time589* formatting styles for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.590* <p>This is equivalent to calling591* {@link #getDateTimeInstance(int, int, Locale) getDateTimeInstance(dateStyle,592* timeStyle, Locale.getDefault(Locale.Category.FORMAT))}.593* @see java.util.Locale#getDefault(java.util.Locale.Category)594* @see java.util.Locale.Category#FORMAT595* @param dateStyle the given date formatting style. For example,596* SHORT for "M/d/yy" in the US locale.597* @param timeStyle the given time formatting style. For example,598* SHORT for "h:mm a" in the US locale.599* @return a date/time formatter.600*/601public static final DateFormat getDateTimeInstance(int dateStyle,602int timeStyle)603{604return get(timeStyle, dateStyle, 3, Locale.getDefault(Locale.Category.FORMAT));605}606607/**608* Gets the date/time formatter with the given formatting styles609* for the given locale.610* @param dateStyle the given date formatting style.611* @param timeStyle the given time formatting style.612* @param aLocale the given locale.613* @return a date/time formatter.614*/615public static final DateFormat616getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale)617{618return get(timeStyle, dateStyle, 3, aLocale);619}620621/**622* Get a default date/time formatter that uses the SHORT style for both the623* date and the time.624*625* @return a date/time formatter626*/627public static final DateFormat getInstance() {628return getDateTimeInstance(SHORT, SHORT);629}630631/**632* Returns an array of all locales for which the633* {@code get*Instance} methods of this class can return634* localized instances.635* The returned array represents the union of locales supported by the Java636* runtime and by installed637* {@link java.text.spi.DateFormatProvider DateFormatProvider} implementations.638* It must contain at least a {@code Locale} instance equal to639* {@link java.util.Locale#US Locale.US}.640*641* @return An array of locales for which localized642* {@code DateFormat} instances are available.643*/644public static Locale[] getAvailableLocales()645{646LocaleServiceProviderPool pool =647LocaleServiceProviderPool.getPool(DateFormatProvider.class);648return pool.getAvailableLocales();649}650651/**652* Set the calendar to be used by this date format. Initially, the default653* calendar for the specified or default locale is used.654*655* <p>Any {@link java.util.TimeZone TimeZone} and {@linkplain656* #isLenient() leniency} values that have previously been set are657* overwritten by {@code newCalendar}'s values.658*659* @param newCalendar the new {@code Calendar} to be used by the date format660*/661public void setCalendar(Calendar newCalendar)662{663this.calendar = newCalendar;664}665666/**667* Gets the calendar associated with this date/time formatter.668*669* @return the calendar associated with this date/time formatter.670*/671public Calendar getCalendar()672{673return calendar;674}675676/**677* Allows you to set the number formatter.678* @param newNumberFormat the given new NumberFormat.679*/680public void setNumberFormat(NumberFormat newNumberFormat)681{682this.numberFormat = newNumberFormat;683}684685/**686* Gets the number formatter which this date/time formatter uses to687* format and parse a time.688* @return the number formatter which this date/time formatter uses.689*/690public NumberFormat getNumberFormat()691{692return numberFormat;693}694695/**696* Sets the time zone for the calendar of this {@code DateFormat} object.697* This method is equivalent to the following call.698* <blockquote><pre>{@code699* getCalendar().setTimeZone(zone)700* }</pre></blockquote>701*702* <p>The {@code TimeZone} set by this method is overwritten by a703* {@link #setCalendar(java.util.Calendar) setCalendar} call.704*705* <p>The {@code TimeZone} set by this method may be overwritten as706* a result of a call to the parse method.707*708* @param zone the given new time zone.709*/710public void setTimeZone(TimeZone zone)711{712calendar.setTimeZone(zone);713}714715/**716* Gets the time zone.717* This method is equivalent to the following call.718* <blockquote><pre>{@code719* getCalendar().getTimeZone()720* }</pre></blockquote>721*722* @return the time zone associated with the calendar of DateFormat.723*/724public TimeZone getTimeZone()725{726return calendar.getTimeZone();727}728729/**730* Specify whether or not date/time parsing is to be lenient. With731* lenient parsing, the parser may use heuristics to interpret inputs that732* do not precisely match this object's format. With strict parsing,733* inputs must match this object's format.734*735* <p>This method is equivalent to the following call.736* <blockquote><pre>{@code737* getCalendar().setLenient(lenient)738* }</pre></blockquote>739*740* <p>This leniency value is overwritten by a call to {@link741* #setCalendar(java.util.Calendar) setCalendar()}.742*743* @param lenient when {@code true}, parsing is lenient744* @see java.util.Calendar#setLenient(boolean)745*/746public void setLenient(boolean lenient)747{748calendar.setLenient(lenient);749}750751/**752* Tell whether date/time parsing is to be lenient.753* This method is equivalent to the following call.754* <blockquote><pre>{@code755* getCalendar().isLenient()756* }</pre></blockquote>757*758* @return {@code true} if the {@link #calendar} is lenient;759* {@code false} otherwise.760* @see java.util.Calendar#isLenient()761*/762public boolean isLenient()763{764return calendar.isLenient();765}766767/**768* Overrides hashCode769*/770public int hashCode() {771return numberFormat.hashCode();772// just enough fields for a reasonable distribution773}774775/**776* Overrides equals777*/778public boolean equals(Object obj) {779if (this == obj) return true;780if (obj == null || getClass() != obj.getClass()) return false;781DateFormat other = (DateFormat) obj;782return (// calendar.equivalentTo(other.calendar) // THIS API DOESN'T EXIST YET!783calendar.getFirstDayOfWeek() == other.calendar.getFirstDayOfWeek() &&784calendar.getMinimalDaysInFirstWeek() == other.calendar.getMinimalDaysInFirstWeek() &&785calendar.isLenient() == other.calendar.isLenient() &&786calendar.getTimeZone().equals(other.calendar.getTimeZone()) &&787numberFormat.equals(other.numberFormat));788}789790/**791* Overrides Cloneable792*/793public Object clone()794{795DateFormat other = (DateFormat) super.clone();796other.calendar = (Calendar) calendar.clone();797other.numberFormat = (NumberFormat) numberFormat.clone();798return other;799}800801/**802* Creates a DateFormat with the given time and/or date style in the given803* locale.804* @param timeStyle a value from 0 to 3 indicating the time format,805* ignored if flags is 2806* @param dateStyle a value from 0 to 3 indicating the time format,807* ignored if flags is 1808* @param flags either 1 for a time format, 2 for a date format,809* or 3 for a date/time format810* @param loc the locale for the format811*/812private static DateFormat get(int timeStyle, int dateStyle,813int flags, Locale loc) {814if ((flags & 1) != 0) {815if (timeStyle < 0 || timeStyle > 3) {816throw new IllegalArgumentException("Illegal time style " + timeStyle);817}818} else {819timeStyle = -1;820}821if ((flags & 2) != 0) {822if (dateStyle < 0 || dateStyle > 3) {823throw new IllegalArgumentException("Illegal date style " + dateStyle);824}825} else {826dateStyle = -1;827}828829LocaleProviderAdapter adapter = LocaleProviderAdapter.getAdapter(DateFormatProvider.class, loc);830DateFormat dateFormat = get(adapter, timeStyle, dateStyle, loc);831if (dateFormat == null) {832dateFormat = get(LocaleProviderAdapter.forJRE(), timeStyle, dateStyle, loc);833}834return dateFormat;835}836837private static DateFormat get(LocaleProviderAdapter adapter, int timeStyle, int dateStyle, Locale loc) {838DateFormatProvider provider = adapter.getDateFormatProvider();839DateFormat dateFormat;840if (timeStyle == -1) {841dateFormat = provider.getDateInstance(dateStyle, loc);842} else {843if (dateStyle == -1) {844dateFormat = provider.getTimeInstance(timeStyle, loc);845} else {846dateFormat = provider.getDateTimeInstance(dateStyle, timeStyle, loc);847}848}849return dateFormat;850}851852/**853* Create a new date format.854*/855protected DateFormat() {}856857/**858* Defines constants that are used as attribute keys in the859* {@code AttributedCharacterIterator} returned860* from {@code DateFormat.formatToCharacterIterator} and as861* field identifiers in {@code FieldPosition}.862* <p>863* The class also provides two methods to map864* between its constants and the corresponding Calendar constants.865*866* @since 1.4867* @see java.util.Calendar868*/869public static class Field extends Format.Field {870871// Proclaim serial compatibility with 1.4 FCS872@java.io.Serial873private static final long serialVersionUID = 7441350119349544720L;874875// table of all instances in this class, used by readResolve876private static final Map<String, Field> instanceMap = new HashMap<>(18);877// Maps from Calendar constant (such as Calendar.ERA) to Field878// constant (such as Field.ERA).879private static final Field[] calendarToFieldMapping =880new Field[Calendar.FIELD_COUNT];881882/** Calendar field. */883private int calendarField;884885/**886* Returns the {@code Field} constant that corresponds to887* the {@code Calendar} constant {@code calendarField}.888* If there is no direct mapping between the {@code Calendar}889* constant and a {@code Field}, null is returned.890*891* @throws IllegalArgumentException if {@code calendarField} is892* not the value of a {@code Calendar} field constant.893* @param calendarField Calendar field constant894* @return Field instance representing calendarField.895* @see java.util.Calendar896*/897public static Field ofCalendarField(int calendarField) {898if (calendarField < 0 || calendarField >=899calendarToFieldMapping.length) {900throw new IllegalArgumentException("Unknown Calendar constant "901+ calendarField);902}903return calendarToFieldMapping[calendarField];904}905906/**907* Creates a {@code Field}.908*909* @param name the name of the {@code Field}910* @param calendarField the {@code Calendar} constant this911* {@code Field} corresponds to; any value, even one912* outside the range of legal {@code Calendar} values may913* be used, but {@code -1} should be used for values914* that don't correspond to legal {@code Calendar} values915*/916protected Field(String name, int calendarField) {917super(name);918this.calendarField = calendarField;919if (this.getClass() == DateFormat.Field.class) {920instanceMap.put(name, this);921if (calendarField >= 0) {922// assert(calendarField < Calendar.FIELD_COUNT);923calendarToFieldMapping[calendarField] = this;924}925}926}927928/**929* Returns the {@code Calendar} field associated with this930* attribute. For example, if this represents the hours field of931* a {@code Calendar}, this would return932* {@code Calendar.HOUR}. If there is no corresponding933* {@code Calendar} constant, this will return -1.934*935* @return Calendar constant for this field936* @see java.util.Calendar937*/938public int getCalendarField() {939return calendarField;940}941942/**943* Resolves instances being deserialized to the predefined constants.944*945* @throws InvalidObjectException if the constant could not be946* resolved.947* @return resolved DateFormat.Field constant948*/949@Override950@java.io.Serial951protected Object readResolve() throws InvalidObjectException {952if (this.getClass() != DateFormat.Field.class) {953throw new InvalidObjectException("subclass didn't correctly implement readResolve");954}955956Object instance = instanceMap.get(getName());957if (instance != null) {958return instance;959} else {960throw new InvalidObjectException("unknown attribute name");961}962}963964//965// The constants966//967968/**969* Constant identifying the era field.970*/971public static final Field ERA = new Field("era", Calendar.ERA);972973/**974* Constant identifying the year field.975*/976public static final Field YEAR = new Field("year", Calendar.YEAR);977978/**979* Constant identifying the month field.980*/981public static final Field MONTH = new Field("month", Calendar.MONTH);982983/**984* Constant identifying the day of month field.985*/986public static final Field DAY_OF_MONTH = new987Field("day of month", Calendar.DAY_OF_MONTH);988989/**990* Constant identifying the hour of day field, where the legal values991* are 1 to 24.992*/993public static final Field HOUR_OF_DAY1 = new Field("hour of day 1",-1);994995/**996* Constant identifying the hour of day field, where the legal values997* are 0 to 23.998*/999public static final Field HOUR_OF_DAY0 = new1000Field("hour of day", Calendar.HOUR_OF_DAY);10011002/**1003* Constant identifying the minute field.1004*/1005public static final Field MINUTE =new Field("minute", Calendar.MINUTE);10061007/**1008* Constant identifying the second field.1009*/1010public static final Field SECOND =new Field("second", Calendar.SECOND);10111012/**1013* Constant identifying the millisecond field.1014*/1015public static final Field MILLISECOND = new1016Field("millisecond", Calendar.MILLISECOND);10171018/**1019* Constant identifying the day of week field.1020*/1021public static final Field DAY_OF_WEEK = new1022Field("day of week", Calendar.DAY_OF_WEEK);10231024/**1025* Constant identifying the day of year field.1026*/1027public static final Field DAY_OF_YEAR = new1028Field("day of year", Calendar.DAY_OF_YEAR);10291030/**1031* Constant identifying the day of week field.1032*/1033public static final Field DAY_OF_WEEK_IN_MONTH =1034new Field("day of week in month",1035Calendar.DAY_OF_WEEK_IN_MONTH);10361037/**1038* Constant identifying the week of year field.1039*/1040public static final Field WEEK_OF_YEAR = new1041Field("week of year", Calendar.WEEK_OF_YEAR);10421043/**1044* Constant identifying the week of month field.1045*/1046public static final Field WEEK_OF_MONTH = new1047Field("week of month", Calendar.WEEK_OF_MONTH);10481049/**1050* Constant identifying the time of day indicator1051* (e.g. "a.m." or "p.m.") field.1052*/1053public static final Field AM_PM = new1054Field("am pm", Calendar.AM_PM);10551056/**1057* Constant identifying the hour field, where the legal values are1058* 1 to 12.1059*/1060public static final Field HOUR1 = new Field("hour 1", -1);10611062/**1063* Constant identifying the hour field, where the legal values are1064* 0 to 11.1065*/1066public static final Field HOUR0 = new1067Field("hour", Calendar.HOUR);10681069/**1070* Constant identifying the time zone field.1071*/1072public static final Field TIME_ZONE = new Field("time zone", -1);1073}1074}107510761077