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