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