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