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.util; 41 42 import android.icu.text.TimeZoneNames; 43 import com.android.i18n.timezone.ZoneInfoData; 44 import com.android.i18n.timezone.ZoneInfoDb; 45 import com.android.icu.util.ExtendedTimeZone; 46 47 import java.io.IOException; 48 import java.io.Serializable; 49 import java.time.ZoneId; 50 import java.util.function.Supplier; 51 import java.util.regex.Matcher; 52 import java.util.regex.Pattern; 53 import libcore.io.IoUtils; 54 import libcore.util.ZoneInfo; 55 56 import dalvik.system.RuntimeHooks; 57 58 /** 59 * <code>TimeZone</code> represents a time zone offset, and also figures out daylight 60 * savings. 61 * 62 * <p> 63 * Typically, you get a <code>TimeZone</code> using <code>getDefault</code> 64 * which creates a <code>TimeZone</code> based on the time zone where the program 65 * is running. For example, for a program running in Japan, <code>getDefault</code> 66 * creates a <code>TimeZone</code> object based on Japanese Standard Time. 67 * 68 * <p> 69 * You can also get a <code>TimeZone</code> using <code>getTimeZone</code> 70 * along with a time zone ID. For instance, the time zone ID for the 71 * U.S. Pacific Time zone is "America/Los_Angeles". So, you can get a 72 * U.S. Pacific Time <code>TimeZone</code> object with: 73 * <blockquote><pre> 74 * TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles"); 75 * </pre></blockquote> 76 * You can use the <code>getAvailableIDs</code> method to iterate through 77 * all the supported time zone IDs. You can then choose a 78 * supported ID to get a <code>TimeZone</code>. 79 * If the time zone you want is not represented by one of the 80 * supported IDs, then a custom time zone ID can be specified to 81 * produce a TimeZone. The syntax of a custom time zone ID is: 82 * 83 * <blockquote><pre> 84 * <a name="CustomID"><i>CustomID:</i></a> 85 * <code>GMT</code> <i>Sign</i> <i>Hours</i> <code>:</code> <i>Minutes</i> 86 * <code>GMT</code> <i>Sign</i> <i>Hours</i> <i>Minutes</i> 87 * <code>GMT</code> <i>Sign</i> <i>Hours</i> 88 * <i>Sign:</i> one of 89 * <code>+ -</code> 90 * <i>Hours:</i> 91 * <i>Digit</i> 92 * <i>Digit</i> <i>Digit</i> 93 * <i>Minutes:</i> 94 * <i>Digit</i> <i>Digit</i> 95 * <i>Digit:</i> one of 96 * <code>0 1 2 3 4 5 6 7 8 9</code> 97 * </pre></blockquote> 98 * 99 * <i>Hours</i> must be between 0 to 23 and <i>Minutes</i> must be 100 * between 00 to 59. For example, "GMT+10" and "GMT+0010" mean ten 101 * hours and ten minutes ahead of GMT, respectively. 102 * <p> 103 * The format is locale independent and digits must be taken from the 104 * Basic Latin block of the Unicode standard. No daylight saving time 105 * transition schedule can be specified with a custom time zone ID. If 106 * the specified string doesn't match the syntax, <code>"GMT"</code> 107 * is used. 108 * <p> 109 * When creating a <code>TimeZone</code>, the specified custom time 110 * zone ID is normalized in the following syntax: 111 * <blockquote><pre> 112 * <a name="NormalizedCustomID"><i>NormalizedCustomID:</i></a> 113 * <code>GMT</code> <i>Sign</i> <i>TwoDigitHours</i> <code>:</code> <i>Minutes</i> 114 * <i>Sign:</i> one of 115 * <code>+ -</code> 116 * <i>TwoDigitHours:</i> 117 * <i>Digit</i> <i>Digit</i> 118 * <i>Minutes:</i> 119 * <i>Digit</i> <i>Digit</i> 120 * <i>Digit:</i> one of 121 * <code>0 1 2 3 4 5 6 7 8 9</code> 122 * </pre></blockquote> 123 * For example, TimeZone.getTimeZone("GMT-8").getID() returns "GMT-08:00". 124 * 125 * <h3>Three-letter time zone IDs</h3> 126 * 127 * For compatibility with JDK 1.1.x, some other three-letter time zone IDs 128 * (such as "PST", "CTT", "AST") are also supported. However, <strong>their 129 * use is deprecated</strong> because the same abbreviation is often used 130 * for multiple time zones (for example, "CST" could be U.S. "Central Standard 131 * Time" and "China Standard Time"), and the Java platform can then only 132 * recognize one of them. 133 * 134 * 135 * @see Calendar 136 * @see GregorianCalendar 137 * @see SimpleTimeZone 138 * @author Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu 139 * @since JDK1.1 140 */ 141 abstract public class TimeZone implements Serializable, Cloneable { 142 /** 143 * Sole constructor. (For invocation by subclass constructors, typically 144 * implicit.) 145 */ TimeZone()146 public TimeZone() { 147 } 148 149 /** 150 * A style specifier for <code>getDisplayName()</code> indicating 151 * a short name, such as "PST." 152 * @see #LONG 153 * @since 1.2 154 */ 155 public static final int SHORT = 0; 156 157 /** 158 * A style specifier for <code>getDisplayName()</code> indicating 159 * a long name, such as "Pacific Standard Time." 160 * @see #SHORT 161 * @since 1.2 162 */ 163 public static final int LONG = 1; 164 165 // Android-changed: Use a preload holder to allow compile-time initialization of TimeZone and 166 // dependents. 167 private static class NoImagePreloadHolder { 168 public static final Pattern CUSTOM_ZONE_ID_PATTERN = Pattern.compile("^GMT[-+](\\d{1,2})(:?(\\d\\d))?$"); 169 } 170 171 // Proclaim serialization compatibility with JDK 1.1 172 static final long serialVersionUID = 3581463369166924961L; 173 174 // Android-changed: common timezone instances. 175 private static final TimeZone GMT = new SimpleTimeZone(0, "GMT"); 176 private static final TimeZone UTC = new SimpleTimeZone(0, "UTC"); 177 178 /** 179 * Gets the time zone offset, for current date, modified in case of 180 * daylight savings. This is the offset to add to UTC to get local time. 181 * <p> 182 * This method returns a historically correct offset if an 183 * underlying <code>TimeZone</code> implementation subclass 184 * supports historical Daylight Saving Time schedule and GMT 185 * offset changes. 186 * 187 * @param era the era of the given date. 188 * @param year the year in the given date. 189 * @param month the month in the given date. 190 * Month is 0-based. e.g., 0 for January. 191 * @param day the day-in-month of the given date. 192 * @param dayOfWeek the day-of-week of the given date. 193 * @param milliseconds the milliseconds in day in <em>standard</em> 194 * local time. 195 * 196 * @return the offset in milliseconds to add to GMT to get local time. 197 * 198 * @see Calendar#ZONE_OFFSET 199 * @see Calendar#DST_OFFSET 200 */ getOffset(int era, int year, int month, int day, int dayOfWeek, int milliseconds)201 public abstract int getOffset(int era, int year, int month, int day, 202 int dayOfWeek, int milliseconds); 203 204 /** 205 * Returns the offset of this time zone from UTC at the specified 206 * date. If Daylight Saving Time is in effect at the specified 207 * date, the offset value is adjusted with the amount of daylight 208 * saving. 209 * <p> 210 * This method returns a historically correct offset value if an 211 * underlying TimeZone implementation subclass supports historical 212 * Daylight Saving Time schedule and GMT offset changes. 213 * 214 * @param date the date represented in milliseconds since January 1, 1970 00:00:00 GMT 215 * @return the amount of time in milliseconds to add to UTC to get local time. 216 * 217 * @see Calendar#ZONE_OFFSET 218 * @see Calendar#DST_OFFSET 219 * @since 1.4 220 */ getOffset(long date)221 public int getOffset(long date) { 222 if (inDaylightTime(new Date(date))) { 223 return getRawOffset() + getDSTSavings(); 224 } 225 return getRawOffset(); 226 } 227 228 /** 229 * Gets the raw GMT offset and the amount of daylight saving of this 230 * time zone at the given time. 231 * @param date the milliseconds (since January 1, 1970, 232 * 00:00:00.000 GMT) at which the time zone offset and daylight 233 * saving amount are found 234 * @param offsets an array of int where the raw GMT offset 235 * (offset[0]) and daylight saving amount (offset[1]) are stored, 236 * or null if those values are not needed. The method assumes that 237 * the length of the given array is two or larger. 238 * @return the total amount of the raw GMT offset and daylight 239 * saving at the specified date. 240 * 241 * @see Calendar#ZONE_OFFSET 242 * @see Calendar#DST_OFFSET 243 */ getOffsets(long date, int[] offsets)244 int getOffsets(long date, int[] offsets) { 245 int rawoffset = getRawOffset(); 246 int dstoffset = 0; 247 if (inDaylightTime(new Date(date))) { 248 dstoffset = getDSTSavings(); 249 } 250 if (offsets != null) { 251 offsets[0] = rawoffset; 252 offsets[1] = dstoffset; 253 } 254 return rawoffset + dstoffset; 255 } 256 257 /** 258 * Sets the base time zone offset to GMT. 259 * This is the offset to add to UTC to get local time. 260 * <p> 261 * If an underlying <code>TimeZone</code> implementation subclass 262 * supports historical GMT offset changes, the specified GMT 263 * offset is set as the latest GMT offset and the difference from 264 * the known latest GMT offset value is used to adjust all 265 * historical GMT offset values. 266 * 267 * @param offsetMillis the given base time zone offset to GMT. 268 */ setRawOffset(int offsetMillis)269 abstract public void setRawOffset(int offsetMillis); 270 271 /** 272 * Returns the amount of time in milliseconds to add to UTC to get 273 * standard time in this time zone. Because this value is not 274 * affected by daylight saving time, it is called <I>raw 275 * offset</I>. 276 * <p> 277 * If an underlying <code>TimeZone</code> implementation subclass 278 * supports historical GMT offset changes, the method returns the 279 * raw offset value of the current date. In Honolulu, for example, 280 * its raw offset changed from GMT-10:30 to GMT-10:00 in 1947, and 281 * this method always returns -36000000 milliseconds (i.e., -10 282 * hours). 283 * 284 * @return the amount of raw offset time in milliseconds to add to UTC. 285 * @see Calendar#ZONE_OFFSET 286 */ getRawOffset()287 public abstract int getRawOffset(); 288 289 /** 290 * Gets the ID of this time zone. 291 * @return the ID of this time zone. 292 */ getID()293 public String getID() 294 { 295 return ID; 296 } 297 298 /** 299 * Sets the time zone ID. This does not change any other data in 300 * the time zone object. 301 * @param ID the new time zone ID. 302 */ setID(String ID)303 public void setID(String ID) 304 { 305 if (ID == null) { 306 throw new NullPointerException(); 307 } 308 this.ID = ID; 309 } 310 311 /** 312 * Returns a long standard time name of this {@code TimeZone} suitable for 313 * presentation to the user in the default locale. 314 * 315 * <p>This method is equivalent to: 316 * <blockquote><pre> 317 * getDisplayName(false, {@link #LONG}, 318 * Locale.getDefault({@link Locale.Category#DISPLAY})) 319 * </pre></blockquote> 320 * 321 * @return the human-readable name of this time zone in the default locale. 322 * @since 1.2 323 * @see #getDisplayName(boolean, int, Locale) 324 * @see Locale#getDefault(Locale.Category) 325 * @see Locale.Category 326 */ getDisplayName()327 public final String getDisplayName() { 328 return getDisplayName(false, LONG, 329 Locale.getDefault(Locale.Category.DISPLAY)); 330 } 331 332 /** 333 * Returns a long standard time name of this {@code TimeZone} suitable for 334 * presentation to the user in the specified {@code locale}. 335 * 336 * <p>This method is equivalent to: 337 * <blockquote><pre> 338 * getDisplayName(false, {@link #LONG}, locale) 339 * </pre></blockquote> 340 * 341 * @param locale the locale in which to supply the display name. 342 * @return the human-readable name of this time zone in the given locale. 343 * @exception NullPointerException if {@code locale} is {@code null}. 344 * @since 1.2 345 * @see #getDisplayName(boolean, int, Locale) 346 */ getDisplayName(Locale locale)347 public final String getDisplayName(Locale locale) { 348 return getDisplayName(false, LONG, locale); 349 } 350 351 /** 352 * Returns a name in the specified {@code style} of this {@code TimeZone} 353 * suitable for presentation to the user in the default locale. If the 354 * specified {@code daylight} is {@code true}, a Daylight Saving Time name 355 * is returned (even if this {@code TimeZone} doesn't observe Daylight Saving 356 * Time). Otherwise, a Standard Time name is returned. 357 * 358 * <p>This method is equivalent to: 359 * <blockquote><pre> 360 * getDisplayName(daylight, style, 361 * Locale.getDefault({@link Locale.Category#DISPLAY})) 362 * </pre></blockquote> 363 * 364 * @param daylight {@code true} specifying a Daylight Saving Time name, or 365 * {@code false} specifying a Standard Time name 366 * @param style either {@link #LONG} or {@link #SHORT} 367 * @return the human-readable name of this time zone in the default locale. 368 * @exception IllegalArgumentException if {@code style} is invalid. 369 * @since 1.2 370 * @see #getDisplayName(boolean, int, Locale) 371 * @see Locale#getDefault(Locale.Category) 372 * @see Locale.Category 373 * @see java.text.DateFormatSymbols#getZoneStrings() 374 */ getDisplayName(boolean daylight, int style)375 public final String getDisplayName(boolean daylight, int style) { 376 return getDisplayName(daylight, style, 377 Locale.getDefault(Locale.Category.DISPLAY)); 378 } 379 380 /** 381 * Returns the {@link #SHORT short} or {@link #LONG long} name of this time 382 * zone with either standard or daylight time, as written in {@code locale}. 383 * If the name is not available, the result is in the format 384 * {@code GMT[+-]hh:mm}. 385 * 386 * @param daylightTime true for daylight time, false for standard time. 387 * @param style either {@link TimeZone#LONG} or {@link TimeZone#SHORT}. 388 * @param locale the display locale. 389 */ getDisplayName(boolean daylightTime, int style, Locale locale)390 public String getDisplayName(boolean daylightTime, int style, Locale locale) { 391 // BEGIN Android-changed: implement using android.icu.text.TimeZoneNames 392 TimeZoneNames.NameType nameType; 393 switch (style) { 394 case SHORT: 395 nameType = daylightTime 396 ? TimeZoneNames.NameType.SHORT_DAYLIGHT 397 : TimeZoneNames.NameType.SHORT_STANDARD; 398 break; 399 case LONG: 400 nameType = daylightTime 401 ? TimeZoneNames.NameType.LONG_DAYLIGHT 402 : TimeZoneNames.NameType.LONG_STANDARD; 403 break; 404 default: 405 throw new IllegalArgumentException("Illegal style: " + style); 406 } 407 String canonicalID = android.icu.util.TimeZone.getCanonicalID(getID()); 408 if (canonicalID != null) { 409 TimeZoneNames names = TimeZoneNames.getInstance(locale); 410 long now = System.currentTimeMillis(); 411 String displayName = names.getDisplayName(canonicalID, nameType, now); 412 if (displayName != null) { 413 return displayName; 414 } 415 } 416 417 // We get here if this is a custom timezone or ICU doesn't have name data for the specific 418 // style and locale. 419 int offsetMillis = getRawOffset(); 420 if (daylightTime) { 421 offsetMillis += getDSTSavings(); 422 } 423 return createGmtOffsetString(true /* includeGmt */, true /* includeMinuteSeparator */, 424 offsetMillis); 425 // END Android-changed: implement using android.icu.text.TimeZoneNames 426 } 427 428 // BEGIN Android-added: utility method to format an offset as a GMT offset string. 429 /** 430 * Returns a string representation of an offset from UTC. 431 * 432 * <p>The format is "[GMT](+|-)HH[:]MM". The output is not localized. 433 * 434 * @param includeGmt true to include "GMT", false to exclude 435 * @param includeMinuteSeparator true to include the separator between hours and minutes, false 436 * to exclude. 437 * @param offsetMillis the offset from UTC 438 * 439 * @hide used internally by SimpleDateFormat 440 */ createGmtOffsetString(boolean includeGmt, boolean includeMinuteSeparator, int offsetMillis)441 public static String createGmtOffsetString(boolean includeGmt, 442 boolean includeMinuteSeparator, int offsetMillis) { 443 int offsetMinutes = offsetMillis / 60000; 444 char sign = '+'; 445 if (offsetMinutes < 0) { 446 sign = '-'; 447 offsetMinutes = -offsetMinutes; 448 } 449 StringBuilder builder = new StringBuilder(9); 450 if (includeGmt) { 451 builder.append("GMT"); 452 } 453 builder.append(sign); 454 appendNumber(builder, 2, offsetMinutes / 60); 455 if (includeMinuteSeparator) { 456 builder.append(':'); 457 } 458 appendNumber(builder, 2, offsetMinutes % 60); 459 return builder.toString(); 460 } 461 appendNumber(StringBuilder builder, int count, int value)462 private static void appendNumber(StringBuilder builder, int count, int value) { 463 String string = Integer.toString(value); 464 for (int i = 0; i < count - string.length(); i++) { 465 builder.append('0'); 466 } 467 builder.append(string); 468 } 469 // END Android-added: utility method to format an offset as a GMT offset string. 470 471 /** 472 * Returns the amount of time to be added to local standard time 473 * to get local wall clock time. 474 * 475 * <p>The default implementation returns 3600000 milliseconds 476 * (i.e., one hour) if a call to {@link #useDaylightTime()} 477 * returns {@code true}. Otherwise, 0 (zero) is returned. 478 * 479 * <p>If an underlying {@code TimeZone} implementation subclass 480 * supports historical and future Daylight Saving Time schedule 481 * changes, this method returns the amount of saving time of the 482 * last known Daylight Saving Time rule that can be a future 483 * prediction. 484 * 485 * <p>If the amount of saving time at any given time stamp is 486 * required, construct a {@link Calendar} with this {@code 487 * TimeZone} and the time stamp, and call {@link Calendar#get(int) 488 * Calendar.get}{@code (}{@link Calendar#DST_OFFSET}{@code )}. 489 * 490 * @return the amount of saving time in milliseconds 491 * @since 1.4 492 * @see #inDaylightTime(Date) 493 * @see #getOffset(long) 494 * @see #getOffset(int,int,int,int,int,int) 495 * @see Calendar#ZONE_OFFSET 496 */ getDSTSavings()497 public int getDSTSavings() { 498 if (useDaylightTime()) { 499 return 3600000; 500 } 501 return 0; 502 } 503 504 /** 505 * Queries if this {@code TimeZone} uses Daylight Saving Time. 506 * 507 * <p>If an underlying {@code TimeZone} implementation subclass 508 * supports historical and future Daylight Saving Time schedule 509 * changes, this method refers to the last known Daylight Saving Time 510 * rule that can be a future prediction and may not be the same as 511 * the current rule. Consider calling {@link #observesDaylightTime()} 512 * if the current rule should also be taken into account. 513 * 514 * @return {@code true} if this {@code TimeZone} uses Daylight Saving Time, 515 * {@code false}, otherwise. 516 * @see #inDaylightTime(Date) 517 * @see Calendar#DST_OFFSET 518 */ useDaylightTime()519 public abstract boolean useDaylightTime(); 520 521 /** 522 * Returns {@code true} if this {@code TimeZone} is currently in 523 * Daylight Saving Time, or if a transition from Standard Time to 524 * Daylight Saving Time occurs at any future time. 525 * 526 * <p>The default implementation returns {@code true} if 527 * {@code useDaylightTime()} or {@code inDaylightTime(new Date())} 528 * returns {@code true}. 529 * 530 * @return {@code true} if this {@code TimeZone} is currently in 531 * Daylight Saving Time, or if a transition from Standard Time to 532 * Daylight Saving Time occurs at any future time; {@code false} 533 * otherwise. 534 * @since 1.7 535 * @see #useDaylightTime() 536 * @see #inDaylightTime(Date) 537 * @see Calendar#DST_OFFSET 538 */ observesDaylightTime()539 public boolean observesDaylightTime() { 540 return useDaylightTime() || inDaylightTime(new Date()); 541 } 542 543 /** 544 * Queries if the given {@code date} is in Daylight Saving Time in 545 * this time zone. 546 * 547 * @param date the given Date. 548 * @return {@code true} if the given date is in Daylight Saving Time, 549 * {@code false}, otherwise. 550 */ inDaylightTime(Date date)551 abstract public boolean inDaylightTime(Date date); 552 553 /** 554 * Gets the <code>TimeZone</code> for the given ID. 555 * 556 * @param id the ID for a <code>TimeZone</code>, either an abbreviation 557 * such as "PST", a full name such as "America/Los_Angeles", or a custom 558 * ID such as "GMT-8:00". Note that the support of abbreviations is 559 * for JDK 1.1.x compatibility only and full names should be used. 560 * 561 * @return the specified <code>TimeZone</code>, or the GMT zone if the given ID 562 * cannot be understood. 563 */ 564 // Android-changed: param s/ID/id; use ZoneInfoDb instead of ZoneInfo class. getTimeZone(String id)565 public static synchronized TimeZone getTimeZone(String id) { 566 if (id == null) { 567 throw new NullPointerException("id == null"); 568 } 569 570 // Special cases? These can clone an existing instance. 571 if (id.length() == 3) { 572 if (id.equals("GMT")) { 573 return (TimeZone) GMT.clone(); 574 } 575 if (id.equals("UTC")) { 576 return (TimeZone) UTC.clone(); 577 } 578 } 579 580 // In the database? 581 582 ZoneInfoData zoneInfoData = ZoneInfoDb.getInstance().makeZoneInfoData(id); 583 TimeZone zone = zoneInfoData == null ? null : ZoneInfo.createZoneInfo(zoneInfoData); 584 585 // Custom time zone? 586 if (zone == null && id.length() > 3 && id.startsWith("GMT")) { 587 zone = getCustomTimeZone(id); 588 } 589 590 // We never return null; on failure we return the equivalent of "GMT". 591 return (zone != null) ? zone : (TimeZone) GMT.clone(); 592 } 593 594 /** 595 * Gets the {@code TimeZone} for the given {@code zoneId}. 596 * 597 * @param zoneId a {@link ZoneId} from which the time zone ID is obtained 598 * @return the specified {@code TimeZone}, or the GMT zone if the given ID 599 * cannot be understood. 600 * @throws NullPointerException if {@code zoneId} is {@code null} 601 * @since 1.8 602 */ getTimeZone(ZoneId zoneId)603 public static TimeZone getTimeZone(ZoneId zoneId) { 604 String tzid = zoneId.getId(); // throws an NPE if null 605 char c = tzid.charAt(0); 606 if (c == '+' || c == '-') { 607 tzid = "GMT" + tzid; 608 } else if (c == 'Z' && tzid.length() == 1) { 609 tzid = "UTC"; 610 } 611 return getTimeZone(tzid); 612 } 613 614 /** 615 * Converts this {@code TimeZone} object to a {@code ZoneId}. 616 * 617 * @return a {@code ZoneId} representing the same time zone as this 618 * {@code TimeZone} 619 * @since 1.8 620 */ toZoneId()621 public ZoneId toZoneId() { 622 // Android-changed: don't support "old mapping" 623 return ZoneId.of(getID(), ZoneId.SHORT_IDS); 624 } 625 626 /** 627 * Returns a new SimpleTimeZone for an ID of the form "GMT[+|-]hh[[:]mm]", or null. 628 */ getCustomTimeZone(String id)629 private static TimeZone getCustomTimeZone(String id) { 630 Matcher m = NoImagePreloadHolder.CUSTOM_ZONE_ID_PATTERN.matcher(id); 631 if (!m.matches()) { 632 return null; 633 } 634 635 int hour; 636 int minute = 0; 637 try { 638 hour = Integer.parseInt(m.group(1)); 639 if (m.group(3) != null) { 640 minute = Integer.parseInt(m.group(3)); 641 } 642 } catch (NumberFormatException impossible) { 643 throw new AssertionError(impossible); 644 } 645 646 if (hour < 0 || hour > 23 || minute < 0 || minute > 59) { 647 return null; 648 } 649 650 char sign = id.charAt(3); 651 int raw = (hour * 3600000) + (minute * 60000); 652 if (sign == '-') { 653 raw = -raw; 654 } 655 656 String cleanId = String.format(Locale.ROOT, "GMT%c%02d:%02d", sign, hour, minute); 657 658 return new SimpleTimeZone(raw, cleanId); 659 } 660 661 /** 662 * Gets the available IDs according to the given time zone offset in milliseconds. 663 * 664 * @param rawOffset the given time zone GMT offset in milliseconds. 665 * @return an array of IDs, where the time zone for that ID has 666 * the specified GMT offset. For example, "America/Phoenix" and "America/Denver" 667 * both have GMT-07:00, but differ in daylight saving behavior. 668 * @see #getRawOffset() 669 */ getAvailableIDs(int rawOffset)670 public static synchronized String[] getAvailableIDs(int rawOffset) { 671 return ZoneInfoDb.getInstance().getAvailableIDs(rawOffset); 672 } 673 674 /** 675 * Gets all the available IDs supported. 676 * @return an array of IDs. 677 */ getAvailableIDs()678 public static synchronized String[] getAvailableIDs() { 679 return ZoneInfoDb.getInstance().getAvailableIDs(); 680 } 681 682 /** 683 * Gets the platform defined TimeZone ID. 684 **/ getSystemTimeZoneID(String javaHome, String country)685 private static native String getSystemTimeZoneID(String javaHome, 686 String country); 687 688 /** 689 * Gets the custom time zone ID based on the GMT offset of the 690 * platform. (e.g., "GMT+08:00") 691 */ getSystemGMTOffsetID()692 private static native String getSystemGMTOffsetID(); 693 694 /** 695 * Gets the default <code>TimeZone</code> for this host. 696 * The source of the default <code>TimeZone</code> 697 * may vary with implementation. 698 * @return a default <code>TimeZone</code>. 699 * @see #setDefault 700 */ getDefault()701 public static TimeZone getDefault() { 702 return (TimeZone) getDefaultRef().clone(); 703 } 704 705 /** 706 * Returns the reference to the default TimeZone object. This 707 * method doesn't create a clone. 708 */ getDefaultRef()709 static synchronized TimeZone getDefaultRef() { 710 if (defaultTimeZone == null) { 711 Supplier<String> tzGetter = RuntimeHooks.getTimeZoneIdSupplier(); 712 String zoneName = (tzGetter != null) ? tzGetter.get() : null; 713 if (zoneName != null) { 714 zoneName = zoneName.trim(); 715 } 716 if (zoneName == null || zoneName.isEmpty()) { 717 try { 718 // On the host, we can find the configured timezone here. 719 zoneName = IoUtils.readFileAsString("/etc/timezone"); 720 } catch (IOException ex) { 721 // "vogar --mode device" can end up here. 722 // TODO: give libcore access to Android system properties and read "persist.sys.timezone". 723 zoneName = "GMT"; 724 } 725 } 726 defaultTimeZone = TimeZone.getTimeZone(zoneName); 727 } 728 return defaultTimeZone; 729 } 730 731 /** 732 * Sets the {@code TimeZone} that is returned by the {@code getDefault} 733 * method. {@code timeZone} is cached. If {@code timeZone} is null, the cached 734 * default {@code TimeZone} is cleared. This method doesn't change the value 735 * of the {@code user.timezone} property. 736 * 737 * @param timeZone the new default {@code TimeZone}, or null 738 * @see #getDefault 739 */ 740 // Android-changed: s/zone/timeZone, synchronized, removed mention of SecurityException setDefault(TimeZone timeZone)741 public synchronized static void setDefault(TimeZone timeZone) 742 { 743 SecurityManager sm = System.getSecurityManager(); 744 if (sm != null) { 745 sm.checkPermission(new PropertyPermission 746 ("user.timezone", "write")); 747 } 748 defaultTimeZone = timeZone != null ? (TimeZone) timeZone.clone() : null; 749 // Android-changed: notify ICU4J of changed default TimeZone. 750 ExtendedTimeZone.clearDefaultTimeZone(); 751 } 752 753 /** 754 * Returns true if this zone has the same rule and offset as another zone. 755 * That is, if this zone differs only in ID, if at all. Returns false 756 * if the other zone is null. 757 * @param other the <code>TimeZone</code> object to be compared with 758 * @return true if the other zone is not null and is the same as this one, 759 * with the possible exception of the ID 760 * @since 1.2 761 */ hasSameRules(TimeZone other)762 public boolean hasSameRules(TimeZone other) { 763 return other != null && getRawOffset() == other.getRawOffset() && 764 useDaylightTime() == other.useDaylightTime(); 765 } 766 767 /** 768 * Creates a copy of this <code>TimeZone</code>. 769 * 770 * @return a clone of this <code>TimeZone</code> 771 */ clone()772 public Object clone() 773 { 774 try { 775 TimeZone other = (TimeZone) super.clone(); 776 other.ID = ID; 777 return other; 778 } catch (CloneNotSupportedException e) { 779 throw new InternalError(e); 780 } 781 } 782 783 /** 784 * The null constant as a TimeZone. 785 */ 786 static final TimeZone NO_TIMEZONE = null; 787 788 // =======================privates=============================== 789 790 /** 791 * The string identifier of this <code>TimeZone</code>. This is a 792 * programmatic identifier used internally to look up <code>TimeZone</code> 793 * objects from the system table and also to map them to their localized 794 * display names. <code>ID</code> values are unique in the system 795 * table but may not be for dynamically created zones. 796 * @serial 797 */ 798 private String ID; 799 private static volatile TimeZone defaultTimeZone; 800 } 801