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 // Android-changed: Added a warning of deserialization. 377 /** 378 * Parses text from the beginning of the given string to produce a date. 379 * The method may not use the entire text of the given string. 380 * <p> 381 * See the {@link #parse(String, ParsePosition)} method for more information 382 * on date parsing. 383 * 384 * <p> <b>WARNING:</b> Don't use this method to deserialize a date. The underlying localized 385 * date/time format and parsing behaviors can change across Android versions as common usage 386 * in the locale changes. Consider using <code>long</code> type for storing a timestamp or 387 * {@link java.time.format.DateTimeFormatter#ISO_INSTANT} for deserializing the ISO-8601 388 * instant format.</p> 389 * 390 * @param source A {@code String} whose beginning should be parsed. 391 * @return A {@code Date} parsed from the string. 392 * @throws ParseException if the beginning of the specified string 393 * cannot be parsed. 394 */ parse(String source)395 public Date parse(String source) throws ParseException 396 { 397 ParsePosition pos = new ParsePosition(0); 398 Date result = parse(source, pos); 399 if (pos.index == 0) 400 throw new ParseException("Unparseable date: \"" + source + "\"" , 401 pos.errorIndex); 402 return result; 403 } 404 405 // Android-changed: Added a warning of deserialization. 406 /** 407 * Parse a date/time string according to the given parse position. For 408 * example, a time text {@code "07/10/96 4:5 PM, PDT"} will be parsed into a {@code Date} 409 * that is equivalent to {@code Date(837039900000L)}. 410 * 411 * <p> By default, parsing is lenient: If the input is not in the form used 412 * by this object's format method but can still be parsed as a date, then 413 * the parse succeeds. Clients may insist on strict adherence to the 414 * format by calling {@link #setLenient(boolean) setLenient(false)}. 415 * 416 * <p> <b>WARNING:</b> Don't use this method to deserialize a date. The underlying localized 417 * date/time format and parsing behaviors can change across Android versions as common usage 418 * in the locale changes. Consider using <code>long</code> type for storing a timestamp or 419 * {@link java.time.format.DateTimeFormatter#ISO_INSTANT} for deserializing the ISO-8601 420 * instant format.</p> 421 * 422 * <p>This parsing operation uses the {@link #calendar} to produce 423 * a {@code Date}. As a result, the {@code calendar}'s date-time 424 * fields and the {@code TimeZone} value may have been 425 * overwritten, depending on subclass implementations. Any {@code 426 * TimeZone} value that has previously been set by a call to 427 * {@link #setTimeZone(java.util.TimeZone) setTimeZone} may need 428 * to be restored for further operations. 429 * 430 * @param source The date/time string to be parsed 431 * 432 * @param pos On input, the position at which to start parsing; on 433 * output, the position at which parsing terminated, or the 434 * start position if the parse failed. 435 * 436 * @return A {@code Date}, or {@code null} if the input could not be parsed 437 */ parse(String source, ParsePosition pos)438 public abstract Date parse(String source, ParsePosition pos); 439 440 /** 441 * Parses text from a string to produce a {@code Date}. 442 * <p> 443 * The method attempts to parse text starting at the index given by 444 * {@code pos}. 445 * If parsing succeeds, then the index of {@code pos} is updated 446 * to the index after the last character used (parsing does not necessarily 447 * use all characters up to the end of the string), and the parsed 448 * date is returned. The updated {@code pos} can be used to 449 * indicate the starting point for the next call to this method. 450 * If an error occurs, then the index of {@code pos} is not 451 * changed, the error index of {@code pos} is set to the index of 452 * the character where the error occurred, and null is returned. 453 * <p> 454 * See the {@link #parse(String, ParsePosition)} method for more information 455 * on date parsing. 456 * 457 * @param source A {@code String}, part of which should be parsed. 458 * @param pos A {@code ParsePosition} object with index and error 459 * index information as described above. 460 * @return A {@code Date} parsed from the string. In case of 461 * error, returns null. 462 * @throws NullPointerException if {@code source} or {@code pos} is null. 463 */ parseObject(String source, ParsePosition pos)464 public Object parseObject(String source, ParsePosition pos) { 465 return parse(source, pos); 466 } 467 468 /** 469 * Constant for full style pattern. 470 */ 471 public static final int FULL = 0; 472 /** 473 * Constant for long style pattern. 474 */ 475 public static final int LONG = 1; 476 /** 477 * Constant for medium style pattern. 478 */ 479 public static final int MEDIUM = 2; 480 /** 481 * Constant for short style pattern. 482 */ 483 public static final int SHORT = 3; 484 /** 485 * Constant for default style pattern. Its value is MEDIUM. 486 */ 487 public static final int DEFAULT = MEDIUM; 488 489 /** 490 * Gets the time formatter with the default formatting style 491 * for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale. 492 * <p>This is equivalent to calling 493 * {@link #getTimeInstance(int, Locale) getTimeInstance(DEFAULT, 494 * Locale.getDefault(Locale.Category.FORMAT))}. 495 * @see java.util.Locale#getDefault(java.util.Locale.Category) 496 * @see java.util.Locale.Category#FORMAT 497 * @return a time formatter. 498 */ getTimeInstance()499 public static final DateFormat getTimeInstance() 500 { 501 return get(DEFAULT, 0, 1, Locale.getDefault(Locale.Category.FORMAT)); 502 } 503 504 /** 505 * Gets the time formatter with the given formatting style 506 * for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale. 507 * <p>This is equivalent to calling 508 * {@link #getTimeInstance(int, Locale) getTimeInstance(style, 509 * Locale.getDefault(Locale.Category.FORMAT))}. 510 * @see java.util.Locale#getDefault(java.util.Locale.Category) 511 * @see java.util.Locale.Category#FORMAT 512 * @param style the given formatting style. For example, 513 * SHORT for "h:mm a" in the US locale. 514 * @return a time formatter. 515 */ getTimeInstance(int style)516 public static final DateFormat getTimeInstance(int style) 517 { 518 return get(style, 0, 1, Locale.getDefault(Locale.Category.FORMAT)); 519 } 520 521 /** 522 * Gets the time formatter with the given formatting style 523 * for the given locale. 524 * @param style the given formatting style. For example, 525 * SHORT for "h:mm a" in the US locale. 526 * @param aLocale the given locale. 527 * @return a time formatter. 528 */ getTimeInstance(int style, Locale aLocale)529 public static final DateFormat getTimeInstance(int style, 530 Locale aLocale) 531 { 532 return get(style, 0, 1, aLocale); 533 } 534 535 /** 536 * Gets the date formatter with the default formatting style 537 * for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale. 538 * <p>This is equivalent to calling 539 * {@link #getDateInstance(int, Locale) getDateInstance(DEFAULT, 540 * Locale.getDefault(Locale.Category.FORMAT))}. 541 * @see java.util.Locale#getDefault(java.util.Locale.Category) 542 * @see java.util.Locale.Category#FORMAT 543 * @return a date formatter. 544 */ getDateInstance()545 public static final DateFormat getDateInstance() 546 { 547 return get(0, DEFAULT, 2, Locale.getDefault(Locale.Category.FORMAT)); 548 } 549 550 /** 551 * Gets the date formatter with the given formatting style 552 * for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale. 553 * <p>This is equivalent to calling 554 * {@link #getDateInstance(int, Locale) getDateInstance(style, 555 * Locale.getDefault(Locale.Category.FORMAT))}. 556 * @see java.util.Locale#getDefault(java.util.Locale.Category) 557 * @see java.util.Locale.Category#FORMAT 558 * @param style the given formatting style. For example, 559 * SHORT for "M/d/yy" in the US locale. 560 * @return a date formatter. 561 */ getDateInstance(int style)562 public static final DateFormat getDateInstance(int style) 563 { 564 return get(0, style, 2, Locale.getDefault(Locale.Category.FORMAT)); 565 } 566 567 /** 568 * Gets the date formatter with the given formatting style 569 * for the given locale. 570 * @param style the given formatting style. For example, 571 * SHORT for "M/d/yy" in the US locale. 572 * @param aLocale the given locale. 573 * @return a date formatter. 574 */ getDateInstance(int style, Locale aLocale)575 public static final DateFormat getDateInstance(int style, 576 Locale aLocale) 577 { 578 return get(0, style, 2, aLocale); 579 } 580 581 /** 582 * Gets the date/time formatter with the default formatting style 583 * for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale. 584 * <p>This is equivalent to calling 585 * {@link #getDateTimeInstance(int, int, Locale) getDateTimeInstance(DEFAULT, 586 * DEFAULT, Locale.getDefault(Locale.Category.FORMAT))}. 587 * @see java.util.Locale#getDefault(java.util.Locale.Category) 588 * @see java.util.Locale.Category#FORMAT 589 * @return a date/time formatter. 590 */ getDateTimeInstance()591 public static final DateFormat getDateTimeInstance() 592 { 593 return get(DEFAULT, DEFAULT, 3, Locale.getDefault(Locale.Category.FORMAT)); 594 } 595 596 /** 597 * Gets the date/time formatter with the given date and time 598 * formatting styles for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale. 599 * <p>This is equivalent to calling 600 * {@link #getDateTimeInstance(int, int, Locale) getDateTimeInstance(dateStyle, 601 * timeStyle, Locale.getDefault(Locale.Category.FORMAT))}. 602 * @see java.util.Locale#getDefault(java.util.Locale.Category) 603 * @see java.util.Locale.Category#FORMAT 604 * @param dateStyle the given date formatting style. For example, 605 * SHORT for "M/d/yy" in the US locale. 606 * @param timeStyle the given time formatting style. For example, 607 * SHORT for "h:mm a" in the US locale. 608 * @return a date/time formatter. 609 */ getDateTimeInstance(int dateStyle, int timeStyle)610 public static final DateFormat getDateTimeInstance(int dateStyle, 611 int timeStyle) 612 { 613 return get(timeStyle, dateStyle, 3, Locale.getDefault(Locale.Category.FORMAT)); 614 } 615 616 /** 617 * Gets the date/time formatter with the given formatting styles 618 * for the given locale. 619 * @param dateStyle the given date formatting style. 620 * @param timeStyle the given time formatting style. 621 * @param aLocale the given locale. 622 * @return a date/time formatter. 623 */ 624 public static final DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale)625 getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale) 626 { 627 return get(timeStyle, dateStyle, 3, aLocale); 628 } 629 630 /** 631 * Get a default date/time formatter that uses the SHORT style for both the 632 * date and the time. 633 * 634 * @return a date/time formatter 635 */ getInstance()636 public static final DateFormat getInstance() { 637 return getDateTimeInstance(SHORT, SHORT); 638 } 639 640 // Android-changed: Added support for overriding locale default 12 / 24 hour preference. 641 /** 642 * {@code null}: use Locale default. {@code true}: force 24-hour format. 643 * {@code false} force 12-hour format. 644 * @hide 645 */ 646 public static Boolean is24Hour; 647 648 // BEGIN Android-changed: Improve javadoc for stable SystemApi. 649 /** 650 * Override the time formatting behavior for {@link #SHORT} and {@link #MEDIUM} time formats. 651 * Accepts one of the following: 652 * <ul> 653 * <li>{@code null}: use Locale default/li> 654 * <li>{@code true}: force 24-hour format</li> 655 * <li>{@code false} force 12-hour format</li> 656 * </ul> 657 * 658 * @param is24Hour whether to use 24-hour format or not. {@code null} uses locale default. 659 * 660 * @hide for internal use only. 661 */ 662 // END Android-changed: Improve javadoc for stable SystemApi. set24HourTimePref(Boolean is24Hour)663 public static final void set24HourTimePref(Boolean is24Hour) { 664 DateFormat.is24Hour = is24Hour; 665 } 666 667 // Android-changed: Remove reference to DateFormatProvider. 668 /** 669 * Returns an array of all locales for which the 670 * {@code get*Instance} methods of this class can return 671 * localized instances. 672 * It must contain at least a {@code Locale} instance equal to 673 * {@link java.util.Locale#US Locale.US}. 674 * 675 * @return An array of locales for which localized 676 * {@code DateFormat} instances are available. 677 */ getAvailableLocales()678 public static Locale[] getAvailableLocales() 679 { 680 // Android-changed: Removed used of DateFormatProvider. Switched to use ICU. 681 return ICU.getAvailableLocales(); 682 } 683 684 /** 685 * Set the calendar to be used by this date format. Initially, the default 686 * calendar for the specified or default locale is used. 687 * 688 * <p>Any {@link java.util.TimeZone TimeZone} and {@linkplain 689 * #isLenient() leniency} values that have previously been set are 690 * overwritten by {@code newCalendar}'s values. 691 * 692 * @param newCalendar the new {@code Calendar} to be used by the date format 693 */ setCalendar(Calendar newCalendar)694 public void setCalendar(Calendar newCalendar) 695 { 696 this.calendar = newCalendar; 697 } 698 699 /** 700 * Gets the calendar associated with this date/time formatter. 701 * 702 * @return the calendar associated with this date/time formatter. 703 */ getCalendar()704 public Calendar getCalendar() 705 { 706 return calendar; 707 } 708 709 /** 710 * Allows you to set the number formatter. 711 * @param newNumberFormat the given new NumberFormat. 712 */ setNumberFormat(NumberFormat newNumberFormat)713 public void setNumberFormat(NumberFormat newNumberFormat) 714 { 715 this.numberFormat = newNumberFormat; 716 } 717 718 /** 719 * Gets the number formatter which this date/time formatter uses to 720 * format and parse a time. 721 * @return the number formatter which this date/time formatter uses. 722 */ getNumberFormat()723 public NumberFormat getNumberFormat() 724 { 725 return numberFormat; 726 } 727 728 /** 729 * Sets the time zone for the calendar of this {@code DateFormat} object. 730 * This method is equivalent to the following call. 731 * <blockquote><pre>{@code 732 * getCalendar().setTimeZone(zone) 733 * }</pre></blockquote> 734 * 735 * <p>The {@code TimeZone} set by this method is overwritten by a 736 * {@link #setCalendar(java.util.Calendar) setCalendar} call. 737 * 738 * <p>The {@code TimeZone} set by this method may be overwritten as 739 * a result of a call to the parse method. 740 * 741 * @param zone the given new time zone. 742 */ setTimeZone(TimeZone zone)743 public void setTimeZone(TimeZone zone) 744 { 745 calendar.setTimeZone(zone); 746 } 747 748 /** 749 * Gets the time zone. 750 * This method is equivalent to the following call. 751 * <blockquote><pre>{@code 752 * getCalendar().getTimeZone() 753 * }</pre></blockquote> 754 * 755 * @return the time zone associated with the calendar of DateFormat. 756 */ getTimeZone()757 public TimeZone getTimeZone() 758 { 759 return calendar.getTimeZone(); 760 } 761 762 /** 763 * Specify whether or not date/time parsing is to be lenient. With 764 * lenient parsing, the parser may use heuristics to interpret inputs that 765 * do not precisely match this object's format. With strict parsing, 766 * inputs must match this object's format. 767 * 768 * <p>This method is equivalent to the following call. 769 * <blockquote><pre>{@code 770 * getCalendar().setLenient(lenient) 771 * }</pre></blockquote> 772 * 773 * <p>This leniency value is overwritten by a call to {@link 774 * #setCalendar(java.util.Calendar) setCalendar()}. 775 * 776 * @param lenient when {@code true}, parsing is lenient 777 * @see java.util.Calendar#setLenient(boolean) 778 */ setLenient(boolean lenient)779 public void setLenient(boolean lenient) 780 { 781 calendar.setLenient(lenient); 782 } 783 784 /** 785 * Tell whether date/time parsing is to be lenient. 786 * This method is equivalent to the following call. 787 * <blockquote><pre>{@code 788 * getCalendar().isLenient() 789 * }</pre></blockquote> 790 * 791 * @return {@code true} if the {@link #calendar} is lenient; 792 * {@code false} otherwise. 793 * @see java.util.Calendar#isLenient() 794 */ isLenient()795 public boolean isLenient() 796 { 797 return calendar.isLenient(); 798 } 799 800 /** 801 * Overrides hashCode 802 */ hashCode()803 public int hashCode() { 804 return numberFormat.hashCode(); 805 // just enough fields for a reasonable distribution 806 } 807 808 /** 809 * Overrides equals 810 */ equals(Object obj)811 public boolean equals(Object obj) { 812 if (this == obj) return true; 813 if (obj == null || getClass() != obj.getClass()) return false; 814 DateFormat other = (DateFormat) obj; 815 return (// calendar.equivalentTo(other.calendar) // THIS API DOESN'T EXIST YET! 816 calendar.getFirstDayOfWeek() == other.calendar.getFirstDayOfWeek() && 817 calendar.getMinimalDaysInFirstWeek() == other.calendar.getMinimalDaysInFirstWeek() && 818 calendar.isLenient() == other.calendar.isLenient() && 819 calendar.getTimeZone().equals(other.calendar.getTimeZone()) && 820 numberFormat.equals(other.numberFormat)); 821 } 822 823 /** 824 * Overrides Cloneable 825 */ clone()826 public Object clone() 827 { 828 DateFormat other = (DateFormat) super.clone(); 829 other.calendar = (Calendar) calendar.clone(); 830 other.numberFormat = (NumberFormat) numberFormat.clone(); 831 return other; 832 } 833 834 /** 835 * Creates a DateFormat with the given time and/or date style in the given 836 * locale. 837 * @param timeStyle a value from 0 to 3 indicating the time format, 838 * ignored if flags is 2 839 * @param dateStyle a value from 0 to 3 indicating the time format, 840 * ignored if flags is 1 841 * @param flags either 1 for a time format, 2 for a date format, 842 * or 3 for a date/time format 843 * @param loc the locale for the format 844 */ get(int timeStyle, int dateStyle, int flags, Locale loc)845 private static DateFormat get(int timeStyle, int dateStyle, 846 int flags, Locale loc) { 847 if ((flags & 1) != 0) { 848 if (timeStyle < 0 || timeStyle > 3) { 849 throw new IllegalArgumentException("Illegal time style " + timeStyle); 850 } 851 } else { 852 timeStyle = -1; 853 } 854 if ((flags & 2) != 0) { 855 if (dateStyle < 0 || dateStyle > 3) { 856 throw new IllegalArgumentException("Illegal date style " + dateStyle); 857 } 858 } else { 859 dateStyle = -1; 860 } 861 862 // BEGIN Android-changed: Remove use of DateFormatProvider and LocaleProviderAdapter. 863 /* 864 LocaleProviderAdapter adapter = LocaleProviderAdapter.getAdapter(DateFormatProvider.class, loc); 865 DateFormat dateFormat = get(adapter, timeStyle, dateStyle, loc); 866 if (dateFormat == null) { 867 dateFormat = get(LocaleProviderAdapter.forJRE(), timeStyle, dateStyle, loc); 868 } 869 return dateFormat; 870 */ 871 try { 872 return new SimpleDateFormat(timeStyle, dateStyle, loc); 873 } catch (MissingResourceException e) { 874 return new SimpleDateFormat("M/d/yy h:mm a"); 875 } 876 // END Android-changed: Remove use of DateFormatProvider and LocaleProviderAdapter. 877 } 878 879 /** 880 * Create a new date format. 881 */ DateFormat()882 protected DateFormat() {} 883 884 /** 885 * Defines constants that are used as attribute keys in the 886 * {@code AttributedCharacterIterator} returned 887 * from {@code DateFormat.formatToCharacterIterator} and as 888 * field identifiers in {@code FieldPosition}. 889 * <p> 890 * The class also provides two methods to map 891 * between its constants and the corresponding Calendar constants. 892 * 893 * @since 1.4 894 * @see java.util.Calendar 895 */ 896 public static class Field extends Format.Field { 897 898 // Proclaim serial compatibility with 1.4 FCS 899 @java.io.Serial 900 private static final long serialVersionUID = 7441350119349544720L; 901 902 // table of all instances in this class, used by readResolve 903 private static final Map<String, Field> instanceMap = new HashMap<>(18); 904 // Maps from Calendar constant (such as Calendar.ERA) to Field 905 // constant (such as Field.ERA). 906 private static final Field[] calendarToFieldMapping = 907 new Field[Calendar.FIELD_COUNT]; 908 909 /** Calendar field. */ 910 private int calendarField; 911 912 /** 913 * Returns the {@code Field} constant that corresponds to 914 * the {@code Calendar} constant {@code calendarField}. 915 * If there is no direct mapping between the {@code Calendar} 916 * constant and a {@code Field}, null is returned. 917 * 918 * @throws IllegalArgumentException if {@code calendarField} is 919 * not the value of a {@code Calendar} field constant. 920 * @param calendarField Calendar field constant 921 * @return Field instance representing calendarField. 922 * @see java.util.Calendar 923 */ ofCalendarField(int calendarField)924 public static Field ofCalendarField(int calendarField) { 925 if (calendarField < 0 || calendarField >= 926 calendarToFieldMapping.length) { 927 throw new IllegalArgumentException("Unknown Calendar constant " 928 + calendarField); 929 } 930 return calendarToFieldMapping[calendarField]; 931 } 932 933 /** 934 * Creates a {@code Field}. 935 * 936 * @param name the name of the {@code Field} 937 * @param calendarField the {@code Calendar} constant this 938 * {@code Field} corresponds to; any value, even one 939 * outside the range of legal {@code Calendar} values may 940 * be used, but {@code -1} should be used for values 941 * that don't correspond to legal {@code Calendar} values 942 */ Field(String name, int calendarField)943 protected Field(String name, int calendarField) { 944 super(name); 945 this.calendarField = calendarField; 946 if (this.getClass() == DateFormat.Field.class) { 947 instanceMap.put(name, this); 948 if (calendarField >= 0) { 949 // assert(calendarField < Calendar.FIELD_COUNT); 950 calendarToFieldMapping[calendarField] = this; 951 } 952 } 953 } 954 955 /** 956 * Returns the {@code Calendar} field associated with this 957 * attribute. For example, if this represents the hours field of 958 * a {@code Calendar}, this would return 959 * {@code Calendar.HOUR}. If there is no corresponding 960 * {@code Calendar} constant, this will return -1. 961 * 962 * @return Calendar constant for this field 963 * @see java.util.Calendar 964 */ getCalendarField()965 public int getCalendarField() { 966 return calendarField; 967 } 968 969 /** 970 * Resolves instances being deserialized to the predefined constants. 971 * 972 * @throws InvalidObjectException if the constant could not be 973 * resolved. 974 * @return resolved DateFormat.Field constant 975 */ 976 @Override 977 @java.io.Serial readResolve()978 protected Object readResolve() throws InvalidObjectException { 979 if (this.getClass() != DateFormat.Field.class) { 980 throw new InvalidObjectException("subclass didn't correctly implement readResolve"); 981 } 982 983 Object instance = instanceMap.get(getName()); 984 if (instance != null) { 985 return instance; 986 } else { 987 throw new InvalidObjectException("unknown attribute name"); 988 } 989 } 990 991 // 992 // The constants 993 // 994 995 /** 996 * Constant identifying the era field. 997 */ 998 public static final Field ERA = new Field("era", Calendar.ERA); 999 1000 /** 1001 * Constant identifying the year field. 1002 */ 1003 public static final Field YEAR = new Field("year", Calendar.YEAR); 1004 1005 /** 1006 * Constant identifying the month field. 1007 */ 1008 public static final Field MONTH = new Field("month", Calendar.MONTH); 1009 1010 /** 1011 * Constant identifying the day of month field. 1012 */ 1013 public static final Field DAY_OF_MONTH = new 1014 Field("day of month", Calendar.DAY_OF_MONTH); 1015 1016 /** 1017 * Constant identifying the hour of day field, where the legal values 1018 * are 1 to 24. 1019 */ 1020 public static final Field HOUR_OF_DAY1 = new Field("hour of day 1",-1); 1021 1022 /** 1023 * Constant identifying the hour of day field, where the legal values 1024 * are 0 to 23. 1025 */ 1026 public static final Field HOUR_OF_DAY0 = new 1027 Field("hour of day", Calendar.HOUR_OF_DAY); 1028 1029 /** 1030 * Constant identifying the minute field. 1031 */ 1032 public static final Field MINUTE =new Field("minute", Calendar.MINUTE); 1033 1034 /** 1035 * Constant identifying the second field. 1036 */ 1037 public static final Field SECOND =new Field("second", Calendar.SECOND); 1038 1039 /** 1040 * Constant identifying the millisecond field. 1041 */ 1042 public static final Field MILLISECOND = new 1043 Field("millisecond", Calendar.MILLISECOND); 1044 1045 /** 1046 * Constant identifying the day of week field. 1047 */ 1048 public static final Field DAY_OF_WEEK = new 1049 Field("day of week", Calendar.DAY_OF_WEEK); 1050 1051 /** 1052 * Constant identifying the day of year field. 1053 */ 1054 public static final Field DAY_OF_YEAR = new 1055 Field("day of year", Calendar.DAY_OF_YEAR); 1056 1057 /** 1058 * Constant identifying the day of week field. 1059 */ 1060 public static final Field DAY_OF_WEEK_IN_MONTH = 1061 new Field("day of week in month", 1062 Calendar.DAY_OF_WEEK_IN_MONTH); 1063 1064 /** 1065 * Constant identifying the week of year field. 1066 */ 1067 public static final Field WEEK_OF_YEAR = new 1068 Field("week of year", Calendar.WEEK_OF_YEAR); 1069 1070 /** 1071 * Constant identifying the week of month field. 1072 */ 1073 public static final Field WEEK_OF_MONTH = new 1074 Field("week of month", Calendar.WEEK_OF_MONTH); 1075 1076 /** 1077 * Constant identifying the time of day indicator 1078 * (e.g. "a.m." or "p.m.") field. 1079 */ 1080 public static final Field AM_PM = new 1081 Field("am pm", Calendar.AM_PM); 1082 1083 /** 1084 * Constant identifying the hour field, where the legal values are 1085 * 1 to 12. 1086 */ 1087 public static final Field HOUR1 = new Field("hour 1", -1); 1088 1089 /** 1090 * Constant identifying the hour field, where the legal values are 1091 * 0 to 11. 1092 */ 1093 public static final Field HOUR0 = new 1094 Field("hour", Calendar.HOUR); 1095 1096 /** 1097 * Constant identifying the time zone field. 1098 */ 1099 public static final Field TIME_ZONE = new Field("time zone", -1); 1100 } 1101 } 1102