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