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