Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/text/DateFormat.java
38829 views
/*1* Copyright (c) 1996, 2013, 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</code> 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* <p>You can use a DateFormat to parse also.100* <blockquote>101* <pre>{@code102* myDate = df.parse(myString);103* }</pre>104* </blockquote>105* <p>Use {@code getDateInstance} to get the normal date format for that country.106* There are other static factory methods available.107* Use {@code getTimeInstance} to get the time format for that country.108* Use {@code getDateTimeInstance} to get a date and time format. You can pass in109* different options to these factory methods to control the length of the110* result; from {@link #SHORT} to {@link #MEDIUM} to {@link #LONG} to {@link #FULL}. The exact result depends111* on the locale, but generally:112* <ul><li>{@link #SHORT} is completely numeric, such as {@code 12.13.52} or {@code 3:30pm}113* <li>{@link #MEDIUM} is longer, such as {@code Jan 12, 1952}114* <li>{@link #LONG} is longer, such as {@code January 12, 1952} or {@code 3:30:32pm}115* <li>{@link #FULL} is pretty completely specified, such as116* {@code Tuesday, April 12, 1952 AD or 3:30:42pm PST}.117* </ul>118*119* <p>You can also set the time zone on the format if you wish.120* If you want even more control over the format or parsing,121* (or want to give your users more control),122* you can try casting the {@code DateFormat} you get from the factory methods123* to a {@link SimpleDateFormat}. This will work for the majority124* of countries; just remember to put it in a {@code try} block in case you125* encounter an unusual one.126*127* <p>You can also use forms of the parse and format methods with128* {@link ParsePosition} and {@link FieldPosition} to129* allow you to130* <ul><li>progressively parse through pieces of a string.131* <li>align any particular field, or find out where it is for selection132* on the screen.133* </ul>134*135* <h3><a name="synchronization">Synchronization</a></h3>136*137* <p>138* Date formats are not synchronized.139* It is recommended to create separate format instances for each thread.140* If multiple threads access a format concurrently, it must be synchronized141* externally.142*143* @see Format144* @see NumberFormat145* @see SimpleDateFormat146* @see java.util.Calendar147* @see java.util.GregorianCalendar148* @see java.util.TimeZone149* @author Mark Davis, Chen-Lieh Huang, Alan Liu150*/151public abstract class DateFormat extends Format {152153/**154* The {@link Calendar} instance used for calculating the date-time fields155* and the instant of time. This field is used for both formatting and156* parsing.157*158* <p>Subclasses should initialize this field to a {@link Calendar}159* appropriate for the {@link Locale} associated with this160* <code>DateFormat</code>.161* @serial162*/163protected Calendar calendar;164165/**166* The number formatter that <code>DateFormat</code> uses to format numbers167* in dates and times. Subclasses should initialize this to a number format168* appropriate for the locale associated with this <code>DateFormat</code>.169* @serial170*/171protected NumberFormat numberFormat;172173/**174* Useful constant for ERA field alignment.175* Used in FieldPosition of date/time formatting.176*/177public final static int ERA_FIELD = 0;178/**179* Useful constant for YEAR field alignment.180* Used in FieldPosition of date/time formatting.181*/182public final static int YEAR_FIELD = 1;183/**184* Useful constant for MONTH field alignment.185* Used in FieldPosition of date/time formatting.186*/187public final static int MONTH_FIELD = 2;188/**189* Useful constant for DATE field alignment.190* Used in FieldPosition of date/time formatting.191*/192public final static int DATE_FIELD = 3;193/**194* Useful constant for one-based HOUR_OF_DAY field alignment.195* Used in FieldPosition of date/time formatting.196* HOUR_OF_DAY1_FIELD is used for the one-based 24-hour clock.197* For example, 23:59 + 01:00 results in 24:59.198*/199public final static int HOUR_OF_DAY1_FIELD = 4;200/**201* Useful constant for zero-based HOUR_OF_DAY field alignment.202* Used in FieldPosition of date/time formatting.203* HOUR_OF_DAY0_FIELD is used for the zero-based 24-hour clock.204* For example, 23:59 + 01:00 results in 00:59.205*/206public final static int HOUR_OF_DAY0_FIELD = 5;207/**208* Useful constant for MINUTE field alignment.209* Used in FieldPosition of date/time formatting.210*/211public final static int MINUTE_FIELD = 6;212/**213* Useful constant for SECOND field alignment.214* Used in FieldPosition of date/time formatting.215*/216public final static int SECOND_FIELD = 7;217/**218* Useful constant for MILLISECOND field alignment.219* Used in FieldPosition of date/time formatting.220*/221public final static int MILLISECOND_FIELD = 8;222/**223* Useful constant for DAY_OF_WEEK field alignment.224* Used in FieldPosition of date/time formatting.225*/226public final static int DAY_OF_WEEK_FIELD = 9;227/**228* Useful constant for DAY_OF_YEAR field alignment.229* Used in FieldPosition of date/time formatting.230*/231public final static int DAY_OF_YEAR_FIELD = 10;232/**233* Useful constant for DAY_OF_WEEK_IN_MONTH field alignment.234* Used in FieldPosition of date/time formatting.235*/236public final static int DAY_OF_WEEK_IN_MONTH_FIELD = 11;237/**238* Useful constant for WEEK_OF_YEAR field alignment.239* Used in FieldPosition of date/time formatting.240*/241public final static int WEEK_OF_YEAR_FIELD = 12;242/**243* Useful constant for WEEK_OF_MONTH field alignment.244* Used in FieldPosition of date/time formatting.245*/246public final static int WEEK_OF_MONTH_FIELD = 13;247/**248* Useful constant for AM_PM field alignment.249* Used in FieldPosition of date/time formatting.250*/251public final static int AM_PM_FIELD = 14;252/**253* Useful constant for one-based HOUR field alignment.254* Used in FieldPosition of date/time formatting.255* HOUR1_FIELD is used for the one-based 12-hour clock.256* For example, 11:30 PM + 1 hour results in 12:30 AM.257*/258public final static int HOUR1_FIELD = 15;259/**260* Useful constant for zero-based HOUR field alignment.261* Used in FieldPosition of date/time formatting.262* HOUR0_FIELD is used for the zero-based 12-hour clock.263* For example, 11:30 PM + 1 hour results in 00:30 AM.264*/265public final static int HOUR0_FIELD = 16;266/**267* Useful constant for TIMEZONE field alignment.268* Used in FieldPosition of date/time formatting.269*/270public final static int TIMEZONE_FIELD = 17;271272// Proclaim serial compatibility with 1.1 FCS273private static final long serialVersionUID = 7218322306649953788L;274275/**276* Overrides Format.277* Formats a time object into a time string. Examples of time objects278* are a time value expressed in milliseconds and a Date object.279* @param obj must be a Number or a Date.280* @param toAppendTo the string buffer for the returning time string.281* @return the string buffer passed in as toAppendTo, with formatted text appended.282* @param fieldPosition keeps track of the position of the field283* within the returned string.284* On input: an alignment field,285* if desired. On output: the offsets of the alignment field. For286* example, given a time text "1996.07.10 AD at 15:08:56 PDT",287* if the given fieldPosition is DateFormat.YEAR_FIELD, the288* begin index and end index of fieldPosition will be set to289* 0 and 4, respectively.290* Notice that if the same time field appears291* more than once in a pattern, the fieldPosition will be set for the first292* occurrence of that time field. For instance, formatting a Date to293* the time string "1 PM PDT (Pacific Daylight Time)" using the pattern294* "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD,295* the begin index and end index of fieldPosition will be set to296* 5 and 8, respectively, for the first occurrence of the timezone297* pattern character 'z'.298* @see java.text.Format299*/300public final StringBuffer format(Object obj, StringBuffer toAppendTo,301FieldPosition fieldPosition)302{303if (obj instanceof Date)304return format( (Date)obj, toAppendTo, fieldPosition );305else if (obj instanceof Number)306return format( new Date(((Number)obj).longValue()),307toAppendTo, fieldPosition );308else309throw new IllegalArgumentException("Cannot format given Object as a Date");310}311312/**313* Formats a Date into a date/time string.314* @param date a Date to be formatted into a date/time string.315* @param toAppendTo the string buffer for the returning date/time string.316* @param fieldPosition keeps track of the position of the field317* within the returned string.318* On input: an alignment field,319* if desired. On output: the offsets of the alignment field. For320* example, given a time text "1996.07.10 AD at 15:08:56 PDT",321* if the given fieldPosition is DateFormat.YEAR_FIELD, the322* begin index and end index of fieldPosition will be set to323* 0 and 4, respectively.324* Notice that if the same time field appears325* more than once in a pattern, the fieldPosition will be set for the first326* occurrence of that time field. For instance, formatting a Date to327* the time string "1 PM PDT (Pacific Daylight Time)" using the pattern328* "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD,329* the begin index and end index of fieldPosition will be set to330* 5 and 8, respectively, for the first occurrence of the timezone331* pattern character 'z'.332* @return the string buffer passed in as toAppendTo, with formatted text appended.333*/334public abstract StringBuffer format(Date date, StringBuffer toAppendTo,335FieldPosition fieldPosition);336337/**338* Formats a Date into a date/time string.339* @param date the time value to be formatted into a time string.340* @return the formatted time string.341*/342public final String format(Date date)343{344return format(date, new StringBuffer(),345DontCareFieldPosition.INSTANCE).toString();346}347348/**349* Parses text from the beginning of the given string to produce a date.350* The method may not use the entire text of the given string.351* <p>352* See the {@link #parse(String, ParsePosition)} method for more information353* on date parsing.354*355* @param source A <code>String</code> whose beginning should be parsed.356* @return A <code>Date</code> parsed from the string.357* @exception ParseException if the beginning of the specified string358* cannot be parsed.359*/360public Date parse(String source) throws ParseException361{362ParsePosition pos = new ParsePosition(0);363Date result = parse(source, pos);364if (pos.index == 0)365throw new ParseException("Unparseable date: \"" + source + "\"" ,366pos.errorIndex);367return result;368}369370/**371* Parse a date/time string according to the given parse position. For372* example, a time text {@code "07/10/96 4:5 PM, PDT"} will be parsed into a {@code Date}373* that is equivalent to {@code Date(837039900000L)}.374*375* <p> By default, parsing is lenient: If the input is not in the form used376* by this object's format method but can still be parsed as a date, then377* the parse succeeds. Clients may insist on strict adherence to the378* format by calling {@link #setLenient(boolean) setLenient(false)}.379*380* <p>This parsing operation uses the {@link #calendar} to produce381* a {@code Date}. As a result, the {@code calendar}'s date-time382* fields and the {@code TimeZone} value may have been383* overwritten, depending on subclass implementations. Any {@code384* TimeZone} value that has previously been set by a call to385* {@link #setTimeZone(java.util.TimeZone) setTimeZone} may need386* to be restored for further operations.387*388* @param source The date/time string to be parsed389*390* @param pos On input, the position at which to start parsing; on391* output, the position at which parsing terminated, or the392* start position if the parse failed.393*394* @return A {@code Date}, or {@code null} if the input could not be parsed395*/396public abstract Date parse(String source, ParsePosition pos);397398/**399* Parses text from a string to produce a <code>Date</code>.400* <p>401* The method attempts to parse text starting at the index given by402* <code>pos</code>.403* If parsing succeeds, then the index of <code>pos</code> is updated404* to the index after the last character used (parsing does not necessarily405* use all characters up to the end of the string), and the parsed406* date is returned. The updated <code>pos</code> can be used to407* indicate the starting point for the next call to this method.408* If an error occurs, then the index of <code>pos</code> is not409* changed, the error index of <code>pos</code> is set to the index of410* the character where the error occurred, and null is returned.411* <p>412* See the {@link #parse(String, ParsePosition)} method for more information413* on date parsing.414*415* @param source A <code>String</code>, part of which should be parsed.416* @param pos A <code>ParsePosition</code> object with index and error417* index information as described above.418* @return A <code>Date</code> parsed from the string. In case of419* error, returns null.420* @exception NullPointerException if <code>pos</code> is null.421*/422public Object parseObject(String source, ParsePosition pos) {423return parse(source, pos);424}425426/**427* Constant for full style pattern.428*/429public static final int FULL = 0;430/**431* Constant for long style pattern.432*/433public static final int LONG = 1;434/**435* Constant for medium style pattern.436*/437public static final int MEDIUM = 2;438/**439* Constant for short style pattern.440*/441public static final int SHORT = 3;442/**443* Constant for default style pattern. Its value is MEDIUM.444*/445public static final int DEFAULT = MEDIUM;446447/**448* Gets the time formatter with the default formatting style449* for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.450* <p>This is equivalent to calling451* {@link #getTimeInstance(int, Locale) getTimeInstance(DEFAULT,452* Locale.getDefault(Locale.Category.FORMAT))}.453* @see java.util.Locale#getDefault(java.util.Locale.Category)454* @see java.util.Locale.Category#FORMAT455* @return a time formatter.456*/457public final static DateFormat getTimeInstance()458{459return get(DEFAULT, 0, 1, Locale.getDefault(Locale.Category.FORMAT));460}461462/**463* Gets the time formatter with the given formatting style464* for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.465* <p>This is equivalent to calling466* {@link #getTimeInstance(int, Locale) getTimeInstance(style,467* Locale.getDefault(Locale.Category.FORMAT))}.468* @see java.util.Locale#getDefault(java.util.Locale.Category)469* @see java.util.Locale.Category#FORMAT470* @param style the given formatting style. For example,471* SHORT for "h:mm a" in the US locale.472* @return a time formatter.473*/474public final static DateFormat getTimeInstance(int style)475{476return get(style, 0, 1, Locale.getDefault(Locale.Category.FORMAT));477}478479/**480* Gets the time formatter with the given formatting style481* for the given locale.482* @param style the given formatting style. For example,483* SHORT for "h:mm a" in the US locale.484* @param aLocale the given locale.485* @return a time formatter.486*/487public final static DateFormat getTimeInstance(int style,488Locale aLocale)489{490return get(style, 0, 1, aLocale);491}492493/**494* Gets the date formatter with the default formatting style495* for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.496* <p>This is equivalent to calling497* {@link #getDateInstance(int, Locale) getDateInstance(DEFAULT,498* Locale.getDefault(Locale.Category.FORMAT))}.499* @see java.util.Locale#getDefault(java.util.Locale.Category)500* @see java.util.Locale.Category#FORMAT501* @return a date formatter.502*/503public final static DateFormat getDateInstance()504{505return get(0, DEFAULT, 2, Locale.getDefault(Locale.Category.FORMAT));506}507508/**509* Gets the date formatter with the given formatting style510* for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.511* <p>This is equivalent to calling512* {@link #getDateInstance(int, Locale) getDateInstance(style,513* Locale.getDefault(Locale.Category.FORMAT))}.514* @see java.util.Locale#getDefault(java.util.Locale.Category)515* @see java.util.Locale.Category#FORMAT516* @param style the given formatting style. For example,517* SHORT for "M/d/yy" in the US locale.518* @return a date formatter.519*/520public final static DateFormat getDateInstance(int style)521{522return get(0, style, 2, Locale.getDefault(Locale.Category.FORMAT));523}524525/**526* Gets the date formatter with the given formatting style527* for the given locale.528* @param style the given formatting style. For example,529* SHORT for "M/d/yy" in the US locale.530* @param aLocale the given locale.531* @return a date formatter.532*/533public final static DateFormat getDateInstance(int style,534Locale aLocale)535{536return get(0, style, 2, aLocale);537}538539/**540* Gets the date/time formatter with the default formatting style541* for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.542* <p>This is equivalent to calling543* {@link #getDateTimeInstance(int, int, Locale) getDateTimeInstance(DEFAULT,544* DEFAULT, Locale.getDefault(Locale.Category.FORMAT))}.545* @see java.util.Locale#getDefault(java.util.Locale.Category)546* @see java.util.Locale.Category#FORMAT547* @return a date/time formatter.548*/549public final static DateFormat getDateTimeInstance()550{551return get(DEFAULT, DEFAULT, 3, Locale.getDefault(Locale.Category.FORMAT));552}553554/**555* Gets the date/time formatter with the given date and time556* formatting styles for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale.557* <p>This is equivalent to calling558* {@link #getDateTimeInstance(int, int, Locale) getDateTimeInstance(dateStyle,559* timeStyle, Locale.getDefault(Locale.Category.FORMAT))}.560* @see java.util.Locale#getDefault(java.util.Locale.Category)561* @see java.util.Locale.Category#FORMAT562* @param dateStyle the given date formatting style. For example,563* SHORT for "M/d/yy" in the US locale.564* @param timeStyle the given time formatting style. For example,565* SHORT for "h:mm a" in the US locale.566* @return a date/time formatter.567*/568public final static DateFormat getDateTimeInstance(int dateStyle,569int timeStyle)570{571return get(timeStyle, dateStyle, 3, Locale.getDefault(Locale.Category.FORMAT));572}573574/**575* Gets the date/time formatter with the given formatting styles576* for the given locale.577* @param dateStyle the given date formatting style.578* @param timeStyle the given time formatting style.579* @param aLocale the given locale.580* @return a date/time formatter.581*/582public final static DateFormat583getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale)584{585return get(timeStyle, dateStyle, 3, aLocale);586}587588/**589* Get a default date/time formatter that uses the SHORT style for both the590* date and the time.591*592* @return a date/time formatter593*/594public final static DateFormat getInstance() {595return getDateTimeInstance(SHORT, SHORT);596}597598/**599* Returns an array of all locales for which the600* <code>get*Instance</code> methods of this class can return601* localized instances.602* The returned array represents the union of locales supported by the Java603* runtime and by installed604* {@link java.text.spi.DateFormatProvider DateFormatProvider} implementations.605* It must contain at least a <code>Locale</code> instance equal to606* {@link java.util.Locale#US Locale.US}.607*608* @return An array of locales for which localized609* <code>DateFormat</code> instances are available.610*/611public static Locale[] getAvailableLocales()612{613LocaleServiceProviderPool pool =614LocaleServiceProviderPool.getPool(DateFormatProvider.class);615return pool.getAvailableLocales();616}617618/**619* Set the calendar to be used by this date format. Initially, the default620* calendar for the specified or default locale is used.621*622* <p>Any {@link java.util.TimeZone TimeZone} and {@linkplain623* #isLenient() leniency} values that have previously been set are624* overwritten by {@code newCalendar}'s values.625*626* @param newCalendar the new {@code Calendar} to be used by the date format627*/628public void setCalendar(Calendar newCalendar)629{630this.calendar = newCalendar;631}632633/**634* Gets the calendar associated with this date/time formatter.635*636* @return the calendar associated with this date/time formatter.637*/638public Calendar getCalendar()639{640return calendar;641}642643/**644* Allows you to set the number formatter.645* @param newNumberFormat the given new NumberFormat.646*/647public void setNumberFormat(NumberFormat newNumberFormat)648{649this.numberFormat = newNumberFormat;650}651652/**653* Gets the number formatter which this date/time formatter uses to654* format and parse a time.655* @return the number formatter which this date/time formatter uses.656*/657public NumberFormat getNumberFormat()658{659return numberFormat;660}661662/**663* Sets the time zone for the calendar of this {@code DateFormat} object.664* This method is equivalent to the following call.665* <blockquote><pre>{@code666* getCalendar().setTimeZone(zone)667* }</pre></blockquote>668*669* <p>The {@code TimeZone} set by this method is overwritten by a670* {@link #setCalendar(java.util.Calendar) setCalendar} call.671*672* <p>The {@code TimeZone} set by this method may be overwritten as673* a result of a call to the parse method.674*675* @param zone the given new time zone.676*/677public void setTimeZone(TimeZone zone)678{679calendar.setTimeZone(zone);680}681682/**683* Gets the time zone.684* This method is equivalent to the following call.685* <blockquote><pre>{@code686* getCalendar().getTimeZone()687* }</pre></blockquote>688*689* @return the time zone associated with the calendar of DateFormat.690*/691public TimeZone getTimeZone()692{693return calendar.getTimeZone();694}695696/**697* Specify whether or not date/time parsing is to be lenient. With698* lenient parsing, the parser may use heuristics to interpret inputs that699* do not precisely match this object's format. With strict parsing,700* inputs must match this object's format.701*702* <p>This method is equivalent to the following call.703* <blockquote><pre>{@code704* getCalendar().setLenient(lenient)705* }</pre></blockquote>706*707* <p>This leniency value is overwritten by a call to {@link708* #setCalendar(java.util.Calendar) setCalendar()}.709*710* @param lenient when {@code true}, parsing is lenient711* @see java.util.Calendar#setLenient(boolean)712*/713public void setLenient(boolean lenient)714{715calendar.setLenient(lenient);716}717718/**719* Tell whether date/time parsing is to be lenient.720* This method is equivalent to the following call.721* <blockquote><pre>{@code722* getCalendar().isLenient()723* }</pre></blockquote>724*725* @return {@code true} if the {@link #calendar} is lenient;726* {@code false} otherwise.727* @see java.util.Calendar#isLenient()728*/729public boolean isLenient()730{731return calendar.isLenient();732}733734/**735* Overrides hashCode736*/737public int hashCode() {738return numberFormat.hashCode();739// just enough fields for a reasonable distribution740}741742/**743* Overrides equals744*/745public boolean equals(Object obj) {746if (this == obj) return true;747if (obj == null || getClass() != obj.getClass()) return false;748DateFormat other = (DateFormat) obj;749return (// calendar.equivalentTo(other.calendar) // THIS API DOESN'T EXIST YET!750calendar.getFirstDayOfWeek() == other.calendar.getFirstDayOfWeek() &&751calendar.getMinimalDaysInFirstWeek() == other.calendar.getMinimalDaysInFirstWeek() &&752calendar.isLenient() == other.calendar.isLenient() &&753calendar.getTimeZone().equals(other.calendar.getTimeZone()) &&754numberFormat.equals(other.numberFormat));755}756757/**758* Overrides Cloneable759*/760public Object clone()761{762DateFormat other = (DateFormat) super.clone();763other.calendar = (Calendar) calendar.clone();764other.numberFormat = (NumberFormat) numberFormat.clone();765return other;766}767768/**769* Creates a DateFormat with the given time and/or date style in the given770* locale.771* @param timeStyle a value from 0 to 3 indicating the time format,772* ignored if flags is 2773* @param dateStyle a value from 0 to 3 indicating the time format,774* ignored if flags is 1775* @param flags either 1 for a time format, 2 for a date format,776* or 3 for a date/time format777* @param loc the locale for the format778*/779private static DateFormat get(int timeStyle, int dateStyle,780int flags, Locale loc) {781if ((flags & 1) != 0) {782if (timeStyle < 0 || timeStyle > 3) {783throw new IllegalArgumentException("Illegal time style " + timeStyle);784}785} else {786timeStyle = -1;787}788if ((flags & 2) != 0) {789if (dateStyle < 0 || dateStyle > 3) {790throw new IllegalArgumentException("Illegal date style " + dateStyle);791}792} else {793dateStyle = -1;794}795796LocaleProviderAdapter adapter = LocaleProviderAdapter.getAdapter(DateFormatProvider.class, loc);797DateFormat dateFormat = get(adapter, timeStyle, dateStyle, loc);798if (dateFormat == null) {799dateFormat = get(LocaleProviderAdapter.forJRE(), timeStyle, dateStyle, loc);800}801return dateFormat;802}803804private static DateFormat get(LocaleProviderAdapter adapter, int timeStyle, int dateStyle, Locale loc) {805DateFormatProvider provider = adapter.getDateFormatProvider();806DateFormat dateFormat;807if (timeStyle == -1) {808dateFormat = provider.getDateInstance(dateStyle, loc);809} else {810if (dateStyle == -1) {811dateFormat = provider.getTimeInstance(timeStyle, loc);812} else {813dateFormat = provider.getDateTimeInstance(dateStyle, timeStyle, loc);814}815}816return dateFormat;817}818819/**820* Create a new date format.821*/822protected DateFormat() {}823824/**825* Defines constants that are used as attribute keys in the826* <code>AttributedCharacterIterator</code> returned827* from <code>DateFormat.formatToCharacterIterator</code> and as828* field identifiers in <code>FieldPosition</code>.829* <p>830* The class also provides two methods to map831* between its constants and the corresponding Calendar constants.832*833* @since 1.4834* @see java.util.Calendar835*/836public static class Field extends Format.Field {837838// Proclaim serial compatibility with 1.4 FCS839private static final long serialVersionUID = 7441350119349544720L;840841// table of all instances in this class, used by readResolve842private static final Map<String, Field> instanceMap = new HashMap<>(18);843// Maps from Calendar constant (such as Calendar.ERA) to Field844// constant (such as Field.ERA).845private static final Field[] calendarToFieldMapping =846new Field[Calendar.FIELD_COUNT];847848/** Calendar field. */849private int calendarField;850851/**852* Returns the <code>Field</code> constant that corresponds to853* the <code>Calendar</code> constant <code>calendarField</code>.854* If there is no direct mapping between the <code>Calendar</code>855* constant and a <code>Field</code>, null is returned.856*857* @throws IllegalArgumentException if <code>calendarField</code> is858* not the value of a <code>Calendar</code> field constant.859* @param calendarField Calendar field constant860* @return Field instance representing calendarField.861* @see java.util.Calendar862*/863public static Field ofCalendarField(int calendarField) {864if (calendarField < 0 || calendarField >=865calendarToFieldMapping.length) {866throw new IllegalArgumentException("Unknown Calendar constant "867+ calendarField);868}869return calendarToFieldMapping[calendarField];870}871872/**873* Creates a <code>Field</code>.874*875* @param name the name of the <code>Field</code>876* @param calendarField the <code>Calendar</code> constant this877* <code>Field</code> corresponds to; any value, even one878* outside the range of legal <code>Calendar</code> values may879* be used, but <code>-1</code> should be used for values880* that don't correspond to legal <code>Calendar</code> values881*/882protected Field(String name, int calendarField) {883super(name);884this.calendarField = calendarField;885if (this.getClass() == DateFormat.Field.class) {886instanceMap.put(name, this);887if (calendarField >= 0) {888// assert(calendarField < Calendar.FIELD_COUNT);889calendarToFieldMapping[calendarField] = this;890}891}892}893894/**895* Returns the <code>Calendar</code> field associated with this896* attribute. For example, if this represents the hours field of897* a <code>Calendar</code>, this would return898* <code>Calendar.HOUR</code>. If there is no corresponding899* <code>Calendar</code> constant, this will return -1.900*901* @return Calendar constant for this field902* @see java.util.Calendar903*/904public int getCalendarField() {905return calendarField;906}907908/**909* Resolves instances being deserialized to the predefined constants.910*911* @throws InvalidObjectException if the constant could not be912* resolved.913* @return resolved DateFormat.Field constant914*/915@Override916protected Object readResolve() throws InvalidObjectException {917if (this.getClass() != DateFormat.Field.class) {918throw new InvalidObjectException("subclass didn't correctly implement readResolve");919}920921Object instance = instanceMap.get(getName());922if (instance != null) {923return instance;924} else {925throw new InvalidObjectException("unknown attribute name");926}927}928929//930// The constants931//932933/**934* Constant identifying the era field.935*/936public final static Field ERA = new Field("era", Calendar.ERA);937938/**939* Constant identifying the year field.940*/941public final static Field YEAR = new Field("year", Calendar.YEAR);942943/**944* Constant identifying the month field.945*/946public final static Field MONTH = new Field("month", Calendar.MONTH);947948/**949* Constant identifying the day of month field.950*/951public final static Field DAY_OF_MONTH = new952Field("day of month", Calendar.DAY_OF_MONTH);953954/**955* Constant identifying the hour of day field, where the legal values956* are 1 to 24.957*/958public final static Field HOUR_OF_DAY1 = new Field("hour of day 1",-1);959960/**961* Constant identifying the hour of day field, where the legal values962* are 0 to 23.963*/964public final static Field HOUR_OF_DAY0 = new965Field("hour of day", Calendar.HOUR_OF_DAY);966967/**968* Constant identifying the minute field.969*/970public final static Field MINUTE =new Field("minute", Calendar.MINUTE);971972/**973* Constant identifying the second field.974*/975public final static Field SECOND =new Field("second", Calendar.SECOND);976977/**978* Constant identifying the millisecond field.979*/980public final static Field MILLISECOND = new981Field("millisecond", Calendar.MILLISECOND);982983/**984* Constant identifying the day of week field.985*/986public final static Field DAY_OF_WEEK = new987Field("day of week", Calendar.DAY_OF_WEEK);988989/**990* Constant identifying the day of year field.991*/992public final static Field DAY_OF_YEAR = new993Field("day of year", Calendar.DAY_OF_YEAR);994995/**996* Constant identifying the day of week field.997*/998public final static Field DAY_OF_WEEK_IN_MONTH =999new Field("day of week in month",1000Calendar.DAY_OF_WEEK_IN_MONTH);10011002/**1003* Constant identifying the week of year field.1004*/1005public final static Field WEEK_OF_YEAR = new1006Field("week of year", Calendar.WEEK_OF_YEAR);10071008/**1009* Constant identifying the week of month field.1010*/1011public final static Field WEEK_OF_MONTH = new1012Field("week of month", Calendar.WEEK_OF_MONTH);10131014/**1015* Constant identifying the time of day indicator1016* (e.g. "a.m." or "p.m.") field.1017*/1018public final static Field AM_PM = new1019Field("am pm", Calendar.AM_PM);10201021/**1022* Constant identifying the hour field, where the legal values are1023* 1 to 12.1024*/1025public final static Field HOUR1 = new Field("hour 1", -1);10261027/**1028* Constant identifying the hour field, where the legal values are1029* 0 to 11.1030*/1031public final static Field HOUR0 = new1032Field("hour", Calendar.HOUR);10331034/**1035* Constant identifying the time zone field.1036*/1037public final static Field TIME_ZONE = new Field("time zone", -1);1038}1039}104010411042