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.Queries; 70 import java.time.temporal.TemporalAccessor; 71 import java.time.temporal.TemporalField; 72 import java.time.temporal.TemporalQuery; 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.TimeZone; 82 83 /** 84 * A time-zone ID, such as {@code Europe/Paris}. 85 * <p> 86 * A {@code ZoneId} is used to identify the rules used to convert between 87 * an {@link Instant} and a {@link LocalDateTime}. 88 * There are two distinct types of ID: 89 * <p><ul> 90 * <li>Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses 91 * the same offset for all local date-times 92 * <li>Geographical regions - an area where a specific set of rules for finding 93 * the offset from UTC/Greenwich apply 94 * </ul><p> 95 * Most fixed offsets are represented by {@link ZoneOffset}. 96 * <p> 97 * The actual rules, describing when and how the offset changes, are defined by {@link ZoneRules}. 98 * This class is simply an ID used to obtain the underlying rules. 99 * This approach is taken because rules are defined by governments and change 100 * frequently, whereas the ID is stable. 101 * <p> 102 * The distinction has other effects. Serializing the {@code ZoneId} will only send 103 * the ID, whereas serializing the rules sends the entire data set. 104 * Similarly, a comparison of two IDs only examines the ID, whereas 105 * a comparison of two rules examines the entire data set. 106 * <p> 107 * The code supports loading a {@code ZoneId} on a JVM which does not have available rules 108 * for that ID. This allows the date-time object, such as {@link ZonedDateTime}, 109 * to still be queried. 110 * 111 * <h3>Time-zone IDs</h3> 112 * The ID is unique within the system. 113 * The formats for offset and region IDs differ. 114 * <p> 115 * An ID is parsed as an offset ID if it starts with 'UTC', 'GMT', 'UT' '+' or '-', or 116 * is a single letter. For example, 'Z', '+02:00', '-05:00', 'UTC+05', 'GMT-6' and 117 * 'UT+01:00' are all valid offset IDs. 118 * Note that some IDs, such as 'D' or '+ABC' meet the criteria to be parsed as offset IDs, 119 * but have an invalid offset. 120 * <p> 121 * All other IDs are considered to be region IDs. 122 * <p> 123 * Region IDs are defined by configuration, which can be thought of as a {@code Map} 124 * from region ID to {@code ZoneRules}, see {@link ZoneRulesProvider}. 125 * <p> 126 * Time-zones are defined by governments and change frequently. There are a number of 127 * organizations, known here as groups, that monitor time-zone changes and collate them. 128 * The default group is the IANA Time Zone Database (TZDB). 129 * Other organizations include IATA (the airline industry body) and Microsoft. 130 * <p> 131 * Each group defines its own format for the region ID it provides. 132 * The TZDB group defines IDs such as 'Europe/London' or 'America/New_York'. 133 * TZDB IDs take precedence over other groups. 134 * <p> 135 * It is strongly recommended that the group name is included in all IDs supplied by 136 * groups other than TZDB to avoid conflicts. For example, IATA airline time-zone 137 * region IDs are typically the same as the three letter airport code. 138 * However, the airport of Utrecht has the code 'UTC', which is obviously a conflict. 139 * The recommended format for region IDs from groups other than TZDB is 'group~region'. 140 * Thus if IATA data were defined, Utrecht airport would be 'IATA~UTC'. 141 * 142 * <h3>Specification for implementors</h3> 143 * This abstract class has two implementations, both of which are immutable and thread-safe. 144 * One implementation models region-based IDs, the other is {@code ZoneOffset} modelling 145 * offset-based IDs. This difference is visible in serialization. 146 * 147 * @since 1.8 148 */ 149 public abstract class ZoneId implements Serializable { 150 151 /** 152 * A map of zone overrides to enable the older US time-zone names to be used. 153 * <p> 154 * This maps as follows: 155 * <p><ul> 156 * <li>EST - America/New_York</li> 157 * <li>MST - America/Denver</li> 158 * <li>HST - Pacific/Honolulu</li> 159 * <li>ACT - Australia/Darwin</li> 160 * <li>AET - Australia/Sydney</li> 161 * <li>AGT - America/Argentina/Buenos_Aires</li> 162 * <li>ART - Africa/Cairo</li> 163 * <li>AST - America/Anchorage</li> 164 * <li>BET - America/Sao_Paulo</li> 165 * <li>BST - Asia/Dhaka</li> 166 * <li>CAT - Africa/Harare</li> 167 * <li>CNT - America/St_Johns</li> 168 * <li>CST - America/Chicago</li> 169 * <li>CTT - Asia/Shanghai</li> 170 * <li>EAT - Africa/Addis_Ababa</li> 171 * <li>ECT - Europe/Paris</li> 172 * <li>IET - America/Indiana/Indianapolis</li> 173 * <li>IST - Asia/Kolkata</li> 174 * <li>JST - Asia/Tokyo</li> 175 * <li>MIT - Pacific/Apia</li> 176 * <li>NET - Asia/Yerevan</li> 177 * <li>NST - Pacific/Auckland</li> 178 * <li>PLT - Asia/Karachi</li> 179 * <li>PNT - America/Phoenix</li> 180 * <li>PRT - America/Puerto_Rico</li> 181 * <li>PST - America/Los_Angeles</li> 182 * <li>SST - Pacific/Guadalcanal</li> 183 * <li>VST - Asia/Ho_Chi_Minh</li> 184 * </ul><p> 185 * The map is unmodifiable. 186 */ 187 public static final Map<String, String> OLD_IDS_PRE_2005; 188 /** 189 * A map of zone overrides to enable the older US time-zone names to be used. 190 * <p> 191 * This maps as follows: 192 * <p><ul> 193 * <li>EST - -05:00</li> 194 * <li>HST - -10:00</li> 195 * <li>MST - -07:00</li> 196 * <li>ACT - Australia/Darwin</li> 197 * <li>AET - Australia/Sydney</li> 198 * <li>AGT - America/Argentina/Buenos_Aires</li> 199 * <li>ART - Africa/Cairo</li> 200 * <li>AST - America/Anchorage</li> 201 * <li>BET - America/Sao_Paulo</li> 202 * <li>BST - Asia/Dhaka</li> 203 * <li>CAT - Africa/Harare</li> 204 * <li>CNT - America/St_Johns</li> 205 * <li>CST - America/Chicago</li> 206 * <li>CTT - Asia/Shanghai</li> 207 * <li>EAT - Africa/Addis_Ababa</li> 208 * <li>ECT - Europe/Paris</li> 209 * <li>IET - America/Indiana/Indianapolis</li> 210 * <li>IST - Asia/Kolkata</li> 211 * <li>JST - Asia/Tokyo</li> 212 * <li>MIT - Pacific/Apia</li> 213 * <li>NET - Asia/Yerevan</li> 214 * <li>NST - Pacific/Auckland</li> 215 * <li>PLT - Asia/Karachi</li> 216 * <li>PNT - America/Phoenix</li> 217 * <li>PRT - America/Puerto_Rico</li> 218 * <li>PST - America/Los_Angeles</li> 219 * <li>SST - Pacific/Guadalcanal</li> 220 * <li>VST - Asia/Ho_Chi_Minh</li> 221 * </ul><p> 222 * The map is unmodifiable. 223 */ 224 public static final Map<String, String> OLD_IDS_POST_2005; 225 static { 226 Map<String, String> base = new HashMap<>(); 227 base.put("ACT", "Australia/Darwin"); 228 base.put("AET", "Australia/Sydney"); 229 base.put("AGT", "America/Argentina/Buenos_Aires"); 230 base.put("ART", "Africa/Cairo"); 231 base.put("AST", "America/Anchorage"); 232 base.put("BET", "America/Sao_Paulo"); 233 base.put("BST", "Asia/Dhaka"); 234 base.put("CAT", "Africa/Harare"); 235 base.put("CNT", "America/St_Johns"); 236 base.put("CST", "America/Chicago"); 237 base.put("CTT", "Asia/Shanghai"); 238 base.put("EAT", "Africa/Addis_Ababa"); 239 base.put("ECT", "Europe/Paris"); 240 base.put("IET", "America/Indiana/Indianapolis"); 241 base.put("IST", "Asia/Kolkata"); 242 base.put("JST", "Asia/Tokyo"); 243 base.put("MIT", "Pacific/Apia"); 244 base.put("NET", "Asia/Yerevan"); 245 base.put("NST", "Pacific/Auckland"); 246 base.put("PLT", "Asia/Karachi"); 247 base.put("PNT", "America/Phoenix"); 248 base.put("PRT", "America/Puerto_Rico"); 249 base.put("PST", "America/Los_Angeles"); 250 base.put("SST", "Pacific/Guadalcanal"); 251 base.put("VST", "Asia/Ho_Chi_Minh"); 252 Map<String, String> pre = new HashMap<>(base); 253 pre.put("EST", "America/New_York"); 254 pre.put("MST", "America/Denver"); 255 pre.put("HST", "Pacific/Honolulu"); 256 OLD_IDS_PRE_2005 = Collections.unmodifiableMap(pre); 257 Map<String, String> post = new HashMap<>(base); 258 post.put("EST", "-05:00"); 259 post.put("MST", "-07:00"); 260 post.put("HST", "-10:00"); 261 OLD_IDS_POST_2005 = Collections.unmodifiableMap(post); 262 } 263 /** 264 * Serialization version. 265 */ 266 private static final long serialVersionUID = 8352817235686L; 267 268 //----------------------------------------------------------------------- 269 /** 270 * Gets the system default time-zone. 271 * <p> 272 * This queries {@link TimeZone#getDefault()} to find the default time-zone 273 * and converts it to a {@code ZoneId}. If the system default time-zone is changed, 274 * then the result of this method will also change. 275 * 276 * @return the zone ID, not null 277 * @throws DateTimeException if the converted zone ID has an invalid format 278 * @throws ZoneRulesException if the converted zone region ID cannot be found 279 */ 280 public static ZoneId systemDefault() { 281 return ZoneId.of(TimeZone.getDefault().getID(), OLD_IDS_POST_2005); 282 } 283 284 //----------------------------------------------------------------------- 285 /** 286 * Obtains an instance of {@code ZoneId} using its ID using a map 287 * of aliases to supplement the standard zone IDs. 288 * <p> 289 * Many users of time-zones use short abbreviations, such as PST for 290 * 'Pacific Standard Time' and PDT for 'Pacific Daylight Time'. 291 * These abbreviations are not unique, and so cannot be used as IDs. 292 * This method allows a map of string to time-zone to be setup and reused 293 * within an application. 294 * 295 * @param zoneId the time-zone ID, not null 296 * @param aliasMap a map of alias zone IDs (typically abbreviations) to real zone IDs, not null 297 * @return the zone ID, not null 298 * @throws DateTimeException if the zone ID has an invalid format 299 * @throws ZoneRulesException if the zone ID is a region ID that cannot be found 300 */ 301 public static ZoneId of(String zoneId, Map<String, String> aliasMap) { 302 Objects.requireNonNull(zoneId, "zoneId"); 303 Objects.requireNonNull(aliasMap, "aliasMap"); 304 String id = aliasMap.get(zoneId); 305 id = (id != null ? id : zoneId); 306 return of(id); 307 } 308 309 /** 310 * Obtains an instance of {@code ZoneId} from an ID ensuring that the 311 * ID is valid and available for use. 312 * <p> 313 * This method parses the ID, applies any appropriate normalization, and validates it 314 * against the known set of IDs for which rules are available. 315 * <p> 316 * An ID is parsed as though it is an offset ID if it starts with 'UTC', 'GMT', 'UT', '+' 317 * or '-', or if it has less then two letters. 318 * The offset of {@linkplain ZoneOffset#UTC zero} may be represented in multiple ways, 319 * including 'Z', 'UTC', 'GMT', 'UT', 'UTC0', 'GMT0', 'UT0', '+00:00', '-00:00' and 'UTC+00:00'. 320 * <p> 321 * Six forms of ID are recognized: 322 * <p><ul> 323 * <li><code>Z</code> - an offset of zero, which is {@code ZoneOffset.UTC} 324 * <li><code>{offset}</code> - a {@code ZoneOffset} ID, such as '+02:00' 325 * <li><code>{utcPrefix}</code> - a {@code ZoneOffset} ID equal to 'Z' 326 * <li><code>{utcPrefix}0</code> - a {@code ZoneOffset} ID equal to 'Z' 327 * <li><code>{utcPrefix}{offset}</code> - a {@code ZoneOffset} ID equal to '{offset}' 328 * <li><code>{regionID}</code> - full region ID, loaded from configuration 329 * </ul><p> 330 * The {offset} is a valid format for {@link ZoneOffset#of(String)}, excluding 'Z'. 331 * The {utcPrefix} is 'UTC', 'GMT' or 'UT'. 332 * Region IDs must match the regular expression <code>[A-Za-z][A-Za-z0-9~/._+-]+</code>. 333 * <p> 334 * The detailed format of the region ID depends on the group supplying the data. 335 * The default set of data is supplied by the IANA Time Zone Database (TZDB) 336 * This has region IDs of the form '{area}/{city}', such as 'Europe/Paris' or 'America/New_York'. 337 * This is compatible with most IDs from {@link java.util.TimeZone}. 338 * 339 * @param zoneId the time-zone ID, not null 340 * @return the zone ID, not null 341 * @throws DateTimeException if the zone ID has an invalid format 342 * @throws ZoneRulesException if the zone ID is a region ID that cannot be found 343 */ 344 public static ZoneId of(String zoneId) { 345 Objects.requireNonNull(zoneId, "zoneId"); 346 if (zoneId.length() <= 1 || zoneId.startsWith("+") || zoneId.startsWith("-")) { 347 return ZoneOffset.of(zoneId); 348 } else if (zoneId.startsWith("UTC") || zoneId.startsWith("GMT")) { 349 return ofWithPrefix(zoneId, 3); 350 } else if (zoneId.startsWith("UT")) { 351 return ofWithPrefix(zoneId, 2); 352 } 353 return ZoneRegion.ofId(zoneId, true); 354 } 355 356 /** 357 * Parse once a prefix is established. 358 * 359 * @param zoneId the time-zone ID, not null 360 * @param prefixLength the length of the prefix, 2 or 3 361 * @return the zone ID, not null 362 * @return the zone ID, not null 363 * @throws DateTimeException if the zone ID has an invalid format 364 */ 365 private static ZoneId ofWithPrefix(String zoneId, int prefixLength) { 366 if (zoneId.length() == prefixLength || 367 (zoneId.length() == prefixLength + 1 && zoneId.charAt(prefixLength) == '0')) { 368 return ZoneOffset.UTC; 369 } 370 if (zoneId.charAt(prefixLength) == '+' || zoneId.charAt(prefixLength) == '-') { 371 try { 372 return ZoneOffset.of(zoneId.substring(prefixLength)); 373 } catch (DateTimeException ex) { 374 throw new DateTimeException("Invalid ID for offset-based ZoneId: " + zoneId, ex); 375 } 376 } 377 throw new DateTimeException("Invalid ID for offset-based ZoneId: " + zoneId); 378 } 379 380 //----------------------------------------------------------------------- 381 /** 382 * Obtains an instance of {@code ZoneId} from a temporal object. 383 * <p> 384 * This obtains a zone based on the specified temporal. 385 * A {@code TemporalAccessor} represents an arbitrary set of date and time information, 386 * which this factory converts to an instance of {@code ZoneId}. 387 * <p> 388 * A {@code TemporalAccessor} represents some form of date and time information. 389 * This factory converts the arbitrary temporal object to an instance of {@code ZoneId}. 390 * <p> 391 * The conversion will try to obtain the zone in a way that favours region-based 392 * zones over offset-based zones using {@link Queries#zone()}. 393 * <p> 394 * This method matches the signature of the functional interface {@link TemporalQuery} 395 * allowing it to be used in queries via method reference, {@code ZoneId::from}. 396 * 397 * @param temporal the temporal object to convert, not null 398 * @return the zone ID, not null 399 * @throws DateTimeException if unable to convert to a {@code ZoneId} 400 */ 401 public static ZoneId from(TemporalAccessor temporal) { 402 ZoneId obj = temporal.query(Queries.zone()); 403 if (obj == null) { 404 throw new DateTimeException("Unable to obtain ZoneId from TemporalAccessor: " + temporal.getClass()); 405 } 406 return obj; 407 } 408 409 //----------------------------------------------------------------------- 410 /** 411 * Constructor only accessible within the package. 412 */ 413 ZoneId() { 414 if (getClass() != ZoneOffset.class && getClass() != ZoneRegion.class) { 415 throw new AssertionError("Invalid subclass"); 416 } 417 } 418 419 //----------------------------------------------------------------------- 420 /** 421 * Gets the unique time-zone ID. 422 * <p> 423 * This ID uniquely defines this object. 424 * The format of an offset based ID is defined by {@link ZoneOffset#getId()}. 425 * 426 * @return the time-zone unique ID, not null 427 */ 428 public abstract String getId(); 429 430 //----------------------------------------------------------------------- 431 /** 432 * Gets the time-zone rules for this ID allowing calculations to be performed. 433 * <p> 434 * The rules provide the functionality associated with a time-zone, 435 * such as finding the offset for a given instant or local date-time. 436 * <p> 437 * A time-zone can be invalid if it is deserialized in a JVM which does not 438 * have the same rules loaded as the JVM that stored it. In this case, calling 439 * this method will throw an exception. 440 * <p> 441 * The rules are supplied by {@link ZoneRulesProvider}. An advanced provider may 442 * support dynamic updates to the rules without restarting the JVM. 443 * If so, then the result of this method may change over time. 444 * Each individual call will be still remain thread-safe. 445 * <p> 446 * {@link ZoneOffset} will always return a set of rules where the offset never changes. 447 * 448 * @return the rules, not null 449 * @throws ZoneRulesException if no rules are available for this ID 450 */ 451 public abstract ZoneRules getRules(); 452 453 //----------------------------------------------------------------------- 454 /** 455 * Gets the textual representation of the zone, such as 'British Time' or 456 * '+02:00'. 457 * <p> 458 * This returns the textual name used to identify the time-zone ID, 459 * suitable for presentation to the user. 460 * The parameters control the style of the returned text and the locale. 461 * <p> 462 * If no textual mapping is found then the {@link #getId() full ID} is returned. 463 * 464 * @param style the length of the text required, not null 465 * @param locale the locale to use, not null 466 * @return the text value of the zone, not null 467 */ 468 public String getDisplayName(TextStyle style, Locale locale) { 469 return new DateTimeFormatterBuilder().appendZoneText(style).toFormatter(locale).format(new TemporalAccessor() { 470 @Override 471 public boolean isSupported(TemporalField field) { 472 return false; 473 } 474 @Override 475 public long getLong(TemporalField field) { 476 throw new DateTimeException("Unsupported field: " + field); 477 } 478 @SuppressWarnings("unchecked") 479 @Override 480 public <R> R query(TemporalQuery<R> query) { 481 if (query == Queries.zoneId()) { 482 return (R) ZoneId.this; 483 } 484 return TemporalAccessor.super.query(query); 485 } 486 }); 487 } 488 489 //----------------------------------------------------------------------- 490 /** 491 * Checks if this time-zone ID is equal to another time-zone ID. 492 * <p> 493 * The comparison is based on the ID. 494 * 495 * @param obj the object to check, null returns false 496 * @return true if this is equal to the other time-zone ID 497 */ 498 @Override 499 public boolean equals(Object obj) { 500 if (this == obj) { 501 return true; 502 } 503 if (obj instanceof ZoneId) { 504 ZoneId other = (ZoneId) obj; 505 return getId().equals(other.getId()); 506 } 507 return false; 508 } 509 510 /** 511 * A hash code for this time-zone ID. 512 * 513 * @return a suitable hash code 514 */ 515 @Override 516 public int hashCode() { 517 return getId().hashCode(); 518 } 519 520 //----------------------------------------------------------------------- 521 /** 522 * Outputs this zone as a {@code String}, using the ID. 523 * 524 * @return a string representation of this time-zone ID, not null 525 */ 526 @Override 527 public String toString() { 528 return getId(); 529 } 530 531 //----------------------------------------------------------------------- 532 /** 533 * Writes the object using a 534 * <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>. 535 * <pre> 536 * out.writeByte(7); // identifies this as a ZoneId (not ZoneOffset) 537 * out.writeUTF(zoneId); 538 * </pre> 539 * 540 * @return the instance of {@code Ser}, not null 541 */ 542 // this is here for serialization Javadoc 543 private Object writeReplace() { 544 return new Ser(Ser.ZONE_REGION_TYPE, this); 545 } 546 547 abstract void write(DataOutput out) throws IOException; 548 549 }