1 /* 2 * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 /* 27 * (C) Copyright Taligent, Inc. 1996 - All Rights Reserved 28 * (C) Copyright IBM Corp. 1996 - All Rights Reserved 29 * 30 * The original version of this source code and documentation is copyrighted 31 * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These 32 * materials are provided under terms of a License Agreement between Taligent 33 * and Sun. This technology is protected by multiple US and International 34 * patents. This notice and attribution to Taligent may not be removed. 35 * Taligent is a registered trademark of Taligent, Inc. 36 * 37 */ 38 39 package java.util; 40 41 import java.io.Serializable; 42 import java.lang.ref.SoftReference; 43 import java.security.AccessController; 44 import java.security.PrivilegedAction; 45 import java.time.ZoneId; 46 import java.util.concurrent.ConcurrentHashMap; 47 import sun.misc.JavaAWTAccess; 48 import sun.misc.SharedSecrets; 49 import sun.security.action.GetPropertyAction; 50 import sun.util.calendar.ZoneInfo; 51 import sun.util.calendar.ZoneInfoFile; 52 import sun.util.locale.provider.TimeZoneNameUtility; 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 * <h4>Three-letter time zone IDs</h4> 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 */ 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 // Constants used internally; unit is milliseconds 162 private static final int ONE_MINUTE = 60*1000; 163 private static final int ONE_HOUR = 60*ONE_MINUTE; 164 private static final int ONE_DAY = 24*ONE_HOUR; 165 166 // Proclaim serialization compatibility with JDK 1.1 167 static final long serialVersionUID = 3581463369166924961L; 168 169 /** 170 * Gets the time zone offset, for current date, modified in case of 171 * daylight savings. This is the offset to add to UTC to get local time. 172 * <p> 173 * This method returns a historically correct offset if an 174 * underlying <code>TimeZone</code> implementation subclass 175 * supports historical Daylight Saving Time schedule and GMT 176 * offset changes. 177 * 178 * @param era the era of the given date. 179 * @param year the year in the given date. 180 * @param month the month in the given date. 181 * Month is 0-based. e.g., 0 for January. 182 * @param day the day-in-month of the given date. 183 * @param dayOfWeek the day-of-week of the given date. 184 * @param milliseconds the milliseconds in day in <em>standard</em> 185 * local time. 186 * 187 * @return the offset in milliseconds to add to GMT to get local time. 188 * 189 * @see Calendar#ZONE_OFFSET 190 * @see Calendar#DST_OFFSET 191 */ 192 public abstract int getOffset(int era, int year, int month, int day, 193 int dayOfWeek, int milliseconds); 194 195 /** 196 * Returns the offset of this time zone from UTC at the specified 197 * date. If Daylight Saving Time is in effect at the specified 198 * date, the offset value is adjusted with the amount of daylight 199 * saving. 200 * <p> 201 * This method returns a historically correct offset value if an 202 * underlying TimeZone implementation subclass supports historical 203 * Daylight Saving Time schedule and GMT offset changes. 204 * 205 * @param date the date represented in milliseconds since January 1, 1970 00:00:00 GMT 206 * @return the amount of time in milliseconds to add to UTC to get local time. 207 * 208 * @see Calendar#ZONE_OFFSET 209 * @see Calendar#DST_OFFSET 210 * @since 1.4 211 */ 212 public int getOffset(long date) { 213 if (inDaylightTime(new Date(date))) { 214 return getRawOffset() + getDSTSavings(); 215 } 216 return getRawOffset(); 217 } 218 219 /** 220 * Gets the raw GMT offset and the amount of daylight saving of this 221 * time zone at the given time. 222 * @param date the milliseconds (since January 1, 1970, 223 * 00:00:00.000 GMT) at which the time zone offset and daylight 224 * saving amount are found 225 * @param offsets an array of int where the raw GMT offset 226 * (offset[0]) and daylight saving amount (offset[1]) are stored, 227 * or null if those values are not needed. The method assumes that 228 * the length of the given array is two or larger. 229 * @return the total amount of the raw GMT offset and daylight 230 * saving at the specified date. 231 * 232 * @see Calendar#ZONE_OFFSET 233 * @see Calendar#DST_OFFSET 234 */ 235 int getOffsets(long date, int[] offsets) { 236 int rawoffset = getRawOffset(); 237 int dstoffset = 0; 238 if (inDaylightTime(new Date(date))) { 239 dstoffset = getDSTSavings(); 240 } 241 if (offsets != null) { 242 offsets[0] = rawoffset; 243 offsets[1] = dstoffset; 244 } 245 return rawoffset + dstoffset; 246 } 247 248 /** 249 * Sets the base time zone offset to GMT. 250 * This is the offset to add to UTC to get local time. 251 * <p> 252 * If an underlying <code>TimeZone</code> implementation subclass 253 * supports historical GMT offset changes, the specified GMT 254 * offset is set as the latest GMT offset and the difference from 255 * the known latest GMT offset value is used to adjust all 256 * historical GMT offset values. 257 * 258 * @param offsetMillis the given base time zone offset to GMT. 259 */ 260 abstract public void setRawOffset(int offsetMillis); 261 262 /** 263 * Returns the amount of time in milliseconds to add to UTC to get 264 * standard time in this time zone. Because this value is not 265 * affected by daylight saving time, it is called <I>raw 266 * offset</I>. 267 * <p> 268 * If an underlying <code>TimeZone</code> implementation subclass 269 * supports historical GMT offset changes, the method returns the 270 * raw offset value of the current date. In Honolulu, for example, 271 * its raw offset changed from GMT-10:30 to GMT-10:00 in 1947, and 272 * this method always returns -36000000 milliseconds (i.e., -10 273 * hours). 274 * 275 * @return the amount of raw offset time in milliseconds to add to UTC. 276 * @see Calendar#ZONE_OFFSET 277 */ 278 public abstract int getRawOffset(); 279 280 /** 281 * Gets the ID of this time zone. 282 * @return the ID of this time zone. 283 */ 284 public String getID() 285 { 286 return ID; 287 } 288 289 /** 290 * Sets the time zone ID. This does not change any other data in 291 * the time zone object. 292 * @param ID the new time zone ID. 293 */ 294 public void setID(String ID) 295 { 296 if (ID == null) { 297 throw new NullPointerException(); 298 } 299 this.ID = ID; 300 } 301 302 /** 303 * Returns a long standard time name of this {@code TimeZone} suitable for 304 * presentation to the user in the default locale. 305 * 306 * <p>This method is equivalent to: 307 * <pre><blockquote> 308 * getDisplayName(false, {@link #LONG}, 309 * Locale.getDefault({@link Locale.Category#DISPLAY})) 310 * </blockquote></pre> 311 * 312 * @return the human-readable name of this time zone in the default locale. 313 * @since 1.2 314 * @see #getDisplayName(boolean, int, Locale) 315 * @see Locale#getDefault(Locale.Category) 316 * @see Locale.Category 317 */ 318 public final String getDisplayName() { 319 return getDisplayName(false, LONG, 320 Locale.getDefault(Locale.Category.DISPLAY)); 321 } 322 323 /** 324 * Returns a long standard time name of this {@code TimeZone} suitable for 325 * presentation to the user in the specified {@code locale}. 326 * 327 * <p>This method is equivalent to: 328 * <pre><blockquote> 329 * getDisplayName(false, {@link #LONG}, locale) 330 * </blockquote></pre> 331 * 332 * @param locale the locale in which to supply the display name. 333 * @return the human-readable name of this time zone in the given locale. 334 * @exception NullPointerException if {@code locale} is {@code null}. 335 * @since 1.2 336 * @see #getDisplayName(boolean, int, Locale) 337 */ 338 public final String getDisplayName(Locale locale) { 339 return getDisplayName(false, LONG, locale); 340 } 341 342 /** 343 * Returns a name in the specified {@code style} of this {@code TimeZone} 344 * suitable for presentation to the user in the default locale. If the 345 * specified {@code daylight} is {@code true}, a Daylight Saving Time name 346 * is returned (even if this {@code TimeZone} doesn't observe Daylight Saving 347 * Time). Otherwise, a Standard Time name is returned. 348 * 349 * <p>This method is equivalent to: 350 * <pre><blockquote> 351 * getDisplayName(daylight, style, 352 * Locale.getDefault({@link Locale.Category#DISPLAY})) 353 * </blockquote></pre> 354 * 355 * @param daylight {@code true} specifying a Daylight Saving Time name, or 356 * {@code false} specifying a Standard Time name 357 * @param style either {@link #LONG} or {@link #SHORT} 358 * @return the human-readable name of this time zone in the default locale. 359 * @exception IllegalArgumentException if {@code style} is invalid. 360 * @since 1.2 361 * @see #getDisplayName(boolean, int, Locale) 362 * @see Locale#getDefault(Locale.Category) 363 * @see Locale.Category 364 * @see java.text.DateFormatSymbols#getZoneStrings() 365 */ 366 public final String getDisplayName(boolean daylight, int style) { 367 return getDisplayName(daylight, style, 368 Locale.getDefault(Locale.Category.DISPLAY)); 369 } 370 371 /** 372 * Returns a name in the specified {@code style} of this {@code TimeZone} 373 * suitable for presentation to the user in the specified {@code 374 * locale}. If the specified {@code daylight} is {@code true}, a Daylight 375 * Saving Time name is returned (even if this {@code TimeZone} doesn't 376 * observe Daylight Saving Time). Otherwise, a Standard Time name is 377 * returned. 378 * 379 * <p>When looking up a time zone name, the {@linkplain 380 * ResourceBundle.Control#getCandidateLocales(String,Locale) default 381 * <code>Locale</code> search path of <code>ResourceBundle</code>} derived 382 * from the specified {@code locale} is used. (No {@linkplain 383 * ResourceBundle.Control#getFallbackLocale(String,Locale) fallback 384 * <code>Locale</code>} search is performed.) If a time zone name in any 385 * {@code Locale} of the search path, including {@link Locale#ROOT}, is 386 * found, the name is returned. Otherwise, a string in the 387 * <a href="#NormalizedCustomID">normalized custom ID format</a> is returned. 388 * 389 * @param daylight {@code true} specifying a Daylight Saving Time name, or 390 * {@code false} specifying a Standard Time name 391 * @param style either {@link #LONG} or {@link #SHORT} 392 * @param locale the locale in which to supply the display name. 393 * @return the human-readable name of this time zone in the given locale. 394 * @exception IllegalArgumentException if {@code style} is invalid. 395 * @exception NullPointerException if {@code locale} is {@code null}. 396 * @since 1.2 397 * @see java.text.DateFormatSymbols#getZoneStrings() 398 */ 399 public String getDisplayName(boolean daylight, int style, Locale locale) { 400 if (style != SHORT && style != LONG) { 401 throw new IllegalArgumentException("Illegal style: " + style); 402 } 403 String id = getID(); 404 String name = TimeZoneNameUtility.retrieveDisplayName(id, daylight, style, locale); 405 if (name != null) { 406 return name; 407 } 408 409 if (id.startsWith("GMT") && id.length() > 3) { 410 char sign = id.charAt(3); 411 if (sign == '+' || sign == '-') { 412 return id; 413 } 414 } 415 int offset = getRawOffset(); 416 if (daylight) { 417 offset += getDSTSavings(); 418 } 419 return ZoneInfoFile.toCustomID(offset); 420 } 421 422 private static String[] getDisplayNames(String id, Locale locale) { 423 return TimeZoneNameUtility.retrieveDisplayNames(id, locale); 424 } 425 426 /** 427 * Returns the amount of time to be added to local standard time 428 * to get local wall clock time. 429 * 430 * <p>The default implementation returns 3600000 milliseconds 431 * (i.e., one hour) if a call to {@link #useDaylightTime()} 432 * returns {@code true}. Otherwise, 0 (zero) is returned. 433 * 434 * <p>If an underlying {@code TimeZone} implementation subclass 435 * supports historical and future Daylight Saving Time schedule 436 * changes, this method returns the amount of saving time of the 437 * last known Daylight Saving Time rule that can be a future 438 * prediction. 439 * 440 * <p>If the amount of saving time at any given time stamp is 441 * required, construct a {@link Calendar} with this {@code 442 * TimeZone} and the time stamp, and call {@link Calendar#get(int) 443 * Calendar.get}{@code (}{@link Calendar#DST_OFFSET}{@code )}. 444 * 445 * @return the amount of saving time in milliseconds 446 * @since 1.4 447 * @see #inDaylightTime(Date) 448 * @see #getOffset(long) 449 * @see #getOffset(int,int,int,int,int,int) 450 * @see Calendar#ZONE_OFFSET 451 */ 452 public int getDSTSavings() { 453 if (useDaylightTime()) { 454 return 3600000; 455 } 456 return 0; 457 } 458 459 /** 460 * Queries if this {@code TimeZone} uses Daylight Saving Time. 461 * 462 * <p>If an underlying {@code TimeZone} implementation subclass 463 * supports historical and future Daylight Saving Time schedule 464 * changes, this method refers to the last known Daylight Saving Time 465 * rule that can be a future prediction and may not be the same as 466 * the current rule. Consider calling {@link #observesDaylightTime()} 467 * if the current rule should also be taken into account. 468 * 469 * @return {@code true} if this {@code TimeZone} uses Daylight Saving Time, 470 * {@code false}, otherwise. 471 * @see #inDaylightTime(Date) 472 * @see Calendar#DST_OFFSET 473 */ 474 public abstract boolean useDaylightTime(); 475 476 /** 477 * Returns {@code true} if this {@code TimeZone} is currently in 478 * Daylight Saving Time, or if a transition from Standard Time to 479 * Daylight Saving Time occurs at any future time. 480 * 481 * <p>The default implementation returns {@code true} if 482 * {@code useDaylightTime()} or {@code inDaylightTime(new Date())} 483 * returns {@code true}. 484 * 485 * @return {@code true} if this {@code TimeZone} is currently in 486 * Daylight Saving Time, or if a transition from Standard Time to 487 * Daylight Saving Time occurs at any future time; {@code false} 488 * otherwise. 489 * @since 1.7 490 * @see #useDaylightTime() 491 * @see #inDaylightTime(Date) 492 * @see Calendar#DST_OFFSET 493 */ 494 public boolean observesDaylightTime() { 495 return useDaylightTime() || inDaylightTime(new Date()); 496 } 497 498 /** 499 * Queries if the given {@code date} is in Daylight Saving Time in 500 * this time zone. 501 * 502 * @param date the given Date. 503 * @return {@code true} if the given date is in Daylight Saving Time, 504 * {@code false}, otherwise. 505 */ 506 abstract public boolean inDaylightTime(Date date); 507 508 /** 509 * Gets the <code>TimeZone</code> for the given ID. 510 * 511 * @param ID the ID for a <code>TimeZone</code>, either an abbreviation 512 * such as "PST", a full name such as "America/Los_Angeles", or a custom 513 * ID such as "GMT-8:00". Note that the support of abbreviations is 514 * for JDK 1.1.x compatibility only and full names should be used. 515 * 516 * @return the specified <code>TimeZone</code>, or the GMT zone if the given ID 517 * cannot be understood. 518 */ 519 public static synchronized TimeZone getTimeZone(String ID) { 520 return getTimeZone(ID, true); 521 } 522 523 /** 524 * Gets the {@code TimeZone} for the given {@code zoneId}. 525 * 526 * @param zoneId a {@link ZoneId} from which the time zone ID is obtained 527 * @return the specified {@code TimeZone}, or the GMT zone if the given ID 528 * cannot be understood. 529 * @throws NullPointerException if {@code zoneId} is {@code null} 530 * @since 1.8 531 */ 532 public static TimeZone getTimeZone(ZoneId zoneId) { 533 String tzid = zoneId.getId(); // throws an NPE if null 534 char c = tzid.charAt(0); 535 if (c == '+' || c == '-') { 536 tzid = "GMT" + tzid; 537 } else if (c == 'Z' && tzid.length() == 1) { 538 tzid = "UTC"; 539 } 540 return getTimeZone(tzid, true); 541 } 542 543 /** 544 * Converts this {@code TimeZone} object to a {@code ZoneId}. 545 * 546 * @return a {@code ZoneId} representing the same time zone as this 547 * {@code TimeZone} 548 * @since 1.8 549 */ 550 public ZoneId toZoneId() { 551 return ZoneId.of(getID(), ZoneId.SHORT_IDS); 552 } 553 554 private static TimeZone getTimeZone(String ID, boolean fallback) { 555 TimeZone tz = ZoneInfo.getTimeZone(ID); 556 if (tz == null) { 557 tz = parseCustomTimeZone(ID); 558 if (tz == null && fallback) { 559 tz = new ZoneInfo(GMT_ID, 0); 560 } 561 } 562 return tz; 563 } 564 565 /** 566 * Gets the available IDs according to the given time zone offset in milliseconds. 567 * 568 * @param rawOffset the given time zone GMT offset in milliseconds. 569 * @return an array of IDs, where the time zone for that ID has 570 * the specified GMT offset. For example, "America/Phoenix" and "America/Denver" 571 * both have GMT-07:00, but differ in daylight saving behavior. 572 * @see #getRawOffset() 573 */ 574 public static synchronized String[] getAvailableIDs(int rawOffset) { 575 return ZoneInfo.getAvailableIDs(rawOffset); 576 } 577 578 /** 579 * Gets all the available IDs supported. 580 * @return an array of IDs. 581 */ 582 public static synchronized String[] getAvailableIDs() { 583 return ZoneInfo.getAvailableIDs(); 584 } 585 586 /** 587 * Gets the platform defined TimeZone ID. 588 **/ 589 private static native String getSystemTimeZoneID(String javaHome, 590 String country); 591 592 /** 593 * Gets the custom time zone ID based on the GMT offset of the 594 * platform. (e.g., "GMT+08:00") 595 */ 596 private static native String getSystemGMTOffsetID(); 597 598 /** 599 * Gets the default <code>TimeZone</code> for this host. 600 * The source of the default <code>TimeZone</code> 601 * may vary with implementation. 602 * @return a default <code>TimeZone</code>. 603 * @see #setDefault 604 */ 605 public static TimeZone getDefault() { 606 return (TimeZone) getDefaultRef().clone(); 607 } 608 609 /** 610 * Returns the reference to the default TimeZone object. This 611 * method doesn't create a clone. 612 */ 613 static TimeZone getDefaultRef() { 614 TimeZone defaultZone = getDefaultInAppContext(); 615 if (defaultZone == null) { 616 defaultZone = defaultTimeZone; 617 if (defaultZone == null) { 618 // Need to initialize the default time zone. 619 defaultZone = setDefaultZone(); 620 assert defaultZone != null; 621 } 622 } 623 // Don't clone here. 624 return defaultZone; 625 } 626 627 private static synchronized TimeZone setDefaultZone() { 628 TimeZone tz; 629 // get the time zone ID from the system properties 630 String zoneID = AccessController.doPrivileged( 631 new GetPropertyAction("user.timezone")); 632 633 // if the time zone ID is not set (yet), perform the 634 // platform to Java time zone ID mapping. 635 if (zoneID == null || zoneID.isEmpty()) { 636 String country = AccessController.doPrivileged( 637 new GetPropertyAction("user.country")); 638 String javaHome = AccessController.doPrivileged( 639 new GetPropertyAction("java.home")); 640 try { 641 zoneID = getSystemTimeZoneID(javaHome, country); 642 if (zoneID == null) { 643 zoneID = GMT_ID; 644 } 645 } catch (NullPointerException e) { 646 zoneID = GMT_ID; 647 } 648 } 649 650 // Get the time zone for zoneID. But not fall back to 651 // "GMT" here. 652 tz = getTimeZone(zoneID, false); 653 654 if (tz == null) { 655 // If the given zone ID is unknown in Java, try to 656 // get the GMT-offset-based time zone ID, 657 // a.k.a. custom time zone ID (e.g., "GMT-08:00"). 658 String gmtOffsetID = getSystemGMTOffsetID(); 659 if (gmtOffsetID != null) { 660 zoneID = gmtOffsetID; 661 } 662 tz = getTimeZone(zoneID, true); 663 } 664 assert tz != null; 665 666 final String id = zoneID; 667 AccessController.doPrivileged(new PrivilegedAction<Void>() { 668 @Override 669 public Void run() { 670 System.setProperty("user.timezone", id); 671 return null; 672 } 673 }); 674 675 defaultTimeZone = tz; 676 return tz; 677 } 678 679 private static boolean hasPermission() { 680 boolean hasPermission = true; 681 SecurityManager sm = System.getSecurityManager(); 682 if (sm != null) { 683 try { 684 sm.checkPermission(new PropertyPermission 685 ("user.timezone", "write")); 686 } catch (SecurityException e) { 687 hasPermission = false; 688 } 689 } 690 return hasPermission; 691 } 692 693 /** 694 * Sets the <code>TimeZone</code> that is 695 * returned by the <code>getDefault</code> method. If <code>zone</code> 696 * is null, reset the default to the value it had originally when the 697 * VM first started. 698 * @param zone the new default time zone 699 * @see #getDefault 700 */ 701 public static void setDefault(TimeZone zone) 702 { 703 if (hasPermission()) { 704 synchronized (TimeZone.class) { 705 defaultTimeZone = zone; 706 setDefaultInAppContext(null); 707 } 708 } else { 709 setDefaultInAppContext(zone); 710 } 711 } 712 713 /** 714 * Returns the default TimeZone in an AppContext if any AppContext 715 * has ever used. null is returned if any AppContext hasn't been 716 * used or if the AppContext doesn't have the default TimeZone. 717 * 718 * Note that javaAWTAccess may be null if sun.awt.AppContext class hasn't 719 * been loaded. If so, it implies that AWTSecurityManager is not our 720 * SecurityManager and we can use a local static variable. 721 * This works around a build time issue. 722 */ 723 private static TimeZone getDefaultInAppContext() { 724 // JavaAWTAccess provides access implementation-private methods without using reflection. 725 JavaAWTAccess javaAWTAccess = SharedSecrets.getJavaAWTAccess(); 726 727 if (javaAWTAccess == null) { 728 return mainAppContextDefault; 729 } else { 730 if (!javaAWTAccess.isDisposed()) { 731 TimeZone tz = (TimeZone) 732 javaAWTAccess.get(TimeZone.class); 733 if (tz == null && javaAWTAccess.isMainAppContext()) { 734 return mainAppContextDefault; 735 } else { 736 return tz; 737 } 738 } 739 } 740 return null; 741 } 742 743 /** 744 * Sets the default TimeZone in the AppContext to the given 745 * tz. null is handled special: do nothing if any AppContext 746 * hasn't been used, remove the default TimeZone in the 747 * AppContext otherwise. 748 * 749 * Note that javaAWTAccess may be null if sun.awt.AppContext class hasn't 750 * been loaded. If so, it implies that AWTSecurityManager is not our 751 * SecurityManager and we can use a local static variable. 752 * This works around a build time issue. 753 */ 754 private static void setDefaultInAppContext(TimeZone tz) { 755 // JavaAWTAccess provides access implementation-private methods without using reflection. 756 JavaAWTAccess javaAWTAccess = SharedSecrets.getJavaAWTAccess(); 757 758 if (javaAWTAccess == null) { 759 mainAppContextDefault = tz; 760 } else { 761 if (!javaAWTAccess.isDisposed()) { 762 javaAWTAccess.put(TimeZone.class, tz); 763 if (javaAWTAccess.isMainAppContext()) { 764 mainAppContextDefault = null; 765 } 766 } 767 } 768 } 769 770 /** 771 * Returns true if this zone has the same rule and offset as another zone. 772 * That is, if this zone differs only in ID, if at all. Returns false 773 * if the other zone is null. 774 * @param other the <code>TimeZone</code> object to be compared with 775 * @return true if the other zone is not null and is the same as this one, 776 * with the possible exception of the ID 777 * @since 1.2 778 */ 779 public boolean hasSameRules(TimeZone other) { 780 return other != null && getRawOffset() == other.getRawOffset() && 781 useDaylightTime() == other.useDaylightTime(); 782 } 783 784 /** 785 * Creates a copy of this <code>TimeZone</code>. 786 * 787 * @return a clone of this <code>TimeZone</code> 788 */ 789 public Object clone() 790 { 791 try { 792 TimeZone other = (TimeZone) super.clone(); 793 other.ID = ID; 794 return other; 795 } catch (CloneNotSupportedException e) { 796 throw new InternalError(e); 797 } 798 } 799 800 /** 801 * The null constant as a TimeZone. 802 */ 803 static final TimeZone NO_TIMEZONE = null; 804 805 // =======================privates=============================== 806 807 /** 808 * The string identifier of this <code>TimeZone</code>. This is a 809 * programmatic identifier used internally to look up <code>TimeZone</code> 810 * objects from the system table and also to map them to their localized 811 * display names. <code>ID</code> values are unique in the system 812 * table but may not be for dynamically created zones. 813 * @serial 814 */ 815 private String ID; 816 private static volatile TimeZone defaultTimeZone; 817 818 static final String GMT_ID = "GMT"; 819 private static final int GMT_ID_LENGTH = 3; 820 821 // a static TimeZone we can reference if no AppContext is in place 822 private static volatile TimeZone mainAppContextDefault; 823 824 /** 825 * Parses a custom time zone identifier and returns a corresponding zone. 826 * This method doesn't support the RFC 822 time zone format. (e.g., +hhmm) 827 * 828 * @param id a string of the <a href="#CustomID">custom ID form</a>. 829 * @return a newly created TimeZone with the given offset and 830 * no daylight saving time, or null if the id cannot be parsed. 831 */ 832 private static final TimeZone parseCustomTimeZone(String id) { 833 int length; 834 835 // Error if the length of id isn't long enough or id doesn't 836 // start with "GMT". 837 if ((length = id.length()) < (GMT_ID_LENGTH + 2) || 838 id.indexOf(GMT_ID) != 0) { 839 return null; 840 } 841 842 ZoneInfo zi; 843 844 // First, we try to find it in the cache with the given 845 // id. Even the id is not normalized, the returned ZoneInfo 846 // should have its normalized id. 847 zi = ZoneInfoFile.getZoneInfo(id); 848 if (zi != null) { 849 return zi; 850 } 851 852 int index = GMT_ID_LENGTH; 853 boolean negative = false; 854 char c = id.charAt(index++); 855 if (c == '-') { 856 negative = true; 857 } else if (c != '+') { 858 return null; 859 } 860 861 int hours = 0; 862 int num = 0; 863 int countDelim = 0; 864 int len = 0; 865 while (index < length) { 866 c = id.charAt(index++); 867 if (c == ':') { 868 if (countDelim > 0) { 869 return null; 870 } 871 if (len > 2) { 872 return null; 873 } 874 hours = num; 875 countDelim++; 876 num = 0; 877 len = 0; 878 continue; 879 } 880 if (c < '0' || c > '9') { 881 return null; 882 } 883 num = num * 10 + (c - '0'); 884 len++; 885 } 886 if (index != length) { 887 return null; 888 } 889 if (countDelim == 0) { 890 if (len <= 2) { 891 hours = num; 892 num = 0; 893 } else { 894 hours = num / 100; 895 num %= 100; 896 } 897 } else { 898 if (len != 2) { 899 return null; 900 } 901 } 902 if (hours > 23 || num > 59) { 903 return null; 904 } 905 int gmtOffset = (hours * 60 + num) * 60 * 1000; 906 907 if (gmtOffset == 0) { 908 zi = ZoneInfoFile.getZoneInfo(GMT_ID); 909 if (negative) { 910 zi.setID("GMT-00:00"); 911 } else { 912 zi.setID("GMT+00:00"); 913 } 914 } else { 915 zi = ZoneInfoFile.getCustomTimeZone(id, negative ? -gmtOffset : gmtOffset); 916 } 917 return zi; 918 } 919 }