1 /* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.text.format; 18 19 import android.annotation.NonNull; 20 import android.app.compat.CompatChanges; 21 import android.compat.annotation.ChangeId; 22 import android.compat.annotation.EnabledSince; 23 import android.compat.annotation.UnsupportedAppUsage; 24 import android.content.Context; 25 import android.icu.text.DateFormatSymbols; 26 import android.icu.text.DateTimePatternGenerator; 27 import android.os.Build; 28 import android.provider.Settings; 29 import android.text.SpannableStringBuilder; 30 import android.text.Spanned; 31 import android.text.SpannedString; 32 import android.text.TextUtils; 33 34 import java.text.SimpleDateFormat; 35 import java.util.Calendar; 36 import java.util.Date; 37 import java.util.GregorianCalendar; 38 import java.util.Locale; 39 import java.util.TimeZone; 40 41 /** 42 * Utility class for producing strings with formatted date/time. 43 * 44 * <p>Most callers should avoid supplying their own format strings to this 45 * class' {@code format} methods and rely on the correctly localized ones 46 * supplied by the system. This class' factory methods return 47 * appropriately-localized {@link java.text.DateFormat} instances, suitable 48 * for both formatting and parsing dates. For the canonical documentation 49 * of format strings, see {@link java.text.SimpleDateFormat}. 50 * 51 * <p>In cases where the system does not provide a suitable pattern, 52 * this class offers the {@link #getBestDateTimePattern} method. 53 * 54 * <p>The {@code format} methods in this class implement a subset of Unicode 55 * <a href="http://www.unicode.org/reports/tr35/#Date_Format_Patterns">UTS #35</a> patterns. 56 * The subset currently supported by this class includes the following format characters: 57 * {@code acdEHhLKkLMmsyz}. Up to API level 17, only {@code adEhkMmszy} were supported. 58 * Note that this class incorrectly implements {@code k} as if it were {@code H} for backwards 59 * compatibility. 60 * 61 * <p>See {@link java.text.SimpleDateFormat} for more documentation 62 * about patterns, or if you need a more complete or correct implementation. 63 * Note that the non-{@code format} methods in this class are implemented by 64 * {@code SimpleDateFormat}. 65 */ 66 public class DateFormat { 67 /** 68 * @deprecated Use a literal {@code '} instead. 69 * @removed 70 */ 71 @Deprecated 72 public static final char QUOTE = '\''; 73 74 /** 75 * @deprecated Use a literal {@code 'a'} instead. 76 * @removed 77 */ 78 @Deprecated 79 public static final char AM_PM = 'a'; 80 81 /** 82 * @deprecated Use a literal {@code 'a'} instead; 'A' was always equivalent to 'a'. 83 * @removed 84 */ 85 @Deprecated 86 public static final char CAPITAL_AM_PM = 'A'; 87 88 /** 89 * @deprecated Use a literal {@code 'd'} instead. 90 * @removed 91 */ 92 @Deprecated 93 public static final char DATE = 'd'; 94 95 /** 96 * @deprecated Use a literal {@code 'E'} instead. 97 * @removed 98 */ 99 @Deprecated 100 public static final char DAY = 'E'; 101 102 /** 103 * @deprecated Use a literal {@code 'h'} instead. 104 * @removed 105 */ 106 @Deprecated 107 public static final char HOUR = 'h'; 108 109 /** 110 * @deprecated Use a literal {@code 'H'} (for compatibility with {@link SimpleDateFormat} 111 * and Unicode) or {@code 'k'} (for compatibility with Android releases up to and including 112 * Jelly Bean MR-1) instead. Note that the two are incompatible. 113 * 114 * @removed 115 */ 116 @Deprecated 117 public static final char HOUR_OF_DAY = 'k'; 118 119 /** 120 * @deprecated Use a literal {@code 'm'} instead. 121 * @removed 122 */ 123 @Deprecated 124 public static final char MINUTE = 'm'; 125 126 /** 127 * @deprecated Use a literal {@code 'M'} instead. 128 * @removed 129 */ 130 @Deprecated 131 public static final char MONTH = 'M'; 132 133 /** 134 * @deprecated Use a literal {@code 'L'} instead. 135 * @removed 136 */ 137 @Deprecated 138 public static final char STANDALONE_MONTH = 'L'; 139 140 /** 141 * @deprecated Use a literal {@code 's'} instead. 142 * @removed 143 */ 144 @Deprecated 145 public static final char SECONDS = 's'; 146 147 /** 148 * @deprecated Use a literal {@code 'z'} instead. 149 * @removed 150 */ 151 @Deprecated 152 public static final char TIME_ZONE = 'z'; 153 154 /** 155 * @deprecated Use a literal {@code 'y'} instead. 156 * @removed 157 */ 158 @Deprecated 159 public static final char YEAR = 'y'; 160 161 162 private static final Object sLocaleLock = new Object(); 163 private static Locale sIs24HourLocale; 164 private static boolean sIs24Hour; 165 166 /** 167 * {@link #getBestDateTimePattern(Locale, String)} does not allow non-consecutive repeated 168 * symbol in the skeleton. For example, please use a skeleton of {@code "jmm"} or 169 * {@code "hmma"} instead of {@code "ahmma"} or {@code "jmma"}, because the field 'j' could 170 * mean using 12-hour in some locales and, in this case, is duplicated as the 'a' field. 171 */ 172 @ChangeId 173 @EnabledSince(targetSdkVersion = Build.VERSION_CODES.CUR_DEVELOPMENT) 174 static final long DISALLOW_DUPLICATE_FIELD_IN_SKELETON = 170233598L; 175 176 /** 177 * Returns true if times should be formatted as 24 hour times, false if times should be 178 * formatted as 12 hour (AM/PM) times. Based on the user's chosen locale and other preferences. 179 * @param context the context to use for the content resolver 180 * @return true if 24 hour time format is selected, false otherwise. 181 */ is24HourFormat(Context context)182 public static boolean is24HourFormat(Context context) { 183 return is24HourFormat(context, context.getUserId()); 184 } 185 186 /** 187 * Returns true if times should be formatted as 24 hour times, false if times should be 188 * formatted as 12 hour (AM/PM) times. Based on the user's chosen locale and other preferences. 189 * @param context the context to use for the content resolver 190 * @param userHandle the user handle of the user to query. 191 * @return true if 24 hour time format is selected, false otherwise. 192 * 193 * @hide 194 */ 195 @UnsupportedAppUsage is24HourFormat(Context context, int userHandle)196 public static boolean is24HourFormat(Context context, int userHandle) { 197 final String value = Settings.System.getStringForUser(context.getContentResolver(), 198 Settings.System.TIME_12_24, userHandle); 199 if (value != null) { 200 return value.equals("24"); 201 } 202 203 return is24HourLocale(context.getResources().getConfiguration().locale); 204 } 205 206 /** 207 * Returns true if the specified locale uses a 24-hour time format by default, ignoring user 208 * settings. 209 * @param locale the locale to check 210 * @return true if the locale uses a 24 hour time format by default, false otherwise 211 * @hide 212 */ is24HourLocale(@onNull Locale locale)213 public static boolean is24HourLocale(@NonNull Locale locale) { 214 synchronized (sLocaleLock) { 215 if (sIs24HourLocale != null && sIs24HourLocale.equals(locale)) { 216 return sIs24Hour; 217 } 218 } 219 220 final java.text.DateFormat natural = 221 java.text.DateFormat.getTimeInstance(java.text.DateFormat.LONG, locale); 222 223 final boolean is24Hour; 224 if (natural instanceof SimpleDateFormat) { 225 final SimpleDateFormat sdf = (SimpleDateFormat) natural; 226 final String pattern = sdf.toPattern(); 227 is24Hour = hasDesignator(pattern, 'H'); 228 } else { 229 is24Hour = false; 230 } 231 232 synchronized (sLocaleLock) { 233 sIs24HourLocale = locale; 234 sIs24Hour = is24Hour; 235 } 236 237 return is24Hour; 238 } 239 240 /** 241 * Returns the best possible localized form of the given skeleton for the given 242 * locale. A skeleton is similar to, and uses the same format characters as, a Unicode 243 * <a href="http://www.unicode.org/reports/tr35/#Date_Format_Patterns">UTS #35</a> 244 * pattern. 245 * 246 * <p>One difference is that order is irrelevant. For example, "MMMMd" will return 247 * "MMMM d" in the {@code en_US} locale, but "d. MMMM" in the {@code de_CH} locale. 248 * 249 * <p>Note also in that second example that the necessary punctuation for German was 250 * added. For the same input in {@code es_ES}, we'd have even more extra text: 251 * "d 'de' MMMM". 252 * 253 * <p>This method will automatically correct for grammatical necessity. Given the 254 * same "MMMMd" input, this method will return "d LLLL" in the {@code fa_IR} locale, 255 * where stand-alone months are necessary. Lengths are preserved where meaningful, 256 * so "Md" would give a different result to "MMMd", say, except in a locale such as 257 * {@code ja_JP} where there is only one length of month. 258 * 259 * <p>This method will only return patterns that are in CLDR, and is useful whenever 260 * you know what elements you want in your format string but don't want to make your 261 * code specific to any one locale. 262 * 263 * @param locale the locale into which the skeleton should be localized 264 * @param skeleton a skeleton as described above 265 * @return a string pattern suitable for use with {@link java.text.SimpleDateFormat}. 266 */ getBestDateTimePattern(Locale locale, String skeleton)267 public static String getBestDateTimePattern(Locale locale, String skeleton) { 268 DateTimePatternGenerator dtpg = DateTimePatternGenerator.getInstance(locale); 269 boolean allowDuplicateFields = !CompatChanges.isChangeEnabled( 270 DISALLOW_DUPLICATE_FIELD_IN_SKELETON); 271 return dtpg.getBestPattern(skeleton, DateTimePatternGenerator.MATCH_NO_OPTIONS, 272 allowDuplicateFields); 273 } 274 275 /** 276 * Returns a {@link java.text.DateFormat} object that can format the time according 277 * to the context's locale and the user's 12-/24-hour clock preference. 278 * @param context the application context 279 * @return the {@link java.text.DateFormat} object that properly formats the time. 280 */ getTimeFormat(Context context)281 public static java.text.DateFormat getTimeFormat(Context context) { 282 final Locale locale = context.getResources().getConfiguration().locale; 283 return new java.text.SimpleDateFormat(getTimeFormatString(context), locale); 284 } 285 286 /** 287 * Returns a String pattern that can be used to format the time according 288 * to the context's locale and the user's 12-/24-hour clock preference. 289 * @param context the application context 290 * @hide 291 */ 292 @UnsupportedAppUsage getTimeFormatString(Context context)293 public static String getTimeFormatString(Context context) { 294 return getTimeFormatString(context, context.getUserId()); 295 } 296 297 /** 298 * Returns a String pattern that can be used to format the time according 299 * to the context's locale and the user's 12-/24-hour clock preference. 300 * @param context the application context 301 * @param userHandle the user handle of the user to query the format for 302 * @hide 303 */ 304 @UnsupportedAppUsage getTimeFormatString(Context context, int userHandle)305 public static String getTimeFormatString(Context context, int userHandle) { 306 DateTimePatternGenerator dtpg = DateTimePatternGenerator.getInstance( 307 context.getResources().getConfiguration().locale); 308 return is24HourFormat(context, userHandle) ? dtpg.getBestPattern("Hm") 309 : dtpg.getBestPattern("hm"); 310 } 311 312 /** 313 * Returns a {@link java.text.DateFormat} object that can format the date 314 * in short form according to the context's locale. 315 * 316 * @param context the application context 317 * @return the {@link java.text.DateFormat} object that properly formats the date. 318 */ getDateFormat(Context context)319 public static java.text.DateFormat getDateFormat(Context context) { 320 final Locale locale = context.getResources().getConfiguration().locale; 321 return java.text.DateFormat.getDateInstance(java.text.DateFormat.SHORT, locale); 322 } 323 324 /** 325 * Returns a {@link java.text.DateFormat} object that can format the date 326 * in long form (such as {@code Monday, January 3, 2000}) for the context's locale. 327 * @param context the application context 328 * @return the {@link java.text.DateFormat} object that formats the date in long form. 329 */ getLongDateFormat(Context context)330 public static java.text.DateFormat getLongDateFormat(Context context) { 331 final Locale locale = context.getResources().getConfiguration().locale; 332 return java.text.DateFormat.getDateInstance(java.text.DateFormat.LONG, locale); 333 } 334 335 /** 336 * Returns a {@link java.text.DateFormat} object that can format the date 337 * in medium form (such as {@code Jan 3, 2000}) for the context's locale. 338 * @param context the application context 339 * @return the {@link java.text.DateFormat} object that formats the date in long form. 340 */ getMediumDateFormat(Context context)341 public static java.text.DateFormat getMediumDateFormat(Context context) { 342 final Locale locale = context.getResources().getConfiguration().locale; 343 return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM, locale); 344 } 345 346 /** 347 * Gets the current date format stored as a char array. Returns a 3 element 348 * array containing the day ({@code 'd'}), month ({@code 'M'}), and year ({@code 'y'})) 349 * in the order specified by the user's format preference. Note that this order is 350 * <i>only</i> appropriate for all-numeric dates; spelled-out (MEDIUM and LONG) 351 * dates will generally contain other punctuation, spaces, or words, 352 * not just the day, month, and year, and not necessarily in the same 353 * order returned here. 354 */ getDateFormatOrder(Context context)355 public static char[] getDateFormatOrder(Context context) { 356 return getDateFormatOrder(getDateFormatString(context)); 357 } 358 359 /** 360 * @hide Used by internal framework class {@link android.widget.DatePickerSpinnerDelegate}. 361 */ getDateFormatOrder(String pattern)362 public static char[] getDateFormatOrder(String pattern) { 363 char[] result = new char[3]; 364 int resultIndex = 0; 365 boolean sawDay = false; 366 boolean sawMonth = false; 367 boolean sawYear = false; 368 369 for (int i = 0; i < pattern.length(); ++i) { 370 char ch = pattern.charAt(i); 371 if (ch == 'd' || ch == 'L' || ch == 'M' || ch == 'y') { 372 if (ch == 'd' && !sawDay) { 373 result[resultIndex++] = 'd'; 374 sawDay = true; 375 } else if ((ch == 'L' || ch == 'M') && !sawMonth) { 376 result[resultIndex++] = 'M'; 377 sawMonth = true; 378 } else if ((ch == 'y') && !sawYear) { 379 result[resultIndex++] = 'y'; 380 sawYear = true; 381 } 382 } else if (ch == 'G') { 383 // Ignore the era specifier, if present. 384 } else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { 385 throw new IllegalArgumentException("Bad pattern character '" + ch + "' in " 386 + pattern); 387 } else if (ch == '\'') { 388 if (i < pattern.length() - 1 && pattern.charAt(i + 1) == '\'') { 389 ++i; 390 } else { 391 i = pattern.indexOf('\'', i + 1); 392 if (i == -1) { 393 throw new IllegalArgumentException("Bad quoting in " + pattern); 394 } 395 ++i; 396 } 397 } else { 398 // Ignore spaces and punctuation. 399 } 400 } 401 return result; 402 } 403 getDateFormatString(Context context)404 private static String getDateFormatString(Context context) { 405 final Locale locale = context.getResources().getConfiguration().locale; 406 java.text.DateFormat df = java.text.DateFormat.getDateInstance( 407 java.text.DateFormat.SHORT, locale); 408 if (df instanceof SimpleDateFormat) { 409 return ((SimpleDateFormat) df).toPattern(); 410 } 411 412 throw new AssertionError("!(df instanceof SimpleDateFormat)"); 413 } 414 415 /** 416 * Given a format string and a time in milliseconds since Jan 1, 1970 GMT, returns a 417 * CharSequence containing the requested date. 418 * @param inFormat the format string, as described in {@link android.text.format.DateFormat} 419 * @param inTimeInMillis in milliseconds since Jan 1, 1970 GMT 420 * @return a {@link CharSequence} containing the requested text 421 */ format(CharSequence inFormat, long inTimeInMillis)422 public static CharSequence format(CharSequence inFormat, long inTimeInMillis) { 423 return format(inFormat, new Date(inTimeInMillis)); 424 } 425 426 /** 427 * Given a format string and a {@link java.util.Date} object, returns a CharSequence containing 428 * the requested date. 429 * @param inFormat the format string, as described in {@link android.text.format.DateFormat} 430 * @param inDate the date to format 431 * @return a {@link CharSequence} containing the requested text 432 */ format(CharSequence inFormat, Date inDate)433 public static CharSequence format(CharSequence inFormat, Date inDate) { 434 Calendar c = new GregorianCalendar(); 435 c.setTime(inDate); 436 return format(inFormat, c); 437 } 438 439 /** 440 * Indicates whether the specified format string contains seconds. 441 * 442 * Always returns false if the input format is null. 443 * 444 * @param inFormat the format string, as described in {@link android.text.format.DateFormat} 445 * 446 * @return true if the format string contains {@link #SECONDS}, false otherwise 447 * 448 * @hide 449 */ 450 @UnsupportedAppUsage hasSeconds(CharSequence inFormat)451 public static boolean hasSeconds(CharSequence inFormat) { 452 return hasDesignator(inFormat, SECONDS); 453 } 454 455 /** 456 * Test if a format string contains the given designator. Always returns 457 * {@code false} if the input format is {@code null}. 458 * 459 * Note that this is intended for searching for designators, not arbitrary 460 * characters. So searching for a literal single quote would not work correctly. 461 * 462 * @hide 463 */ 464 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) hasDesignator(CharSequence inFormat, char designator)465 public static boolean hasDesignator(CharSequence inFormat, char designator) { 466 if (inFormat == null) return false; 467 468 final int length = inFormat.length(); 469 470 boolean insideQuote = false; 471 for (int i = 0; i < length; i++) { 472 final char c = inFormat.charAt(i); 473 if (c == QUOTE) { 474 insideQuote = !insideQuote; 475 } else if (!insideQuote) { 476 if (c == designator) { 477 return true; 478 } 479 } 480 } 481 482 return false; 483 } 484 485 /** 486 * Given a format string and a {@link java.util.Calendar} object, returns a CharSequence 487 * containing the requested date. 488 * @param inFormat the format string, as described in {@link android.text.format.DateFormat} 489 * @param inDate the date to format 490 * @return a {@link CharSequence} containing the requested text 491 */ format(CharSequence inFormat, Calendar inDate)492 public static CharSequence format(CharSequence inFormat, Calendar inDate) { 493 SpannableStringBuilder s = new SpannableStringBuilder(inFormat); 494 int count; 495 496 DateFormatSymbols dfs = getIcuDateFormatSymbols(Locale.getDefault()); 497 String[] amPm = dfs.getAmPmStrings(); 498 499 int len = inFormat.length(); 500 501 for (int i = 0; i < len; i += count) { 502 count = 1; 503 int c = s.charAt(i); 504 505 if (c == QUOTE) { 506 count = appendQuotedText(s, i); 507 len = s.length(); 508 continue; 509 } 510 511 while ((i + count < len) && (s.charAt(i + count) == c)) { 512 count++; 513 } 514 515 String replacement; 516 switch (c) { 517 case 'A': 518 case 'a': 519 replacement = amPm[inDate.get(Calendar.AM_PM) - Calendar.AM]; 520 break; 521 case 'd': 522 replacement = zeroPad(inDate.get(Calendar.DATE), count); 523 break; 524 case 'c': 525 case 'E': 526 replacement = getDayOfWeekString(dfs, 527 inDate.get(Calendar.DAY_OF_WEEK), count, c); 528 break; 529 case 'K': // hour in am/pm (0-11) 530 case 'h': // hour in am/pm (1-12) 531 { 532 int hour = inDate.get(Calendar.HOUR); 533 if (c == 'h' && hour == 0) { 534 hour = 12; 535 } 536 replacement = zeroPad(hour, count); 537 } 538 break; 539 case 'H': // hour in day (0-23) 540 case 'k': // hour in day (1-24) [but see note below] 541 { 542 int hour = inDate.get(Calendar.HOUR_OF_DAY); 543 // Historically on Android 'k' was interpreted as 'H', which wasn't 544 // implemented, so pretty much all callers that want to format 24-hour 545 // times are abusing 'k'. http://b/8359981. 546 if (false && c == 'k' && hour == 0) { 547 hour = 24; 548 } 549 replacement = zeroPad(hour, count); 550 } 551 break; 552 case 'L': 553 case 'M': 554 replacement = getMonthString(dfs, inDate.get(Calendar.MONTH), count, c); 555 break; 556 case 'm': 557 replacement = zeroPad(inDate.get(Calendar.MINUTE), count); 558 break; 559 case 's': 560 replacement = zeroPad(inDate.get(Calendar.SECOND), count); 561 break; 562 case 'y': 563 replacement = getYearString(inDate.get(Calendar.YEAR), count); 564 break; 565 case 'z': 566 replacement = getTimeZoneString(inDate, count); 567 break; 568 default: 569 replacement = null; 570 break; 571 } 572 573 if (replacement != null) { 574 s.replace(i, i + count, replacement); 575 count = replacement.length(); // CARE: count is used in the for loop above 576 len = s.length(); 577 } 578 } 579 580 if (inFormat instanceof Spanned) { 581 return new SpannedString(s); 582 } else { 583 return s.toString(); 584 } 585 } 586 getDayOfWeekString(DateFormatSymbols dfs, int day, int count, int kind)587 private static String getDayOfWeekString(DateFormatSymbols dfs, int day, int count, int kind) { 588 boolean standalone = (kind == 'c'); 589 int context = standalone ? DateFormatSymbols.STANDALONE : DateFormatSymbols.FORMAT; 590 final int width; 591 if (count == 5) { 592 width = DateFormatSymbols.NARROW; 593 } else if (count == 4) { 594 width = DateFormatSymbols.WIDE; 595 } else { 596 width = DateFormatSymbols.ABBREVIATED; 597 } 598 return dfs.getWeekdays(context, width)[day]; 599 } 600 getMonthString(DateFormatSymbols dfs, int month, int count, int kind)601 private static String getMonthString(DateFormatSymbols dfs, int month, int count, int kind) { 602 boolean standalone = (kind == 'L'); 603 int monthContext = standalone ? DateFormatSymbols.STANDALONE : DateFormatSymbols.FORMAT; 604 if (count == 5) { 605 return dfs.getMonths(monthContext, DateFormatSymbols.NARROW)[month]; 606 } else if (count == 4) { 607 return dfs.getMonths(monthContext, DateFormatSymbols.WIDE)[month]; 608 } else if (count == 3) { 609 return dfs.getMonths(monthContext, DateFormatSymbols.ABBREVIATED)[month]; 610 } else { 611 // Calendar.JANUARY == 0, so add 1 to month. 612 return zeroPad(month+1, count); 613 } 614 } 615 getTimeZoneString(Calendar inDate, int count)616 private static String getTimeZoneString(Calendar inDate, int count) { 617 TimeZone tz = inDate.getTimeZone(); 618 if (count < 2) { // FIXME: shouldn't this be <= 2 ? 619 return formatZoneOffset(inDate.get(Calendar.DST_OFFSET) + 620 inDate.get(Calendar.ZONE_OFFSET), 621 count); 622 } else { 623 boolean dst = inDate.get(Calendar.DST_OFFSET) != 0; 624 return tz.getDisplayName(dst, TimeZone.SHORT); 625 } 626 } 627 formatZoneOffset(int offset, int count)628 private static String formatZoneOffset(int offset, int count) { 629 offset /= 1000; // milliseconds to seconds 630 StringBuilder tb = new StringBuilder(); 631 632 if (offset < 0) { 633 tb.insert(0, "-"); 634 offset = -offset; 635 } else { 636 tb.insert(0, "+"); 637 } 638 639 int hours = offset / 3600; 640 int minutes = (offset % 3600) / 60; 641 642 tb.append(zeroPad(hours, 2)); 643 tb.append(zeroPad(minutes, 2)); 644 return tb.toString(); 645 } 646 getYearString(int year, int count)647 private static String getYearString(int year, int count) { 648 return (count <= 2) ? zeroPad(year % 100, 2) 649 : String.format(Locale.getDefault(), "%d", year); 650 } 651 652 653 /** 654 * Strips quotation marks from the {@code formatString} and appends the result back to the 655 * {@code formatString}. 656 * 657 * @param formatString the format string, as described in 658 * {@link android.text.format.DateFormat}, to be modified 659 * @param index index of the first quote 660 * @return the length of the quoted text that was appended. 661 * @hide 662 */ appendQuotedText(SpannableStringBuilder formatString, int index)663 public static int appendQuotedText(SpannableStringBuilder formatString, int index) { 664 int length = formatString.length(); 665 if (index + 1 < length && formatString.charAt(index + 1) == QUOTE) { 666 formatString.delete(index, index + 1); 667 return 1; 668 } 669 670 int count = 0; 671 672 // delete leading quote 673 formatString.delete(index, index + 1); 674 length--; 675 676 while (index < length) { 677 char c = formatString.charAt(index); 678 679 if (c == QUOTE) { 680 // QUOTEQUOTE -> QUOTE 681 if (index + 1 < length && formatString.charAt(index + 1) == QUOTE) { 682 683 formatString.delete(index, index + 1); 684 length--; 685 count++; 686 index++; 687 } else { 688 // Closing QUOTE ends quoted text copying 689 formatString.delete(index, index + 1); 690 break; 691 } 692 } else { 693 index++; 694 count++; 695 } 696 } 697 698 return count; 699 } 700 zeroPad(int inValue, int inMinDigits)701 private static String zeroPad(int inValue, int inMinDigits) { 702 return String.format(Locale.getDefault(), "%0" + inMinDigits + "d", inValue); 703 } 704 705 /** 706 * We use Gregorian calendar for date formats in android.text.format and various UI widget 707 * historically. It's a utility method to get an {@link DateFormatSymbols} instance. Note that 708 * {@link DateFormatSymbols} has cache, and external cache is not needed unless same instance is 709 * requested repeatedly in the performance critical code. 710 * 711 * @hide 712 */ getIcuDateFormatSymbols(Locale locale)713 public static DateFormatSymbols getIcuDateFormatSymbols(Locale locale) { 714 return new DateFormatSymbols(android.icu.util.GregorianCalendar.class, locale); 715 } 716 } 717