1 /* 2 * Copyright (c) 2012, 2013, 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 * This file is available under and governed by the GNU General Public 28 * License version 2 only, as published by the Free Software Foundation. 29 * However, the following notice accompanied the original version of this 30 * file: 31 * 32 * Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos 33 * 34 * All rights reserved. 35 * 36 * Redistribution and use in source and binary forms, with or without 37 * modification, are permitted provided that the following conditions are met: 38 * 39 * * Redistributions of source code must retain the above copyright notice, 40 * this list of conditions and the following disclaimer. 41 * 42 * * Redistributions in binary form must reproduce the above copyright notice, 43 * this list of conditions and the following disclaimer in the documentation 44 * and/or other materials provided with the distribution. 45 * 46 * * Neither the name of JSR-310 nor the names of its contributors 47 * may be used to endorse or promote products derived from this software 48 * without specific prior written permission. 49 * 50 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 51 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 52 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 53 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 54 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 55 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 56 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 57 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 58 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 59 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 60 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 61 */ 62 package java.time; 63 64 import sun.misc.SharedSecrets; 65 66 import java.io.DataOutput; 67 import java.io.IOException; 68 import java.io.InvalidObjectException; 69 import java.io.ObjectInputStream; 70 import java.io.Serializable; 71 import java.time.format.DateTimeFormatterBuilder; 72 import java.time.format.TextStyle; 73 import java.time.temporal.TemporalAccessor; 74 import java.time.temporal.TemporalField; 75 import java.time.temporal.TemporalQueries; 76 import java.time.temporal.TemporalQuery; 77 import java.time.temporal.UnsupportedTemporalTypeException; 78 import java.time.zone.ZoneRules; 79 import java.time.zone.ZoneRulesException; 80 import java.time.zone.ZoneRulesProvider; 81 import java.util.Collections; 82 import java.util.HashMap; 83 import java.util.Locale; 84 import java.util.Map; 85 import java.util.Objects; 86 import java.util.Set; 87 import java.util.TimeZone; 88 89 /** 90 * A time-zone ID, such as {@code Europe/Paris}. 91 * <p> 92 * A {@code ZoneId} is used to identify the rules used to convert between 93 * an {@link Instant} and a {@link LocalDateTime}. 94 * There are two distinct types of ID: 95 * <ul> 96 * <li>Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses 97 * the same offset for all local date-times 98 * <li>Geographical regions - an area where a specific set of rules for finding 99 * the offset from UTC/Greenwich apply 100 * </ul> 101 * Most fixed offsets are represented by {@link ZoneOffset}. 102 * Calling {@link #normalized()} on any {@code ZoneId} will ensure that a 103 * fixed offset ID will be represented as a {@code ZoneOffset}. 104 * <p> 105 * The actual rules, describing when and how the offset changes, are defined by {@link ZoneRules}. 106 * This class is simply an ID used to obtain the underlying rules. 107 * This approach is taken because rules are defined by governments and change 108 * frequently, whereas the ID is stable. 109 * <p> 110 * The distinction has other effects. Serializing the {@code ZoneId} will only send 111 * the ID, whereas serializing the rules sends the entire data set. 112 * Similarly, a comparison of two IDs only examines the ID, whereas 113 * a comparison of two rules examines the entire data set. 114 * 115 * <h3>Time-zone IDs</h3> 116 * The ID is unique within the system. 117 * There are three types of ID. 118 * <p> 119 * The simplest type of ID is that from {@code ZoneOffset}. 120 * This consists of 'Z' and IDs starting with '+' or '-'. 121 * <p> 122 * The next type of ID are offset-style IDs with some form of prefix, 123 * such as 'GMT+2' or 'UTC+01:00'. 124 * The recognised prefixes are 'UTC', 'GMT' and 'UT'. 125 * The offset is the suffix and will be normalized during creation. 126 * These IDs can be normalized to a {@code ZoneOffset} using {@code normalized()}. 127 * <p> 128 * The third type of ID are region-based IDs. A region-based ID must be of 129 * two or more characters, and not start with 'UTC', 'GMT', 'UT' '+' or '-'. 130 * Region-based IDs are defined by configuration, see {@link ZoneRulesProvider}. 131 * The configuration focuses on providing the lookup from the ID to the 132 * underlying {@code ZoneRules}. 133 * <p> 134 * Time-zone rules are defined by governments and change frequently. 135 * There are a number of organizations, known here as groups, that monitor 136 * time-zone changes and collate them. 137 * The default group is the IANA Time Zone Database (TZDB). 138 * Other organizations include IATA (the airline industry body) and Microsoft. 139 * <p> 140 * Each group defines its own format for the region ID it provides. 141 * The TZDB group defines IDs such as 'Europe/London' or 'America/New_York'. 142 * TZDB IDs take precedence over other groups. 143 * <p> 144 * It is strongly recommended that the group name is included in all IDs supplied by 145 * groups other than TZDB to avoid conflicts. For example, IATA airline time-zone 146 * region IDs are typically the same as the three letter airport code. 147 * However, the airport of Utrecht has the code 'UTC', which is obviously a conflict. 148 * The recommended format for region IDs from groups other than TZDB is 'group~region'. 149 * Thus if IATA data were defined, Utrecht airport would be 'IATA~UTC'. 150 * 151 * <h3>Serialization</h3> 152 * This class can be serialized and stores the string zone ID in the external form. 153 * The {@code ZoneOffset} subclass uses a dedicated format that only stores the 154 * offset from UTC/Greenwich. 155 * <p> 156 * A {@code ZoneId} can be deserialized in a Java Runtime where the ID is unknown. 157 * For example, if a server-side Java Runtime has been updated with a new zone ID, but 158 * the client-side Java Runtime has not been updated. In this case, the {@code ZoneId} 159 * object will exist, and can be queried using {@code getId}, {@code equals}, 160 * {@code hashCode}, {@code toString}, {@code getDisplayName} and {@code normalized}. 161 * However, any call to {@code getRules} will fail with {@code ZoneRulesException}. 162 * This approach is designed to allow a {@link ZonedDateTime} to be loaded and 163 * queried, but not modified, on a Java Runtime with incomplete time-zone information. 164 * 165 * <p> 166 * This is a <a href="{@docRoot}/java/lang/doc-files/ValueBased.html">value-based</a> 167 * class; use of identity-sensitive operations (including reference equality 168 * ({@code ==}), identity hash code, or synchronization) on instances of 169 * {@code ZoneId} may have unpredictable results and should be avoided. 170 * The {@code equals} method should be used for comparisons. 171 * 172 * @implSpec 173 * This abstract class has two implementations, both of which are immutable and thread-safe. 174 * One implementation models region-based IDs, the other is {@code ZoneOffset} modelling 175 * offset-based IDs. This difference is visible in serialization. 176 * 177 * @since 1.8 178 */ 179 public abstract class ZoneId implements Serializable { 180 181 /** 182 * A map of zone overrides to enable the short time-zone names to be used. 183 * <p> 184 * Use of short zone IDs has been deprecated in {@code java.util.TimeZone}. 185 * This map allows the IDs to continue to be used via the 186 * {@link #of(String, Map)} factory method. 187 * <p> 188 * This map contains a mapping of the IDs that is in line with TZDB 2005r and 189 * later, where 'EST', 'MST' and 'HST' map to IDs which do not include daylight 190 * savings. 191 * <p> 192 * This maps as follows: 193 * <ul> 194 * <li>EST - -05:00</li> 195 * <li>HST - -10:00</li> 196 * <li>MST - -07:00</li> 197 * <li>ACT - Australia/Darwin</li> 198 * <li>AET - Australia/Sydney</li> 199 * <li>AGT - America/Argentina/Buenos_Aires</li> 200 * <li>ART - Africa/Cairo</li> 201 * <li>AST - America/Anchorage</li> 202 * <li>BET - America/Sao_Paulo</li> 203 * <li>BST - Asia/Dhaka</li> 204 * <li>CAT - Africa/Harare</li> 205 * <li>CNT - America/St_Johns</li> 206 * <li>CST - America/Chicago</li> 207 * <li>CTT - Asia/Shanghai</li> 208 * <li>EAT - Africa/Addis_Ababa</li> 209 * <li>ECT - Europe/Paris</li> 210 * <li>IET - America/Indiana/Indianapolis</li> 211 * <li>IST - Asia/Kolkata</li> 212 * <li>JST - Asia/Tokyo</li> 213 * <li>MIT - Pacific/Apia</li> 214 * <li>NET - Asia/Yerevan</li> 215 * <li>NST - Pacific/Auckland</li> 216 * <li>PLT - Asia/Karachi</li> 217 * <li>PNT - America/Phoenix</li> 218 * <li>PRT - America/Puerto_Rico</li> 219 * <li>PST - America/Los_Angeles</li> 220 * <li>SST - Pacific/Guadalcanal</li> 221 * <li>VST - Asia/Ho_Chi_Minh</li> 222 * </ul> 223 * The map is unmodifiable. 224 */ 225 public static final Map<String, String> SHORT_IDS; 226 static { 227 Map<String, String> map = new HashMap<>(64); 228 map.put("ACT", "Australia/Darwin"); 229 map.put("AET", "Australia/Sydney"); 230 map.put("AGT", "America/Argentina/Buenos_Aires"); 231 map.put("ART", "Africa/Cairo"); 232 map.put("AST", "America/Anchorage"); 233 map.put("BET", "America/Sao_Paulo"); 234 map.put("BST", "Asia/Dhaka"); 235 map.put("CAT", "Africa/Harare"); 236 map.put("CNT", "America/St_Johns"); 237 map.put("CST", "America/Chicago"); 238 map.put("CTT", "Asia/Shanghai"); 239 map.put("EAT", "Africa/Addis_Ababa"); 240 map.put("ECT", "Europe/Paris"); 241 map.put("IET", "America/Indiana/Indianapolis"); 242 map.put("IST", "Asia/Kolkata"); 243 map.put("JST", "Asia/Tokyo"); 244 map.put("MIT", "Pacific/Apia"); 245 map.put("NET", "Asia/Yerevan"); 246 map.put("NST", "Pacific/Auckland"); 247 map.put("PLT", "Asia/Karachi"); 248 map.put("PNT", "America/Phoenix"); 249 map.put("PRT", "America/Puerto_Rico"); 250 map.put("PST", "America/Los_Angeles"); 251 map.put("SST", "Pacific/Guadalcanal"); 252 map.put("VST", "Asia/Ho_Chi_Minh"); 253 map.put("EST", "-05:00"); 254 map.put("MST", "-07:00"); 255 map.put("HST", "-10:00"); 256 SHORT_IDS = Collections.unmodifiableMap(map); 257 } 258 /** 259 * Serialization version. 260 */ 261 private static final long serialVersionUID = 8352817235686L; 262 263 //----------------------------------------------------------------------- 264 /** 265 * Gets the system default time-zone. 266 * <p> 267 * This queries {@link TimeZone#getDefault()} to find the default time-zone 268 * and converts it to a {@code ZoneId}. If the system default time-zone is changed, 269 * then the result of this method will also change. 270 * 271 * @return the zone ID, not null 272 * @throws DateTimeException if the converted zone ID has an invalid format 273 * @throws ZoneRulesException if the converted zone region ID cannot be found 274 */ 275 public static ZoneId systemDefault() { 276 return SharedSecrets.getJavaUtilTimeZoneAccess().getDefaultRef().toZoneId(); 277 } 278 279 /** 280 * Gets the set of available zone IDs. 281 * <p> 282 * This set includes the string form of all available region-based IDs. 283 * Offset-based zone IDs are not included in the returned set. 284 * The ID can be passed to {@link #of(String)} to create a {@code ZoneId}. 285 * <p> 286 * The set of zone IDs can increase over time, although in a typical application 287 * the set of IDs is fixed. Each call to this method is thread-safe. 288 * 289 * @return a modifiable copy of the set of zone IDs, not null 290 */ 291 public static Set<String> getAvailableZoneIds() { 292 return ZoneRulesProvider.getAvailableZoneIds(); 293 } 294 295 //----------------------------------------------------------------------- 296 /** 297 * Obtains an instance of {@code ZoneId} using its ID using a map 298 * of aliases to supplement the standard zone IDs. 299 * <p> 300 * Many users of time-zones use short abbreviations, such as PST for 301 * 'Pacific Standard Time' and PDT for 'Pacific Daylight Time'. 302 * These abbreviations are not unique, and so cannot be used as IDs. 303 * This method allows a map of string to time-zone to be setup and reused 304 * within an application. 305 * 306 * @param zoneId the time-zone ID, not null 307 * @param aliasMap a map of alias zone IDs (typically abbreviations) to real zone IDs, not null 308 * @return the zone ID, not null 309 * @throws DateTimeException if the zone ID has an invalid format 310 * @throws ZoneRulesException if the zone ID is a region ID that cannot be found 311 */ 312 public static ZoneId of(String zoneId, Map<String, String> aliasMap) { 313 Objects.requireNonNull(zoneId, "zoneId"); 314 Objects.requireNonNull(aliasMap, "aliasMap"); 315 String id = aliasMap.get(zoneId); 316 id = (id != null ? id : zoneId); 317 return of(id); 318 } 319 320 /** 321 * Obtains an instance of {@code ZoneId} from an ID ensuring that the 322 * ID is valid and available for use. 323 * <p> 324 * This method parses the ID producing a {@code ZoneId} or {@code ZoneOffset}. 325 * A {@code ZoneOffset} is returned if the ID is 'Z', or starts with '+' or '-'. 326 * The result will always be a valid ID for which {@link ZoneRules} can be obtained. 327 * <p> 328 * Parsing matches the zone ID step by step as follows. 329 * <ul> 330 * <li>If the zone ID equals 'Z', the result is {@code ZoneOffset.UTC}. 331 * <li>If the zone ID consists of a single letter, the zone ID is invalid 332 * and {@code DateTimeException} is thrown. 333 * <li>If the zone ID starts with '+' or '-', the ID is parsed as a 334 * {@code ZoneOffset} using {@link ZoneOffset#of(String)}. 335 * <li>If the zone ID equals 'GMT', 'UTC' or 'UT' then the result is a {@code ZoneId} 336 * with the same ID and rules equivalent to {@code ZoneOffset.UTC}. 337 * <li>If the zone ID starts with 'UTC+', 'UTC-', 'GMT+', 'GMT-', 'UT+' or 'UT-' 338 * then the ID is a prefixed offset-based ID. The ID is split in two, with 339 * a two or three letter prefix and a suffix starting with the sign. 340 * The suffix is parsed as a {@link ZoneOffset#of(String) ZoneOffset}. 341 * The result will be a {@code ZoneId} with the specified UTC/GMT/UT prefix 342 * and the normalized offset ID as per {@link ZoneOffset#getId()}. 343 * The rules of the returned {@code ZoneId} will be equivalent to the 344 * parsed {@code ZoneOffset}. 345 * <li>All other IDs are parsed as region-based zone IDs. Region IDs must 346 * match the regular expression <code>[A-Za-z][A-Za-z0-9~/._+-]+</code> 347 * otherwise a {@code DateTimeException} is thrown. If the zone ID is not 348 * in the configured set of IDs, {@code ZoneRulesException} is thrown. 349 * The detailed format of the region ID depends on the group supplying the data. 350 * The default set of data is supplied by the IANA Time Zone Database (TZDB). 351 * This has region IDs of the form '{area}/{city}', such as 'Europe/Paris' or 'America/New_York'. 352 * This is compatible with most IDs from {@link java.util.TimeZone}. 353 * </ul> 354 * 355 * @param zoneId the time-zone ID, not null 356 * @return the zone ID, not null 357 * @throws DateTimeException if the zone ID has an invalid format 358 * @throws ZoneRulesException if the zone ID is a region ID that cannot be found 359 */ 360 public static ZoneId of(String zoneId) { 361 return of(zoneId, true); 362 } 363 364 /** 365 * Obtains an instance of {@code ZoneId} wrapping an offset. 366 * <p> 367 * If the prefix is "GMT", "UTC", or "UT" a {@code ZoneId} 368 * with the prefix and the non-zero offset is returned. 369 * If the prefix is empty {@code ""} the {@code ZoneOffset} is returned. 370 * 371 * @param prefix the time-zone ID, not null 372 * @param offset the offset, not null 373 * @return the zone ID, not null 374 * @throws IllegalArgumentException if the prefix is not one of 375 * "GMT", "UTC", or "UT", or "" 376 */ 377 public static ZoneId ofOffset(String prefix, ZoneOffset offset) { 378 Objects.requireNonNull(prefix, "prefix"); 379 Objects.requireNonNull(offset, "offset"); 380 if (prefix.length() == 0) { 381 return offset; 382 } 383 384 if (!prefix.equals("GMT") && !prefix.equals("UTC") && !prefix.equals("UT")) { 385 throw new IllegalArgumentException("prefix should be GMT, UTC or UT, is: " + prefix); 386 } 387 388 if (offset.getTotalSeconds() != 0) { 389 prefix = prefix.concat(offset.getId()); 390 } 391 return new ZoneRegion(prefix, offset.getRules()); 392 } 393 394 /** 395 * Parses the ID, taking a flag to indicate whether {@code ZoneRulesException} 396 * should be thrown or not, used in deserialization. 397 * 398 * @param zoneId the time-zone ID, not null 399 * @param checkAvailable whether to check if the zone ID is available 400 * @return the zone ID, not null 401 * @throws DateTimeException if the ID format is invalid 402 * @throws ZoneRulesException if checking availability and the ID cannot be found 403 */ 404 static ZoneId of(String zoneId, boolean checkAvailable) { 405 Objects.requireNonNull(zoneId, "zoneId"); 406 if (zoneId.length() <= 1 || zoneId.startsWith("+") || zoneId.startsWith("-")) { 407 return ZoneOffset.of(zoneId); 408 } else if (zoneId.startsWith("UTC") || zoneId.startsWith("GMT")) { 409 return ofWithPrefix(zoneId, 3, checkAvailable); 410 } else if (zoneId.startsWith("UT")) { 411 return ofWithPrefix(zoneId, 2, checkAvailable); 412 } 413 return ZoneRegion.ofId(zoneId, checkAvailable); 414 } 415 416 /** 417 * Parse once a prefix is established. 418 * 419 * @param zoneId the time-zone ID, not null 420 * @param prefixLength the length of the prefix, 2 or 3 421 * @return the zone ID, not null 422 * @throws DateTimeException if the zone ID has an invalid format 423 */ 424 private static ZoneId ofWithPrefix(String zoneId, int prefixLength, boolean checkAvailable) { 425 String prefix = zoneId.substring(0, prefixLength); 426 if (zoneId.length() == prefixLength) { 427 return ofOffset(prefix, ZoneOffset.UTC); 428 } 429 if (zoneId.charAt(prefixLength) != '+' && zoneId.charAt(prefixLength) != '-') { 430 return ZoneRegion.ofId(zoneId, checkAvailable); // drop through to ZoneRulesProvider 431 } 432 try { 433 ZoneOffset offset = ZoneOffset.of(zoneId.substring(prefixLength)); 434 if (offset == ZoneOffset.UTC) { 435 return ofOffset(prefix, offset); 436 } 437 return ofOffset(prefix, offset); 438 } catch (DateTimeException ex) { 439 throw new DateTimeException("Invalid ID for offset-based ZoneId: " + zoneId, ex); 440 } 441 } 442 443 //----------------------------------------------------------------------- 444 /** 445 * Obtains an instance of {@code ZoneId} from a temporal object. 446 * <p> 447 * This obtains a zone based on the specified temporal. 448 * A {@code TemporalAccessor} represents an arbitrary set of date and time information, 449 * which this factory converts to an instance of {@code ZoneId}. 450 * <p> 451 * A {@code TemporalAccessor} represents some form of date and time information. 452 * This factory converts the arbitrary temporal object to an instance of {@code ZoneId}. 453 * <p> 454 * The conversion will try to obtain the zone in a way that favours region-based 455 * zones over offset-based zones using {@link TemporalQueries#zone()}. 456 * <p> 457 * This method matches the signature of the functional interface {@link TemporalQuery} 458 * allowing it to be used as a query via method reference, {@code ZoneId::from}. 459 * 460 * @param temporal the temporal object to convert, not null 461 * @return the zone ID, not null 462 * @throws DateTimeException if unable to convert to a {@code ZoneId} 463 */ 464 public static ZoneId from(TemporalAccessor temporal) { 465 ZoneId obj = temporal.query(TemporalQueries.zone()); 466 if (obj == null) { 467 throw new DateTimeException("Unable to obtain ZoneId from TemporalAccessor: " + 468 temporal + " of type " + temporal.getClass().getName()); 469 } 470 return obj; 471 } 472 473 //----------------------------------------------------------------------- 474 /** 475 * Constructor only accessible within the package. 476 */ 477 ZoneId() { 478 if (getClass() != ZoneOffset.class && getClass() != ZoneRegion.class) { 479 throw new AssertionError("Invalid subclass"); 480 } 481 } 482 483 //----------------------------------------------------------------------- 484 /** 485 * Gets the unique time-zone ID. 486 * <p> 487 * This ID uniquely defines this object. 488 * The format of an offset based ID is defined by {@link ZoneOffset#getId()}. 489 * 490 * @return the time-zone unique ID, not null 491 */ 492 public abstract String getId(); 493 494 //----------------------------------------------------------------------- 495 /** 496 * Gets the textual representation of the zone, such as 'British Time' or 497 * '+02:00'. 498 * <p> 499 * This returns the textual name used to identify the time-zone ID, 500 * suitable for presentation to the user. 501 * The parameters control the style of the returned text and the locale. 502 * <p> 503 * If no textual mapping is found then the {@link #getId() full ID} is returned. 504 * 505 * @param style the length of the text required, not null 506 * @param locale the locale to use, not null 507 * @return the text value of the zone, not null 508 */ 509 public String getDisplayName(TextStyle style, Locale locale) { 510 return new DateTimeFormatterBuilder().appendZoneText(style).toFormatter(locale).format(toTemporal()); 511 } 512 513 /** 514 * Converts this zone to a {@code TemporalAccessor}. 515 * <p> 516 * A {@code ZoneId} can be fully represented as a {@code TemporalAccessor}. 517 * However, the interface is not implemented by this class as most of the 518 * methods on the interface have no meaning to {@code ZoneId}. 519 * <p> 520 * The returned temporal has no supported fields, with the query method 521 * supporting the return of the zone using {@link TemporalQueries#zoneId()}. 522 * 523 * @return a temporal equivalent to this zone, not null 524 */ 525 private TemporalAccessor toTemporal() { 526 return new TemporalAccessor() { 527 @Override 528 public boolean isSupported(TemporalField field) { 529 return false; 530 } 531 @Override 532 public long getLong(TemporalField field) { 533 throw new UnsupportedTemporalTypeException("Unsupported field: " + field); 534 } 535 @SuppressWarnings("unchecked") 536 @Override 537 public <R> R query(TemporalQuery<R> query) { 538 if (query == TemporalQueries.zoneId()) { 539 return (R) ZoneId.this; 540 } 541 return TemporalAccessor.super.query(query); 542 } 543 }; 544 } 545 546 //----------------------------------------------------------------------- 547 /** 548 * Gets the time-zone rules for this ID allowing calculations to be performed. 549 * <p> 550 * The rules provide the functionality associated with a time-zone, 551 * such as finding the offset for a given instant or local date-time. 552 * <p> 553 * A time-zone can be invalid if it is deserialized in a Java Runtime which 554 * does not have the same rules loaded as the Java Runtime that stored it. 555 * In this case, calling this method will throw a {@code ZoneRulesException}. 556 * <p> 557 * The rules are supplied by {@link ZoneRulesProvider}. An advanced provider may 558 * support dynamic updates to the rules without restarting the Java Runtime. 559 * If so, then the result of this method may change over time. 560 * Each individual call will be still remain thread-safe. 561 * <p> 562 * {@link ZoneOffset} will always return a set of rules where the offset never changes. 563 * 564 * @return the rules, not null 565 * @throws ZoneRulesException if no rules are available for this ID 566 */ 567 public abstract ZoneRules getRules(); 568 569 /** 570 * Normalizes the time-zone ID, returning a {@code ZoneOffset} where possible. 571 * <p> 572 * The returns a normalized {@code ZoneId} that can be used in place of this ID. 573 * The result will have {@code ZoneRules} equivalent to those returned by this object, 574 * however the ID returned by {@code getId()} may be different. 575 * <p> 576 * The normalization checks if the rules of this {@code ZoneId} have a fixed offset. 577 * If they do, then the {@code ZoneOffset} equal to that offset is returned. 578 * Otherwise {@code this} is returned. 579 * 580 * @return the time-zone unique ID, not null 581 */ 582 public ZoneId normalized() { 583 try { 584 ZoneRules rules = getRules(); 585 if (rules.isFixedOffset()) { 586 return rules.getOffset(Instant.EPOCH); 587 } 588 } catch (ZoneRulesException ex) { 589 // invalid ZoneRegion is not important to this method 590 } 591 return this; 592 } 593 594 //----------------------------------------------------------------------- 595 /** 596 * Checks if this time-zone ID is equal to another time-zone ID. 597 * <p> 598 * The comparison is based on the ID. 599 * 600 * @param obj the object to check, null returns false 601 * @return true if this is equal to the other time-zone ID 602 */ 603 @Override 604 public boolean equals(Object obj) { 605 if (this == obj) { 606 return true; 607 } 608 if (obj instanceof ZoneId) { 609 ZoneId other = (ZoneId) obj; 610 return getId().equals(other.getId()); 611 } 612 return false; 613 } 614 615 /** 616 * A hash code for this time-zone ID. 617 * 618 * @return a suitable hash code 619 */ 620 @Override 621 public int hashCode() { 622 return getId().hashCode(); 623 } 624 625 //----------------------------------------------------------------------- 626 /** 627 * Defend against malicious streams. 628 * 629 * @param s the stream to read 630 * @throws InvalidObjectException always 631 */ 632 private void readObject(ObjectInputStream s) throws InvalidObjectException { 633 throw new InvalidObjectException("Deserialization via serialization delegate"); 634 } 635 636 /** 637 * Outputs this zone as a {@code String}, using the ID. 638 * 639 * @return a string representation of this time-zone ID, not null 640 */ 641 @Override 642 public String toString() { 643 return getId(); 644 } 645 646 //----------------------------------------------------------------------- 647 /** 648 * Writes the object using a 649 * <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>. 650 * @serialData 651 * <pre> 652 * out.writeByte(7); // identifies a ZoneId (not ZoneOffset) 653 * out.writeUTF(getId()); 654 * </pre> 655 * <p> 656 * When read back in, the {@code ZoneId} will be created as though using 657 * {@link #of(String)}, but without any exception in the case where the 658 * ID has a valid format, but is not in the known set of region-based IDs. 659 * 660 * @return the instance of {@code Ser}, not null 661 */ 662 // this is here for serialization Javadoc 663 private Object writeReplace() { 664 return new Ser(Ser.ZONE_REGION_TYPE, this); 665 } 666 667 abstract void write(DataOutput out) throws IOException; 668 669 }