001/* 002 * Copyright (c) 2007-2013, Stephen Colebourne & Michael Nascimento Santos 003 * 004 * All rights reserved. 005 * 006 * Redistribution and use in source and binary forms, with or without 007 * modification, are permitted provided that the following conditions are met: 008 * 009 * * Redistributions of source code must retain the above copyright notice, 010 * this list of conditions and the following disclaimer. 011 * 012 * * Redistributions in binary form must reproduce the above copyright notice, 013 * this list of conditions and the following disclaimer in the documentation 014 * and/or other materials provided with the distribution. 015 * 016 * * Neither the name of JSR-310 nor the names of its contributors 017 * may be used to endorse or promote products derived from this software 018 * without specific prior written permission. 019 * 020 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 021 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 022 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 023 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 024 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 025 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 026 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 027 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 028 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 029 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 030 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 031 */ 032package org.threeten.bp; 033 034import java.io.DataOutput; 035import java.io.IOException; 036import java.io.Serializable; 037import java.util.Collections; 038import java.util.HashMap; 039import java.util.Locale; 040import java.util.Map; 041import java.util.Objects; 042import java.util.TimeZone; 043 044import org.threeten.bp.format.DateTimeFormatterBuilder; 045import org.threeten.bp.format.TextStyle; 046import org.threeten.bp.jdk8.DefaultInterfaceTemporalAccessor; 047import org.threeten.bp.temporal.TemporalAccessor; 048import org.threeten.bp.temporal.TemporalField; 049import org.threeten.bp.temporal.TemporalQueries; 050import org.threeten.bp.temporal.TemporalQuery; 051import org.threeten.bp.zone.ZoneRules; 052import org.threeten.bp.zone.ZoneRulesException; 053import org.threeten.bp.zone.ZoneRulesProvider; 054 055/** 056 * A time-zone ID, such as {@code Europe/Paris}. 057 * <p> 058 * A {@code ZoneId} is used to identify the rules used to convert between 059 * an {@link Instant} and a {@link LocalDateTime}. 060 * There are two distinct types of ID: 061 * <p><ul> 062 * <li>Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses 063 * the same offset for all local date-times 064 * <li>Geographical regions - an area where a specific set of rules for finding 065 * the offset from UTC/Greenwich apply 066 * </ul><p> 067 * Most fixed offsets are represented by {@link ZoneOffset}. 068 * <p> 069 * The actual rules, describing when and how the offset changes, are defined by {@link ZoneRules}. 070 * This class is simply an ID used to obtain the underlying rules. 071 * This approach is taken because rules are defined by governments and change 072 * frequently, whereas the ID is stable. 073 * <p> 074 * The distinction has other effects. Serializing the {@code ZoneId} will only send 075 * the ID, whereas serializing the rules sends the entire data set. 076 * Similarly, a comparison of two IDs only examines the ID, whereas 077 * a comparison of two rules examines the entire data set. 078 * <p> 079 * The code supports loading a {@code ZoneId} on a JVM which does not have available rules 080 * for that ID. This allows the date-time object, such as {@link ZonedDateTime}, 081 * to still be queried. 082 * 083 * <h3>Time-zone IDs</h3> 084 * The ID is unique within the system. 085 * The formats for offset and region IDs differ. 086 * <p> 087 * An ID is parsed as an offset ID if it starts with 'UTC', 'GMT', '+' or '-', or 088 * is a single letter. 089 * For example, 'Z', '+02:00', '-05:00', 'UTC+05' and 'GMT-6' are all valid offset IDs. 090 * Note that some IDs, such as 'D' or '+ABC' meet the criteria, but are invalid. 091 * <p> 092 * All other IDs are considered to be region IDs. 093 * <p> 094 * Region IDs are defined by configuration, which can be thought of as a {@code Map} 095 * from region ID to {@code ZoneRules}, see {@link ZoneRulesProvider}. 096 * <p> 097 * Time-zones are defined by governments and change frequently. There are a number of 098 * organizations, known here as groups, that monitor time-zone changes and collate them. 099 * The default group is the IANA Time Zone Database (TZDB). 100 * Other organizations include IATA (the airline industry body) and Microsoft. 101 * <p> 102 * Each group defines its own format for region ID. 103 * The TZDB group defines IDs such as 'Europe/London' or 'America/New_York'. 104 * TZDB IDs take precedence over other groups. 105 * <p> 106 * It is strongly recommended that the group name is included in all Ids supplied by 107 * groups other than TZDB to avoid conflicts. For example, IATA airline time-zone 108 * region IDs are typically the same as the three letter airport code. 109 * However, the airport of Utrecht has the code 'UTC', which is obviously a conflict. 110 * The recommended format for region IDs from groups other than TZDB is 'group~region'. 111 * Thus if IATA data were defined, Utrecht airport would be 'IATA~UTC'. 112 * 113 * <h3>Specification for implementors</h3> 114 * This abstract class has two implementations, both of which are immutable and thread-safe. 115 * One implementation models region-based IDs, the other is {@code ZoneOffset} modelling 116 * offset-based IDs. 117 */ 118public abstract class ZoneId implements Serializable { 119 120 /** 121 * A map of zone overrides to enable the older US time-zone names to be used. 122 * <p> 123 * This maps as follows: 124 * <p><ul> 125 * <li>EST - America/Indianapolis</li> 126 * <li>MST - America/Phoenix</li> 127 * <li>HST - Pacific/Honolulu</li> 128 * <li>ACT - Australia/Darwin</li> 129 * <li>AET - Australia/Sydney</li> 130 * <li>AGT - America/Argentina/Buenos_Aires</li> 131 * <li>ART - Africa/Cairo</li> 132 * <li>AST - America/Anchorage</li> 133 * <li>BET - America/Sao_Paulo</li> 134 * <li>BST - Asia/Dhaka</li> 135 * <li>CAT - Africa/Harare</li> 136 * <li>CNT - America/St_Johns</li> 137 * <li>CST - America/Chicago</li> 138 * <li>CTT - Asia/Shanghai</li> 139 * <li>EAT - Africa/Addis_Ababa</li> 140 * <li>ECT - Europe/Paris</li> 141 * <li>IET - America/Indiana/Indianapolis</li> 142 * <li>IST - Asia/Kolkata</li> 143 * <li>JST - Asia/Tokyo</li> 144 * <li>MIT - Pacific/Apia</li> 145 * <li>NET - Asia/Yerevan</li> 146 * <li>NST - Pacific/Auckland</li> 147 * <li>PLT - Asia/Karachi</li> 148 * <li>PNT - America/Phoenix</li> 149 * <li>PRT - America/Puerto_Rico</li> 150 * <li>PST - America/Los_Angeles</li> 151 * <li>SST - Pacific/Guadalcanal</li> 152 * <li>VST - Asia/Ho_Chi_Minh</li> 153 * </ul><p> 154 * The map is unmodifiable. 155 */ 156 public static final Map<String, String> OLD_IDS_PRE_2005; 157 /** 158 * A map of zone overrides to enable the older US time-zone names to be used. 159 * <p> 160 * This maps as follows: 161 * <p><ul> 162 * <li>EST - -05:00</li> 163 * <li>HST - -10:00</li> 164 * <li>MST - -07:00</li> 165 * <li>ACT - Australia/Darwin</li> 166 * <li>AET - Australia/Sydney</li> 167 * <li>AGT - America/Argentina/Buenos_Aires</li> 168 * <li>ART - Africa/Cairo</li> 169 * <li>AST - America/Anchorage</li> 170 * <li>BET - America/Sao_Paulo</li> 171 * <li>BST - Asia/Dhaka</li> 172 * <li>CAT - Africa/Harare</li> 173 * <li>CNT - America/St_Johns</li> 174 * <li>CST - America/Chicago</li> 175 * <li>CTT - Asia/Shanghai</li> 176 * <li>EAT - Africa/Addis_Ababa</li> 177 * <li>ECT - Europe/Paris</li> 178 * <li>IET - America/Indiana/Indianapolis</li> 179 * <li>IST - Asia/Kolkata</li> 180 * <li>JST - Asia/Tokyo</li> 181 * <li>MIT - Pacific/Apia</li> 182 * <li>NET - Asia/Yerevan</li> 183 * <li>NST - Pacific/Auckland</li> 184 * <li>PLT - Asia/Karachi</li> 185 * <li>PNT - America/Phoenix</li> 186 * <li>PRT - America/Puerto_Rico</li> 187 * <li>PST - America/Los_Angeles</li> 188 * <li>SST - Pacific/Guadalcanal</li> 189 * <li>VST - Asia/Ho_Chi_Minh</li> 190 * </ul><p> 191 * The map is unmodifiable. 192 */ 193 public static final Map<String, String> OLD_IDS_POST_2005; 194 static { 195 Map<String, String> base = new HashMap<>(); 196 base.put("ACT", "Australia/Darwin"); 197 base.put("AET", "Australia/Sydney"); 198 base.put("AGT", "America/Argentina/Buenos_Aires"); 199 base.put("ART", "Africa/Cairo"); 200 base.put("AST", "America/Anchorage"); 201 base.put("BET", "America/Sao_Paulo"); 202 base.put("BST", "Asia/Dhaka"); 203 base.put("CAT", "Africa/Harare"); 204 base.put("CNT", "America/St_Johns"); 205 base.put("CST", "America/Chicago"); 206 base.put("CTT", "Asia/Shanghai"); 207 base.put("EAT", "Africa/Addis_Ababa"); 208 base.put("ECT", "Europe/Paris"); 209 base.put("IET", "America/Indiana/Indianapolis"); 210 base.put("IST", "Asia/Kolkata"); 211 base.put("JST", "Asia/Tokyo"); 212 base.put("MIT", "Pacific/Apia"); 213 base.put("NET", "Asia/Yerevan"); 214 base.put("NST", "Pacific/Auckland"); 215 base.put("PLT", "Asia/Karachi"); 216 base.put("PNT", "America/Phoenix"); 217 base.put("PRT", "America/Puerto_Rico"); 218 base.put("PST", "America/Los_Angeles"); 219 base.put("SST", "Pacific/Guadalcanal"); 220 base.put("VST", "Asia/Ho_Chi_Minh"); 221 Map<String, String> pre = new HashMap<>(base); 222 pre.put("EST", "America/Indianapolis"); 223 pre.put("MST", "America/Phoenix"); 224 pre.put("HST", "Pacific/Honolulu"); 225 OLD_IDS_PRE_2005 = Collections.unmodifiableMap(pre); 226 Map<String, String> post = new HashMap<>(base); 227 post.put("EST", "-05:00"); 228 post.put("MST", "-07:00"); 229 post.put("HST", "-10:00"); 230 OLD_IDS_POST_2005 = Collections.unmodifiableMap(post); 231 } 232 /** 233 * Serialization version. 234 */ 235 private static final long serialVersionUID = 8352817235686L; 236 237 //----------------------------------------------------------------------- 238 /** 239 * Gets the system default time-zone. 240 * <p> 241 * This queries {@link TimeZone#getDefault()} to find the default time-zone 242 * and converts it to a {@code ZoneId}. If the system default time-zone is changed, 243 * then the result of this method will also change. 244 * 245 * @return the zone ID, not null 246 * @throws DateTimeException if the converted zone ID has an invalid format 247 * @throws ZoneRulesException if the converted zone region ID cannot be found 248 */ 249 public static ZoneId systemDefault() { 250 return ZoneId.of(TimeZone.getDefault().getID(), OLD_IDS_POST_2005); 251 } 252 253 //----------------------------------------------------------------------- 254 /** 255 * Obtains an instance of {@code ZoneId} using its ID using a map 256 * of aliases to supplement the standard zone IDs. 257 * <p> 258 * Many users of time-zones use short abbreviations, such as PST for 259 * 'Pacific Standard Time' and PDT for 'Pacific Daylight Time'. 260 * These abbreviations are not unique, and so cannot be used as IDs. 261 * This method allows a map of string to time-zone to be setup and reused 262 * within an application. 263 * 264 * @param zoneId the time-zone ID, not null 265 * @param aliasMap a map of alias zone IDs (typically abbreviations) to real zone IDs, not null 266 * @return the zone ID, not null 267 * @throws DateTimeException if the zone ID has an invalid format 268 * @throws ZoneRulesException if the zone region ID cannot be found 269 */ 270 public static ZoneId of(String zoneId, Map<String, String> aliasMap) { 271 Objects.requireNonNull(zoneId, "zoneId"); 272 Objects.requireNonNull(aliasMap, "aliasMap"); 273 String id = aliasMap.get(zoneId); 274 id = (id != null ? id : zoneId); 275 return of(id); 276 } 277 278 /** 279 * Obtains an instance of {@code ZoneId} from an ID ensuring that the 280 * ID is valid and available for use. 281 * <p> 282 * This method parses the ID, applies any appropriate normalization, and validates it 283 * against the known set of IDs for which rules are available. 284 * <p> 285 * An ID is parsed as though it is an offset ID if it starts with 'UTC', 'GMT', '+' 286 * or '-', or if it has less then two letters. 287 * The offset of {@link ZoneOffset#UTC zero} may be represented in multiple ways, 288 * including 'Z', 'UTC', 'GMT', 'UTC0' 'GMT0', '+00:00', '-00:00' and 'UTC+00:00'. 289 * <p> 290 * Eight forms of ID are recognized, where '{offset}' means to parse using {@link ZoneOffset#of(String)}: 291 * <p><ul> 292 * <li><code>{offset}</code> - a {@link ZoneOffset} ID, such as 'Z' or '+02:00' 293 * <li><code>UTC</code> - alternate form of a {@code ZoneOffset} ID equal to 'Z' 294 * <li><code>UTC0</code> - alternate form of a {@code ZoneOffset} ID equal to 'Z' 295 * <li><code>UTC{offset}</code> - alternate form of a {@code ZoneOffset} ID equal to '{offset}' 296 * <li><code>GMT</code> - alternate form of a {@code ZoneOffset} ID equal to 'Z' 297 * <li><code>GMT0</code> - alternate form of a {@code ZoneOffset} ID equal to 'Z' 298 * <li><code>GMT{offset}</code> - alternate form of a {@code ZoneOffset} ID equal to '{offset}'r 299 * <li><code>{regionID}</code> - full region ID, loaded from configuration 300 * </ul><p> 301 * Region IDs must match the regular expression <code>[A-Za-z][A-Za-z0-9~/._+-]+</code>. 302 * <p> 303 * The detailed format of the region ID depends on the group supplying the data. 304 * The default set of data is supplied by the IANA Time Zone Database (TZDB) 305 * This has region IDs of the form '{area}/{city}', such as 'Europe/Paris' or 'America/New_York'. 306 * This is compatible with most IDs from {@link java.util.TimeZone}. 307 * 308 * @param zoneId the time-zone ID, not null 309 * @return the zone ID, not null 310 * @throws DateTimeException if the zone ID has an invalid format 311 * @throws ZoneRulesException if the zone region ID cannot be found 312 */ 313 public static ZoneId of(String zoneId) { 314 Objects.requireNonNull(zoneId, "zoneId"); 315 if (zoneId.length() <= 1 || zoneId.startsWith("+") || zoneId.startsWith("-")) { 316 return ZoneOffset.of(zoneId); 317 } else if (zoneId.startsWith("UTC") || zoneId.startsWith("GMT")) { 318 if (zoneId.length() == 3 || (zoneId.length() == 4 && zoneId.charAt(3) == '0')) { 319 return ZoneOffset.UTC; 320 } 321 return ZoneOffset.of(zoneId.substring(3)); 322 } 323 return ZoneRegion.ofId(zoneId, true); 324 } 325 326 //----------------------------------------------------------------------- 327 /** 328 * Obtains an instance of {@code ZoneId} from a temporal object. 329 * <p> 330 * A {@code TemporalAccessor} represents some form of date and time information. 331 * This factory converts the arbitrary temporal object to an instance of {@code ZoneId}. 332 * <p> 333 * The conversion will try to obtain the zone in a way that favours region-based 334 * zones over offset-based zones using {@link TemporalQueries#zone()}. 335 * <p> 336 * This method matches the signature of the functional interface {@link TemporalQuery} 337 * allowing it to be used in queries via method reference, {@code ZoneId::from}. 338 * 339 * @param temporal the temporal object to convert, not null 340 * @return the zone ID, not null 341 * @throws DateTimeException if unable to convert to a {@code ZoneId} 342 */ 343 public static ZoneId from(TemporalAccessor temporal) { 344 ZoneId obj = temporal.query(TemporalQueries.zone()); 345 if (obj == null) { 346 throw new DateTimeException("Unable to obtain ZoneId from TemporalAccessor: " + temporal.getClass()); 347 } 348 return obj; 349 } 350 351 //----------------------------------------------------------------------- 352 /** 353 * Constructor only accessible within the package. 354 */ 355 ZoneId() { 356 if (getClass() != ZoneOffset.class && getClass() != ZoneRegion.class) { 357 throw new AssertionError("Invalid subclass"); 358 } 359 } 360 361 //----------------------------------------------------------------------- 362 /** 363 * Gets the unique time-zone ID. 364 * <p> 365 * This ID uniquely defines this object. 366 * The format of an offset based ID is defined by {@link ZoneOffset#getId()}. 367 * 368 * @return the time-zone unique ID, not null 369 */ 370 public abstract String getId(); 371 372 //----------------------------------------------------------------------- 373 /** 374 * Gets the time-zone rules for this ID allowing calculations to be performed. 375 * <p> 376 * The rules provide the functionality associated with a time-zone, 377 * such as finding the offset for a given instant or local date-time. 378 * <p> 379 * A time-zone can be invalid if it is deserialized in a JVM which does not 380 * have the same rules loaded as the JVM that stored it. In this case, calling 381 * this method will throw an exception. 382 * <p> 383 * The rules are supplied by {@link ZoneRulesProvider}. An advanced provider may 384 * support dynamic updates to the rules without restarting the JVM. 385 * If so, then the result of this method may change over time. 386 * Each individual call will be still remain thread-safe. 387 * <p> 388 * {@link ZoneOffset} will always return a set of rules where the offset never changes. 389 * 390 * @return the rules, not null 391 * @throws DateTimeException if no rules are available for this ID 392 */ 393 public abstract ZoneRules getRules(); 394 395 //----------------------------------------------------------------------- 396 /** 397 * Gets the textual representation of the zone, such as 'British Time' or 398 * '+02:00'. 399 * <p> 400 * This returns a textual description for the time-zone ID. 401 * <p> 402 * If no textual mapping is found then the {@link #getId() full ID} is returned. 403 * 404 * @param style the length of the text required, not null 405 * @param locale the locale to use, not null 406 * @return the text value of the zone, not null 407 */ 408 public String getText(TextStyle style, Locale locale) { 409 return new DateTimeFormatterBuilder().appendZoneText(style).toFormatter(locale).print(new DefaultInterfaceTemporalAccessor() { 410 @Override 411 public boolean isSupported(TemporalField field) { 412 return false; 413 } 414 @Override 415 public long getLong(TemporalField field) { 416 throw new DateTimeException("Unsupported field: " + field); 417 } 418 @SuppressWarnings("unchecked") 419 @Override 420 public <R> R query(TemporalQuery<R> query) { 421 if (query == TemporalQueries.zoneId()) { 422 return (R) ZoneId.this; 423 } 424 return super.query(query); 425 } 426 }); 427 } 428 429 //----------------------------------------------------------------------- 430 /** 431 * Checks if this time-zone ID is equal to another time-zone ID. 432 * <p> 433 * The comparison is based on the ID. 434 * 435 * @param obj the object to check, null returns false 436 * @return true if this is equal to the other time-zone ID 437 */ 438 @Override 439 public boolean equals(Object obj) { 440 if (this == obj) { 441 return true; 442 } 443 if (obj instanceof ZoneId) { 444 ZoneId other = (ZoneId) obj; 445 return getId().equals(other.getId()); 446 } 447 return false; 448 } 449 450 /** 451 * A hash code for this time-zone ID. 452 * 453 * @return a suitable hash code 454 */ 455 @Override 456 public int hashCode() { 457 return getId().hashCode(); 458 } 459 460 //----------------------------------------------------------------------- 461 /** 462 * Outputs this zone as a {@code String}, using the ID. 463 * 464 * @return a string representation of this time-zone ID, not null 465 */ 466 @Override 467 public String toString() { 468 return getId(); 469 } 470 471 //----------------------------------------------------------------------- 472 abstract void write(DataOutput out) throws IOException; 473 474}