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