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