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