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