1 /*
2  * Copyright (c) 2012, 2019, 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 static java.time.temporal.ChronoField.INSTANT_SECONDS;
65 import static java.time.temporal.ChronoField.NANO_OF_SECOND;
66 import static java.time.temporal.ChronoField.OFFSET_SECONDS;
67 
68 import java.io.DataOutput;
69 import java.io.IOException;
70 import java.io.ObjectInput;
71 import java.io.InvalidObjectException;
72 import java.io.ObjectInputStream;
73 import java.io.Serializable;
74 import java.time.chrono.ChronoZonedDateTime;
75 import java.time.format.DateTimeFormatter;
76 import java.time.format.DateTimeParseException;
77 import java.time.temporal.ChronoField;
78 import java.time.temporal.ChronoUnit;
79 import java.time.temporal.Temporal;
80 import java.time.temporal.TemporalAccessor;
81 import java.time.temporal.TemporalAdjuster;
82 import java.time.temporal.TemporalAmount;
83 import java.time.temporal.TemporalField;
84 import java.time.temporal.TemporalQueries;
85 import java.time.temporal.TemporalQuery;
86 import java.time.temporal.TemporalUnit;
87 import java.time.temporal.UnsupportedTemporalTypeException;
88 import java.time.temporal.ValueRange;
89 import java.time.zone.ZoneOffsetTransition;
90 import java.time.zone.ZoneRules;
91 import java.util.List;
92 import java.util.Objects;
93 
94 // Android-changed: removed ValueBased paragraph.
95 /**
96  * A date-time with a time-zone in the ISO-8601 calendar system,
97  * such as {@code 2007-12-03T10:15:30+01:00 Europe/Paris}.
98  * <p>
99  * {@code ZonedDateTime} is an immutable representation of a date-time with a time-zone.
100  * This class stores all date and time fields, to a precision of nanoseconds,
101  * and a time-zone, with a zone offset used to handle ambiguous local date-times.
102  * For example, the value
103  * "2nd October 2007 at 13:45.30.123456789 +02:00 in the Europe/Paris time-zone"
104  * can be stored in a {@code ZonedDateTime}.
105  * <p>
106  * This class handles conversion from the local time-line of {@code LocalDateTime}
107  * to the instant time-line of {@code Instant}.
108  * The difference between the two time-lines is the offset from UTC/Greenwich,
109  * represented by a {@code ZoneOffset}.
110  * <p>
111  * Converting between the two time-lines involves calculating the offset using the
112  * {@link ZoneRules rules} accessed from the {@code ZoneId}.
113  * Obtaining the offset for an instant is simple, as there is exactly one valid
114  * offset for each instant. By contrast, obtaining the offset for a local date-time
115  * is not straightforward. There are three cases:
116  * <ul>
117  * <li>Normal, with one valid offset. For the vast majority of the year, the normal
118  *  case applies, where there is a single valid offset for the local date-time.</li>
119  * <li>Gap, with zero valid offsets. This is when clocks jump forward typically
120  *  due to the spring daylight savings change from "winter" to "summer".
121  *  In a gap there are local date-time values with no valid offset.</li>
122  * <li>Overlap, with two valid offsets. This is when clocks are set back typically
123  *  due to the autumn daylight savings change from "summer" to "winter".
124  *  In an overlap there are local date-time values with two valid offsets.</li>
125  * </ul>
126  * <p>
127  * Any method that converts directly or implicitly from a local date-time to an
128  * instant by obtaining the offset has the potential to be complicated.
129  * <p>
130  * For Gaps, the general strategy is that if the local date-time falls in the
131  * middle of a Gap, then the resulting zoned date-time will have a local date-time
132  * shifted forwards by the length of the Gap, resulting in a date-time in the later
133  * offset, typically "summer" time.
134  * <p>
135  * For Overlaps, the general strategy is that if the local date-time falls in the
136  * middle of an Overlap, then the previous offset will be retained. If there is no
137  * previous offset, or the previous offset is invalid, then the earlier offset is
138  * used, typically "summer" time.. Two additional methods,
139  * {@link #withEarlierOffsetAtOverlap()} and {@link #withLaterOffsetAtOverlap()},
140  * help manage the case of an overlap.
141  * <p>
142  * In terms of design, this class should be viewed primarily as the combination
143  * of a {@code LocalDateTime} and a {@code ZoneId}. The {@code ZoneOffset} is
144  * a vital, but secondary, piece of information, used to ensure that the class
145  * represents an instant, especially during a daylight savings overlap.
146  *
147  * @implSpec
148  * A {@code ZonedDateTime} holds state equivalent to three separate objects,
149  * a {@code LocalDateTime}, a {@code ZoneId} and the resolved {@code ZoneOffset}.
150  * The offset and local date-time are used to define an instant when necessary.
151  * The zone ID is used to obtain the rules for how and when the offset changes.
152  * The offset cannot be freely set, as the zone controls which offsets are valid.
153  * <p>
154  * This class is immutable and thread-safe.
155  *
156  * @since 1.8
157  */
158 public final class ZonedDateTime
159         implements Temporal, ChronoZonedDateTime<LocalDate>, Serializable {
160 
161     /**
162      * Serialization version.
163      */
164     @java.io.Serial
165     private static final long serialVersionUID = -6260982410461394882L;
166 
167     /**
168      * The local date-time.
169      */
170     private final LocalDateTime dateTime;
171     /**
172      * The offset from UTC/Greenwich.
173      */
174     private final ZoneOffset offset;
175     /**
176      * The time-zone.
177      */
178     private final ZoneId zone;
179 
180     //-----------------------------------------------------------------------
181     /**
182      * Obtains the current date-time from the system clock in the default time-zone.
183      * <p>
184      * This will query the {@link Clock#systemDefaultZone() system clock} in the default
185      * time-zone to obtain the current date-time.
186      * The zone and offset will be set based on the time-zone in the clock.
187      * <p>
188      * Using this method will prevent the ability to use an alternate clock for testing
189      * because the clock is hard-coded.
190      *
191      * @return the current date-time using the system clock, not null
192      */
now()193     public static ZonedDateTime now() {
194         return now(Clock.systemDefaultZone());
195     }
196 
197     /**
198      * Obtains the current date-time from the system clock in the specified time-zone.
199      * <p>
200      * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date-time.
201      * Specifying the time-zone avoids dependence on the default time-zone.
202      * The offset will be calculated from the specified time-zone.
203      * <p>
204      * Using this method will prevent the ability to use an alternate clock for testing
205      * because the clock is hard-coded.
206      *
207      * @param zone  the zone ID to use, not null
208      * @return the current date-time using the system clock, not null
209      */
now(ZoneId zone)210     public static ZonedDateTime now(ZoneId zone) {
211         return now(Clock.system(zone));
212     }
213 
214     /**
215      * Obtains the current date-time from the specified clock.
216      * <p>
217      * This will query the specified clock to obtain the current date-time.
218      * The zone and offset will be set based on the time-zone in the clock.
219      * <p>
220      * Using this method allows the use of an alternate clock for testing.
221      * The alternate clock may be introduced using {@link Clock dependency injection}.
222      *
223      * @param clock  the clock to use, not null
224      * @return the current date-time, not null
225      */
now(Clock clock)226     public static ZonedDateTime now(Clock clock) {
227         Objects.requireNonNull(clock, "clock");
228         final Instant now = clock.instant();  // called once
229         return ofInstant(now, clock.getZone());
230     }
231 
232     //-----------------------------------------------------------------------
233     /**
234      * Obtains an instance of {@code ZonedDateTime} from a local date and time.
235      * <p>
236      * This creates a zoned date-time matching the input local date and time as closely as possible.
237      * Time-zone rules, such as daylight savings, mean that not every local date-time
238      * is valid for the specified zone, thus the local date-time may be adjusted.
239      * <p>
240      * The local date time and first combined to form a local date-time.
241      * The local date-time is then resolved to a single instant on the time-line.
242      * This is achieved by finding a valid offset from UTC/Greenwich for the local
243      * date-time as defined by the {@link ZoneRules rules} of the zone ID.
244      *<p>
245      * In most cases, there is only one valid offset for a local date-time.
246      * In the case of an overlap, when clocks are set back, there are two valid offsets.
247      * This method uses the earlier offset typically corresponding to "summer".
248      * <p>
249      * In the case of a gap, when clocks jump forward, there is no valid offset.
250      * Instead, the local date-time is adjusted to be later by the length of the gap.
251      * For a typical one hour daylight savings change, the local date-time will be
252      * moved one hour later into the offset typically corresponding to "summer".
253      *
254      * @param date  the local date, not null
255      * @param time  the local time, not null
256      * @param zone  the time-zone, not null
257      * @return the offset date-time, not null
258      */
of(LocalDate date, LocalTime time, ZoneId zone)259     public static ZonedDateTime of(LocalDate date, LocalTime time, ZoneId zone) {
260         return of(LocalDateTime.of(date, time), zone);
261     }
262 
263     /**
264      * Obtains an instance of {@code ZonedDateTime} from a local date-time.
265      * <p>
266      * This creates a zoned date-time matching the input local date-time as closely as possible.
267      * Time-zone rules, such as daylight savings, mean that not every local date-time
268      * is valid for the specified zone, thus the local date-time may be adjusted.
269      * <p>
270      * The local date-time is resolved to a single instant on the time-line.
271      * This is achieved by finding a valid offset from UTC/Greenwich for the local
272      * date-time as defined by the {@link ZoneRules rules} of the zone ID.
273      *<p>
274      * In most cases, there is only one valid offset for a local date-time.
275      * In the case of an overlap, when clocks are set back, there are two valid offsets.
276      * This method uses the earlier offset typically corresponding to "summer".
277      * <p>
278      * In the case of a gap, when clocks jump forward, there is no valid offset.
279      * Instead, the local date-time is adjusted to be later by the length of the gap.
280      * For a typical one hour daylight savings change, the local date-time will be
281      * moved one hour later into the offset typically corresponding to "summer".
282      *
283      * @param localDateTime  the local date-time, not null
284      * @param zone  the time-zone, not null
285      * @return the zoned date-time, not null
286      */
of(LocalDateTime localDateTime, ZoneId zone)287     public static ZonedDateTime of(LocalDateTime localDateTime, ZoneId zone) {
288         return ofLocal(localDateTime, zone, null);
289     }
290 
291     /**
292      * Obtains an instance of {@code ZonedDateTime} from a year, month, day,
293      * hour, minute, second, nanosecond and time-zone.
294      * <p>
295      * This creates a zoned date-time matching the local date-time of the seven
296      * specified fields as closely as possible.
297      * Time-zone rules, such as daylight savings, mean that not every local date-time
298      * is valid for the specified zone, thus the local date-time may be adjusted.
299      * <p>
300      * The local date-time is resolved to a single instant on the time-line.
301      * This is achieved by finding a valid offset from UTC/Greenwich for the local
302      * date-time as defined by the {@link ZoneRules rules} of the zone ID.
303      *<p>
304      * In most cases, there is only one valid offset for a local date-time.
305      * In the case of an overlap, when clocks are set back, there are two valid offsets.
306      * This method uses the earlier offset typically corresponding to "summer".
307      * <p>
308      * In the case of a gap, when clocks jump forward, there is no valid offset.
309      * Instead, the local date-time is adjusted to be later by the length of the gap.
310      * For a typical one hour daylight savings change, the local date-time will be
311      * moved one hour later into the offset typically corresponding to "summer".
312      * <p>
313      * This method exists primarily for writing test cases.
314      * Non test-code will typically use other methods to create an offset time.
315      * {@code LocalDateTime} has five additional convenience variants of the
316      * equivalent factory method taking fewer arguments.
317      * They are not provided here to reduce the footprint of the API.
318      *
319      * @param year  the year to represent, from MIN_YEAR to MAX_YEAR
320      * @param month  the month-of-year to represent, from 1 (January) to 12 (December)
321      * @param dayOfMonth  the day-of-month to represent, from 1 to 31
322      * @param hour  the hour-of-day to represent, from 0 to 23
323      * @param minute  the minute-of-hour to represent, from 0 to 59
324      * @param second  the second-of-minute to represent, from 0 to 59
325      * @param nanoOfSecond  the nano-of-second to represent, from 0 to 999,999,999
326      * @param zone  the time-zone, not null
327      * @return the offset date-time, not null
328      * @throws DateTimeException if the value of any field is out of range, or
329      *  if the day-of-month is invalid for the month-year
330      */
of( int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond, ZoneId zone)331     public static ZonedDateTime of(
332             int year, int month, int dayOfMonth,
333             int hour, int minute, int second, int nanoOfSecond, ZoneId zone) {
334         LocalDateTime dt = LocalDateTime.of(year, month, dayOfMonth, hour, minute, second, nanoOfSecond);
335         return ofLocal(dt, zone, null);
336     }
337 
338     /**
339      * Obtains an instance of {@code ZonedDateTime} from a local date-time
340      * using the preferred offset if possible.
341      * <p>
342      * The local date-time is resolved to a single instant on the time-line.
343      * This is achieved by finding a valid offset from UTC/Greenwich for the local
344      * date-time as defined by the {@link ZoneRules rules} of the zone ID.
345      *<p>
346      * In most cases, there is only one valid offset for a local date-time.
347      * In the case of an overlap, where clocks are set back, there are two valid offsets.
348      * If the preferred offset is one of the valid offsets then it is used.
349      * Otherwise the earlier valid offset is used, typically corresponding to "summer".
350      * <p>
351      * In the case of a gap, where clocks jump forward, there is no valid offset.
352      * Instead, the local date-time is adjusted to be later by the length of the gap.
353      * For a typical one hour daylight savings change, the local date-time will be
354      * moved one hour later into the offset typically corresponding to "summer".
355      *
356      * @param localDateTime  the local date-time, not null
357      * @param zone  the time-zone, not null
358      * @param preferredOffset  the zone offset, null if no preference
359      * @return the zoned date-time, not null
360      */
ofLocal(LocalDateTime localDateTime, ZoneId zone, ZoneOffset preferredOffset)361     public static ZonedDateTime ofLocal(LocalDateTime localDateTime, ZoneId zone, ZoneOffset preferredOffset) {
362         Objects.requireNonNull(localDateTime, "localDateTime");
363         Objects.requireNonNull(zone, "zone");
364         if (zone instanceof ZoneOffset) {
365             return new ZonedDateTime(localDateTime, (ZoneOffset) zone, zone);
366         }
367         ZoneRules rules = zone.getRules();
368         List<ZoneOffset> validOffsets = rules.getValidOffsets(localDateTime);
369         ZoneOffset offset;
370         if (validOffsets.size() == 1) {
371             offset = validOffsets.get(0);
372         } else if (validOffsets.size() == 0) {
373             ZoneOffsetTransition trans = rules.getTransition(localDateTime);
374             localDateTime = localDateTime.plusSeconds(trans.getDuration().getSeconds());
375             offset = trans.getOffsetAfter();
376         } else {
377             if (preferredOffset != null && validOffsets.contains(preferredOffset)) {
378                 offset = preferredOffset;
379             } else {
380                 offset = Objects.requireNonNull(validOffsets.get(0), "offset");  // protect against bad ZoneRules
381             }
382         }
383         return new ZonedDateTime(localDateTime, offset, zone);
384     }
385 
386     //-----------------------------------------------------------------------
387     /**
388      * Obtains an instance of {@code ZonedDateTime} from an {@code Instant}.
389      * <p>
390      * This creates a zoned date-time with the same instant as that specified.
391      * Calling {@link #toInstant()} will return an instant equal to the one used here.
392      * <p>
393      * Converting an instant to a zoned date-time is simple as there is only one valid
394      * offset for each instant.
395      *
396      * @param instant  the instant to create the date-time from, not null
397      * @param zone  the time-zone, not null
398      * @return the zoned date-time, not null
399      * @throws DateTimeException if the result exceeds the supported range
400      */
ofInstant(Instant instant, ZoneId zone)401     public static ZonedDateTime ofInstant(Instant instant, ZoneId zone) {
402         Objects.requireNonNull(instant, "instant");
403         Objects.requireNonNull(zone, "zone");
404         return create(instant.getEpochSecond(), instant.getNano(), zone);
405     }
406 
407     /**
408      * Obtains an instance of {@code ZonedDateTime} from the instant formed by combining
409      * the local date-time and offset.
410      * <p>
411      * This creates a zoned date-time by {@link LocalDateTime#toInstant(ZoneOffset) combining}
412      * the {@code LocalDateTime} and {@code ZoneOffset}.
413      * This combination uniquely specifies an instant without ambiguity.
414      * <p>
415      * Converting an instant to a zoned date-time is simple as there is only one valid
416      * offset for each instant. If the valid offset is different to the offset specified,
417      * then the date-time and offset of the zoned date-time will differ from those specified.
418      * <p>
419      * If the {@code ZoneId} to be used is a {@code ZoneOffset}, this method is equivalent
420      * to {@link #of(LocalDateTime, ZoneId)}.
421      *
422      * @param localDateTime  the local date-time, not null
423      * @param offset  the zone offset, not null
424      * @param zone  the time-zone, not null
425      * @return the zoned date-time, not null
426      */
ofInstant(LocalDateTime localDateTime, ZoneOffset offset, ZoneId zone)427     public static ZonedDateTime ofInstant(LocalDateTime localDateTime, ZoneOffset offset, ZoneId zone) {
428         Objects.requireNonNull(localDateTime, "localDateTime");
429         Objects.requireNonNull(offset, "offset");
430         Objects.requireNonNull(zone, "zone");
431         if (zone.getRules().isValidOffset(localDateTime, offset)) {
432             return new ZonedDateTime(localDateTime, offset, zone);
433         }
434         return create(localDateTime.toEpochSecond(offset), localDateTime.getNano(), zone);
435     }
436 
437     /**
438      * Obtains an instance of {@code ZonedDateTime} using seconds from the
439      * epoch of 1970-01-01T00:00:00Z.
440      *
441      * @param epochSecond  the number of seconds from the epoch of 1970-01-01T00:00:00Z
442      * @param nanoOfSecond  the nanosecond within the second, from 0 to 999,999,999
443      * @param zone  the time-zone, not null
444      * @return the zoned date-time, not null
445      * @throws DateTimeException if the result exceeds the supported range
446      */
create(long epochSecond, int nanoOfSecond, ZoneId zone)447     private static ZonedDateTime create(long epochSecond, int nanoOfSecond, ZoneId zone) {
448         ZoneRules rules = zone.getRules();
449         Instant instant = Instant.ofEpochSecond(epochSecond, nanoOfSecond);  // TODO: rules should be queryable by epochSeconds
450         ZoneOffset offset = rules.getOffset(instant);
451         LocalDateTime ldt = LocalDateTime.ofEpochSecond(epochSecond, nanoOfSecond, offset);
452         return new ZonedDateTime(ldt, offset, zone);
453     }
454 
455     //-----------------------------------------------------------------------
456     /**
457      * Obtains an instance of {@code ZonedDateTime} strictly validating the
458      * combination of local date-time, offset and zone ID.
459      * <p>
460      * This creates a zoned date-time ensuring that the offset is valid for the
461      * local date-time according to the rules of the specified zone.
462      * If the offset is invalid, an exception is thrown.
463      *
464      * @param localDateTime  the local date-time, not null
465      * @param offset  the zone offset, not null
466      * @param zone  the time-zone, not null
467      * @return the zoned date-time, not null
468      * @throws DateTimeException if the combination of arguments is invalid
469      */
ofStrict(LocalDateTime localDateTime, ZoneOffset offset, ZoneId zone)470     public static ZonedDateTime ofStrict(LocalDateTime localDateTime, ZoneOffset offset, ZoneId zone) {
471         Objects.requireNonNull(localDateTime, "localDateTime");
472         Objects.requireNonNull(offset, "offset");
473         Objects.requireNonNull(zone, "zone");
474         ZoneRules rules = zone.getRules();
475         if (rules.isValidOffset(localDateTime, offset) == false) {
476             ZoneOffsetTransition trans = rules.getTransition(localDateTime);
477             if (trans != null && trans.isGap()) {
478                 // error message says daylight savings for simplicity
479                 // even though there are other kinds of gaps
480                 throw new DateTimeException("LocalDateTime '" + localDateTime +
481                         "' does not exist in zone '" + zone +
482                         "' due to a gap in the local time-line, typically caused by daylight savings");
483             }
484             throw new DateTimeException("ZoneOffset '" + offset + "' is not valid for LocalDateTime '" +
485                     localDateTime + "' in zone '" + zone + "'");
486         }
487         return new ZonedDateTime(localDateTime, offset, zone);
488     }
489 
490     /**
491      * Obtains an instance of {@code ZonedDateTime} leniently, for advanced use cases,
492      * allowing any combination of local date-time, offset and zone ID.
493      * <p>
494      * This creates a zoned date-time with no checks other than no nulls.
495      * This means that the resulting zoned date-time may have an offset that is in conflict
496      * with the zone ID.
497      * <p>
498      * This method is intended for advanced use cases.
499      * For example, consider the case where a zoned date-time with valid fields is created
500      * and then stored in a database or serialization-based store. At some later point,
501      * the object is then re-loaded. However, between those points in time, the government
502      * that defined the time-zone has changed the rules, such that the originally stored
503      * local date-time now does not occur. This method can be used to create the object
504      * in an "invalid" state, despite the change in rules.
505      *
506      * @param localDateTime  the local date-time, not null
507      * @param offset  the zone offset, not null
508      * @param zone  the time-zone, not null
509      * @return the zoned date-time, not null
510      */
ofLenient(LocalDateTime localDateTime, ZoneOffset offset, ZoneId zone)511     private static ZonedDateTime ofLenient(LocalDateTime localDateTime, ZoneOffset offset, ZoneId zone) {
512         Objects.requireNonNull(localDateTime, "localDateTime");
513         Objects.requireNonNull(offset, "offset");
514         Objects.requireNonNull(zone, "zone");
515         if (zone instanceof ZoneOffset && offset.equals(zone) == false) {
516             throw new IllegalArgumentException("ZoneId must match ZoneOffset");
517         }
518         return new ZonedDateTime(localDateTime, offset, zone);
519     }
520 
521     //-----------------------------------------------------------------------
522     /**
523      * Obtains an instance of {@code ZonedDateTime} from a temporal object.
524      * <p>
525      * This obtains a zoned date-time based on the specified temporal.
526      * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
527      * which this factory converts to an instance of {@code ZonedDateTime}.
528      * <p>
529      * The conversion will first obtain a {@code ZoneId} from the temporal object,
530      * falling back to a {@code ZoneOffset} if necessary. It will then try to obtain
531      * an {@code Instant}, falling back to a {@code LocalDateTime} if necessary.
532      * The result will be either the combination of {@code ZoneId} or {@code ZoneOffset}
533      * with {@code Instant} or {@code LocalDateTime}.
534      * Implementations are permitted to perform optimizations such as accessing
535      * those fields that are equivalent to the relevant objects.
536      * <p>
537      * This method matches the signature of the functional interface {@link TemporalQuery}
538      * allowing it to be used as a query via method reference, {@code ZonedDateTime::from}.
539      *
540      * @param temporal  the temporal object to convert, not null
541      * @return the zoned date-time, not null
542      * @throws DateTimeException if unable to convert to an {@code ZonedDateTime}
543      */
from(TemporalAccessor temporal)544     public static ZonedDateTime from(TemporalAccessor temporal) {
545         if (temporal instanceof ZonedDateTime) {
546             return (ZonedDateTime) temporal;
547         }
548         try {
549             ZoneId zone = ZoneId.from(temporal);
550             if (temporal.isSupported(INSTANT_SECONDS)) {
551                 long epochSecond = temporal.getLong(INSTANT_SECONDS);
552                 int nanoOfSecond = temporal.get(NANO_OF_SECOND);
553                 return create(epochSecond, nanoOfSecond, zone);
554             } else {
555                 LocalDate date = LocalDate.from(temporal);
556                 LocalTime time = LocalTime.from(temporal);
557                 return of(date, time, zone);
558             }
559         } catch (DateTimeException ex) {
560             throw new DateTimeException("Unable to obtain ZonedDateTime from TemporalAccessor: " +
561                     temporal + " of type " + temporal.getClass().getName(), ex);
562         }
563     }
564 
565     //-----------------------------------------------------------------------
566     /**
567      * Obtains an instance of {@code ZonedDateTime} from a text string such as
568      * {@code 2007-12-03T10:15:30+01:00[Europe/Paris]}.
569      * <p>
570      * The string must represent a valid date-time and is parsed using
571      * {@link java.time.format.DateTimeFormatter#ISO_ZONED_DATE_TIME}.
572      *
573      * @param text  the text to parse such as "2007-12-03T10:15:30+01:00[Europe/Paris]", not null
574      * @return the parsed zoned date-time, not null
575      * @throws DateTimeParseException if the text cannot be parsed
576      */
parse(CharSequence text)577     public static ZonedDateTime parse(CharSequence text) {
578         return parse(text, DateTimeFormatter.ISO_ZONED_DATE_TIME);
579     }
580 
581     /**
582      * Obtains an instance of {@code ZonedDateTime} from a text string using a specific formatter.
583      * <p>
584      * The text is parsed using the formatter, returning a date-time.
585      *
586      * @param text  the text to parse, not null
587      * @param formatter  the formatter to use, not null
588      * @return the parsed zoned date-time, not null
589      * @throws DateTimeParseException if the text cannot be parsed
590      */
parse(CharSequence text, DateTimeFormatter formatter)591     public static ZonedDateTime parse(CharSequence text, DateTimeFormatter formatter) {
592         Objects.requireNonNull(formatter, "formatter");
593         return formatter.parse(text, ZonedDateTime::from);
594     }
595 
596     //-----------------------------------------------------------------------
597     /**
598      * Constructor.
599      *
600      * @param dateTime  the date-time, validated as not null
601      * @param offset  the zone offset, validated as not null
602      * @param zone  the time-zone, validated as not null
603      */
ZonedDateTime(LocalDateTime dateTime, ZoneOffset offset, ZoneId zone)604     private ZonedDateTime(LocalDateTime dateTime, ZoneOffset offset, ZoneId zone) {
605         this.dateTime = dateTime;
606         this.offset = offset;
607         this.zone = zone;
608     }
609 
610     /**
611      * Resolves the new local date-time using this zone ID, retaining the offset if possible.
612      *
613      * @param newDateTime  the new local date-time, not null
614      * @return the zoned date-time, not null
615      */
resolveLocal(LocalDateTime newDateTime)616     private ZonedDateTime resolveLocal(LocalDateTime newDateTime) {
617         return ofLocal(newDateTime, zone, offset);
618     }
619 
620     /**
621      * Resolves the new local date-time using the offset to identify the instant.
622      *
623      * @param newDateTime  the new local date-time, not null
624      * @return the zoned date-time, not null
625      */
resolveInstant(LocalDateTime newDateTime)626     private ZonedDateTime resolveInstant(LocalDateTime newDateTime) {
627         return ofInstant(newDateTime, offset, zone);
628     }
629 
630     /**
631      * Resolves the offset into this zoned date-time for the with methods.
632      * <p>
633      * This typically ignores the offset, unless it can be used to switch offset in a DST overlap.
634      *
635      * @param offset  the offset, not null
636      * @return the zoned date-time, not null
637      */
resolveOffset(ZoneOffset offset)638     private ZonedDateTime resolveOffset(ZoneOffset offset) {
639         if (offset.equals(this.offset) == false && zone.getRules().isValidOffset(dateTime, offset)) {
640             return new ZonedDateTime(dateTime, offset, zone);
641         }
642         return this;
643     }
644 
645     //-----------------------------------------------------------------------
646     /**
647      * Checks if the specified field is supported.
648      * <p>
649      * This checks if this date-time can be queried for the specified field.
650      * If false, then calling the {@link #range(TemporalField) range},
651      * {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}
652      * methods will throw an exception.
653      * <p>
654      * If the field is a {@link ChronoField} then the query is implemented here.
655      * The supported fields are:
656      * <ul>
657      * <li>{@code NANO_OF_SECOND}
658      * <li>{@code NANO_OF_DAY}
659      * <li>{@code MICRO_OF_SECOND}
660      * <li>{@code MICRO_OF_DAY}
661      * <li>{@code MILLI_OF_SECOND}
662      * <li>{@code MILLI_OF_DAY}
663      * <li>{@code SECOND_OF_MINUTE}
664      * <li>{@code SECOND_OF_DAY}
665      * <li>{@code MINUTE_OF_HOUR}
666      * <li>{@code MINUTE_OF_DAY}
667      * <li>{@code HOUR_OF_AMPM}
668      * <li>{@code CLOCK_HOUR_OF_AMPM}
669      * <li>{@code HOUR_OF_DAY}
670      * <li>{@code CLOCK_HOUR_OF_DAY}
671      * <li>{@code AMPM_OF_DAY}
672      * <li>{@code DAY_OF_WEEK}
673      * <li>{@code ALIGNED_DAY_OF_WEEK_IN_MONTH}
674      * <li>{@code ALIGNED_DAY_OF_WEEK_IN_YEAR}
675      * <li>{@code DAY_OF_MONTH}
676      * <li>{@code DAY_OF_YEAR}
677      * <li>{@code EPOCH_DAY}
678      * <li>{@code ALIGNED_WEEK_OF_MONTH}
679      * <li>{@code ALIGNED_WEEK_OF_YEAR}
680      * <li>{@code MONTH_OF_YEAR}
681      * <li>{@code PROLEPTIC_MONTH}
682      * <li>{@code YEAR_OF_ERA}
683      * <li>{@code YEAR}
684      * <li>{@code ERA}
685      * <li>{@code INSTANT_SECONDS}
686      * <li>{@code OFFSET_SECONDS}
687      * </ul>
688      * All other {@code ChronoField} instances will return false.
689      * <p>
690      * If the field is not a {@code ChronoField}, then the result of this method
691      * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
692      * passing {@code this} as the argument.
693      * Whether the field is supported is determined by the field.
694      *
695      * @param field  the field to check, null returns false
696      * @return true if the field is supported on this date-time, false if not
697      */
698     @Override
isSupported(TemporalField field)699     public boolean isSupported(TemporalField field) {
700         return field instanceof ChronoField || (field != null && field.isSupportedBy(this));
701     }
702 
703     /**
704      * Checks if the specified unit is supported.
705      * <p>
706      * This checks if the specified unit can be added to, or subtracted from, this date-time.
707      * If false, then calling the {@link #plus(long, TemporalUnit)} and
708      * {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
709      * <p>
710      * If the unit is a {@link ChronoUnit} then the query is implemented here.
711      * The supported units are:
712      * <ul>
713      * <li>{@code NANOS}
714      * <li>{@code MICROS}
715      * <li>{@code MILLIS}
716      * <li>{@code SECONDS}
717      * <li>{@code MINUTES}
718      * <li>{@code HOURS}
719      * <li>{@code HALF_DAYS}
720      * <li>{@code DAYS}
721      * <li>{@code WEEKS}
722      * <li>{@code MONTHS}
723      * <li>{@code YEARS}
724      * <li>{@code DECADES}
725      * <li>{@code CENTURIES}
726      * <li>{@code MILLENNIA}
727      * <li>{@code ERAS}
728      * </ul>
729      * All other {@code ChronoUnit} instances will return false.
730      * <p>
731      * If the unit is not a {@code ChronoUnit}, then the result of this method
732      * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}
733      * passing {@code this} as the argument.
734      * Whether the unit is supported is determined by the unit.
735      *
736      * @param unit  the unit to check, null returns false
737      * @return true if the unit can be added/subtracted, false if not
738      */
739     @Override  // override for Javadoc
isSupported(TemporalUnit unit)740     public boolean isSupported(TemporalUnit unit) {
741         return ChronoZonedDateTime.super.isSupported(unit);
742     }
743 
744     //-----------------------------------------------------------------------
745     /**
746      * Gets the range of valid values for the specified field.
747      * <p>
748      * The range object expresses the minimum and maximum valid values for a field.
749      * This date-time is used to enhance the accuracy of the returned range.
750      * If it is not possible to return the range, because the field is not supported
751      * or for some other reason, an exception is thrown.
752      * <p>
753      * If the field is a {@link ChronoField} then the query is implemented here.
754      * The {@link #isSupported(TemporalField) supported fields} will return
755      * appropriate range instances.
756      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
757      * <p>
758      * If the field is not a {@code ChronoField}, then the result of this method
759      * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
760      * passing {@code this} as the argument.
761      * Whether the range can be obtained is determined by the field.
762      *
763      * @param field  the field to query the range for, not null
764      * @return the range of valid values for the field, not null
765      * @throws DateTimeException if the range for the field cannot be obtained
766      * @throws UnsupportedTemporalTypeException if the field is not supported
767      */
768     @Override
range(TemporalField field)769     public ValueRange range(TemporalField field) {
770         if (field instanceof ChronoField) {
771             if (field == INSTANT_SECONDS || field == OFFSET_SECONDS) {
772                 return field.range();
773             }
774             return dateTime.range(field);
775         }
776         return field.rangeRefinedBy(this);
777     }
778 
779     /**
780      * Gets the value of the specified field from this date-time as an {@code int}.
781      * <p>
782      * This queries this date-time for the value of the specified field.
783      * The returned value will always be within the valid range of values for the field.
784      * If it is not possible to return the value, because the field is not supported
785      * or for some other reason, an exception is thrown.
786      * <p>
787      * If the field is a {@link ChronoField} then the query is implemented here.
788      * The {@link #isSupported(TemporalField) supported fields} will return valid
789      * values based on this date-time, except {@code NANO_OF_DAY}, {@code MICRO_OF_DAY},
790      * {@code EPOCH_DAY}, {@code PROLEPTIC_MONTH} and {@code INSTANT_SECONDS} which are too
791      * large to fit in an {@code int} and throw an {@code UnsupportedTemporalTypeException}.
792      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
793      * <p>
794      * If the field is not a {@code ChronoField}, then the result of this method
795      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
796      * passing {@code this} as the argument. Whether the value can be obtained,
797      * and what the value represents, is determined by the field.
798      *
799      * @param field  the field to get, not null
800      * @return the value for the field
801      * @throws DateTimeException if a value for the field cannot be obtained or
802      *         the value is outside the range of valid values for the field
803      * @throws UnsupportedTemporalTypeException if the field is not supported or
804      *         the range of values exceeds an {@code int}
805      * @throws ArithmeticException if numeric overflow occurs
806      */
807     @Override  // override for Javadoc and performance
get(TemporalField field)808     public int get(TemporalField field) {
809         if (field instanceof ChronoField chronoField) {
810             switch (chronoField) {
811                 case INSTANT_SECONDS:
812                     throw new UnsupportedTemporalTypeException("Invalid field 'InstantSeconds' for get() method, use getLong() instead");
813                 case OFFSET_SECONDS:
814                     return getOffset().getTotalSeconds();
815             }
816             return dateTime.get(field);
817         }
818         return ChronoZonedDateTime.super.get(field);
819     }
820 
821     /**
822      * Gets the value of the specified field from this date-time as a {@code long}.
823      * <p>
824      * This queries this date-time for the value of the specified field.
825      * If it is not possible to return the value, because the field is not supported
826      * or for some other reason, an exception is thrown.
827      * <p>
828      * If the field is a {@link ChronoField} then the query is implemented here.
829      * The {@link #isSupported(TemporalField) supported fields} will return valid
830      * values based on this date-time.
831      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
832      * <p>
833      * If the field is not a {@code ChronoField}, then the result of this method
834      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
835      * passing {@code this} as the argument. Whether the value can be obtained,
836      * and what the value represents, is determined by the field.
837      *
838      * @param field  the field to get, not null
839      * @return the value for the field
840      * @throws DateTimeException if a value for the field cannot be obtained
841      * @throws UnsupportedTemporalTypeException if the field is not supported
842      * @throws ArithmeticException if numeric overflow occurs
843      */
844     @Override
getLong(TemporalField field)845     public long getLong(TemporalField field) {
846         if (field instanceof ChronoField chronoField) {
847             switch (chronoField) {
848                 case INSTANT_SECONDS: return toEpochSecond();
849                 case OFFSET_SECONDS: return getOffset().getTotalSeconds();
850             }
851             return dateTime.getLong(field);
852         }
853         return field.getFrom(this);
854     }
855 
856     //-----------------------------------------------------------------------
857     /**
858      * Gets the zone offset, such as '+01:00'.
859      * <p>
860      * This is the offset of the local date-time from UTC/Greenwich.
861      *
862      * @return the zone offset, not null
863      */
864     @Override
getOffset()865     public ZoneOffset getOffset() {
866         return offset;
867     }
868 
869     /**
870      * Returns a copy of this date-time changing the zone offset to the
871      * earlier of the two valid offsets at a local time-line overlap.
872      * <p>
873      * This method only has any effect when the local time-line overlaps, such as
874      * at an autumn daylight savings cutover. In this scenario, there are two
875      * valid offsets for the local date-time. Calling this method will return
876      * a zoned date-time with the earlier of the two selected.
877      * <p>
878      * If this method is called when it is not an overlap, {@code this}
879      * is returned.
880      * <p>
881      * This instance is immutable and unaffected by this method call.
882      *
883      * @return a {@code ZonedDateTime} based on this date-time with the earlier offset, not null
884      */
885     @Override
withEarlierOffsetAtOverlap()886     public ZonedDateTime withEarlierOffsetAtOverlap() {
887         ZoneOffsetTransition trans = getZone().getRules().getTransition(dateTime);
888         if (trans != null && trans.isOverlap()) {
889             ZoneOffset earlierOffset = trans.getOffsetBefore();
890             if (earlierOffset.equals(offset) == false) {
891                 return new ZonedDateTime(dateTime, earlierOffset, zone);
892             }
893         }
894         return this;
895     }
896 
897     /**
898      * Returns a copy of this date-time changing the zone offset to the
899      * later of the two valid offsets at a local time-line overlap.
900      * <p>
901      * This method only has any effect when the local time-line overlaps, such as
902      * at an autumn daylight savings cutover. In this scenario, there are two
903      * valid offsets for the local date-time. Calling this method will return
904      * a zoned date-time with the later of the two selected.
905      * <p>
906      * If this method is called when it is not an overlap, {@code this}
907      * is returned.
908      * <p>
909      * This instance is immutable and unaffected by this method call.
910      *
911      * @return a {@code ZonedDateTime} based on this date-time with the later offset, not null
912      */
913     @Override
withLaterOffsetAtOverlap()914     public ZonedDateTime withLaterOffsetAtOverlap() {
915         ZoneOffsetTransition trans = getZone().getRules().getTransition(toLocalDateTime());
916         if (trans != null) {
917             ZoneOffset laterOffset = trans.getOffsetAfter();
918             if (laterOffset.equals(offset) == false) {
919                 return new ZonedDateTime(dateTime, laterOffset, zone);
920             }
921         }
922         return this;
923     }
924 
925     //-----------------------------------------------------------------------
926     /**
927      * Gets the time-zone, such as 'Europe/Paris'.
928      * <p>
929      * This returns the zone ID. This identifies the time-zone {@link ZoneRules rules}
930      * that determine when and how the offset from UTC/Greenwich changes.
931      * <p>
932      * The zone ID may be same as the {@linkplain #getOffset() offset}.
933      * If this is true, then any future calculations, such as addition or subtraction,
934      * have no complex edge cases due to time-zone rules.
935      * See also {@link #withFixedOffsetZone()}.
936      *
937      * @return the time-zone, not null
938      */
939     @Override
getZone()940     public ZoneId getZone() {
941         return zone;
942     }
943 
944     /**
945      * Returns a copy of this date-time with a different time-zone,
946      * retaining the local date-time if possible.
947      * <p>
948      * This method changes the time-zone and retains the local date-time.
949      * The local date-time is only changed if it is invalid for the new zone,
950      * determined using the same approach as
951      * {@link #ofLocal(LocalDateTime, ZoneId, ZoneOffset)}.
952      * <p>
953      * To change the zone and adjust the local date-time,
954      * use {@link #withZoneSameInstant(ZoneId)}.
955      * <p>
956      * This instance is immutable and unaffected by this method call.
957      *
958      * @param zone  the time-zone to change to, not null
959      * @return a {@code ZonedDateTime} based on this date-time with the requested zone, not null
960      */
961     @Override
withZoneSameLocal(ZoneId zone)962     public ZonedDateTime withZoneSameLocal(ZoneId zone) {
963         Objects.requireNonNull(zone, "zone");
964         return this.zone.equals(zone) ? this : ofLocal(dateTime, zone, offset);
965     }
966 
967     /**
968      * Returns a copy of this date-time with a different time-zone,
969      * retaining the instant.
970      * <p>
971      * This method changes the time-zone and retains the instant.
972      * This normally results in a change to the local date-time.
973      * <p>
974      * This method is based on retaining the same instant, thus gaps and overlaps
975      * in the local time-line have no effect on the result.
976      * <p>
977      * To change the offset while keeping the local time,
978      * use {@link #withZoneSameLocal(ZoneId)}.
979      *
980      * @param zone  the time-zone to change to, not null
981      * @return a {@code ZonedDateTime} based on this date-time with the requested zone, not null
982      * @throws DateTimeException if the result exceeds the supported date range
983      */
984     @Override
withZoneSameInstant(ZoneId zone)985     public ZonedDateTime withZoneSameInstant(ZoneId zone) {
986         Objects.requireNonNull(zone, "zone");
987         return this.zone.equals(zone) ? this :
988             create(dateTime.toEpochSecond(offset), dateTime.getNano(), zone);
989     }
990 
991     /**
992      * Returns a copy of this date-time with the zone ID set to the offset.
993      * <p>
994      * This returns a zoned date-time where the zone ID is the same as {@link #getOffset()}.
995      * The local date-time, offset and instant of the result will be the same as in this date-time.
996      * <p>
997      * Setting the date-time to a fixed single offset means that any future
998      * calculations, such as addition or subtraction, have no complex edge cases
999      * due to time-zone rules.
1000      * This might also be useful when sending a zoned date-time across a network,
1001      * as most protocols, such as ISO-8601, only handle offsets,
1002      * and not region-based zone IDs.
1003      * <p>
1004      * This is equivalent to {@code ZonedDateTime.of(zdt.toLocalDateTime(), zdt.getOffset())}.
1005      *
1006      * @return a {@code ZonedDateTime} with the zone ID set to the offset, not null
1007      */
withFixedOffsetZone()1008     public ZonedDateTime withFixedOffsetZone() {
1009         return this.zone.equals(offset) ? this : new ZonedDateTime(dateTime, offset, offset);
1010     }
1011 
1012     //-----------------------------------------------------------------------
1013     /**
1014      * Gets the {@code LocalDateTime} part of this date-time.
1015      * <p>
1016      * This returns a {@code LocalDateTime} with the same year, month, day and time
1017      * as this date-time.
1018      *
1019      * @return the local date-time part of this date-time, not null
1020      */
1021     @Override  // override for return type
toLocalDateTime()1022     public LocalDateTime toLocalDateTime() {
1023         return dateTime;
1024     }
1025 
1026     //-----------------------------------------------------------------------
1027     /**
1028      * Gets the {@code LocalDate} part of this date-time.
1029      * <p>
1030      * This returns a {@code LocalDate} with the same year, month and day
1031      * as this date-time.
1032      *
1033      * @return the date part of this date-time, not null
1034      */
1035     @Override  // override for return type
toLocalDate()1036     public LocalDate toLocalDate() {
1037         return dateTime.toLocalDate();
1038     }
1039 
1040     /**
1041      * Gets the year field.
1042      * <p>
1043      * This method returns the primitive {@code int} value for the year.
1044      * <p>
1045      * The year returned by this method is proleptic as per {@code get(YEAR)}.
1046      * To obtain the year-of-era, use {@code get(YEAR_OF_ERA)}.
1047      *
1048      * @return the year, from MIN_YEAR to MAX_YEAR
1049      */
getYear()1050     public int getYear() {
1051         return dateTime.getYear();
1052     }
1053 
1054     /**
1055      * Gets the month-of-year field from 1 to 12.
1056      * <p>
1057      * This method returns the month as an {@code int} from 1 to 12.
1058      * Application code is frequently clearer if the enum {@link Month}
1059      * is used by calling {@link #getMonth()}.
1060      *
1061      * @return the month-of-year, from 1 to 12
1062      * @see #getMonth()
1063      */
getMonthValue()1064     public int getMonthValue() {
1065         return dateTime.getMonthValue();
1066     }
1067 
1068     /**
1069      * Gets the month-of-year field using the {@code Month} enum.
1070      * <p>
1071      * This method returns the enum {@link Month} for the month.
1072      * This avoids confusion as to what {@code int} values mean.
1073      * If you need access to the primitive {@code int} value then the enum
1074      * provides the {@link Month#getValue() int value}.
1075      *
1076      * @return the month-of-year, not null
1077      * @see #getMonthValue()
1078      */
getMonth()1079     public Month getMonth() {
1080         return dateTime.getMonth();
1081     }
1082 
1083     /**
1084      * Gets the day-of-month field.
1085      * <p>
1086      * This method returns the primitive {@code int} value for the day-of-month.
1087      *
1088      * @return the day-of-month, from 1 to 31
1089      */
getDayOfMonth()1090     public int getDayOfMonth() {
1091         return dateTime.getDayOfMonth();
1092     }
1093 
1094     /**
1095      * Gets the day-of-year field.
1096      * <p>
1097      * This method returns the primitive {@code int} value for the day-of-year.
1098      *
1099      * @return the day-of-year, from 1 to 365, or 366 in a leap year
1100      */
getDayOfYear()1101     public int getDayOfYear() {
1102         return dateTime.getDayOfYear();
1103     }
1104 
1105     /**
1106      * Gets the day-of-week field, which is an enum {@code DayOfWeek}.
1107      * <p>
1108      * This method returns the enum {@link DayOfWeek} for the day-of-week.
1109      * This avoids confusion as to what {@code int} values mean.
1110      * If you need access to the primitive {@code int} value then the enum
1111      * provides the {@link DayOfWeek#getValue() int value}.
1112      * <p>
1113      * Additional information can be obtained from the {@code DayOfWeek}.
1114      * This includes textual names of the values.
1115      *
1116      * @return the day-of-week, not null
1117      */
getDayOfWeek()1118     public DayOfWeek getDayOfWeek() {
1119         return dateTime.getDayOfWeek();
1120     }
1121 
1122     //-----------------------------------------------------------------------
1123     /**
1124      * Gets the {@code LocalTime} part of this date-time.
1125      * <p>
1126      * This returns a {@code LocalTime} with the same hour, minute, second and
1127      * nanosecond as this date-time.
1128      *
1129      * @return the time part of this date-time, not null
1130      */
1131     @Override  // override for Javadoc and performance
toLocalTime()1132     public LocalTime toLocalTime() {
1133         return dateTime.toLocalTime();
1134     }
1135 
1136     /**
1137      * Gets the hour-of-day field.
1138      *
1139      * @return the hour-of-day, from 0 to 23
1140      */
getHour()1141     public int getHour() {
1142         return dateTime.getHour();
1143     }
1144 
1145     /**
1146      * Gets the minute-of-hour field.
1147      *
1148      * @return the minute-of-hour, from 0 to 59
1149      */
getMinute()1150     public int getMinute() {
1151         return dateTime.getMinute();
1152     }
1153 
1154     /**
1155      * Gets the second-of-minute field.
1156      *
1157      * @return the second-of-minute, from 0 to 59
1158      */
getSecond()1159     public int getSecond() {
1160         return dateTime.getSecond();
1161     }
1162 
1163     /**
1164      * Gets the nano-of-second field.
1165      *
1166      * @return the nano-of-second, from 0 to 999,999,999
1167      */
getNano()1168     public int getNano() {
1169         return dateTime.getNano();
1170     }
1171 
1172     //-----------------------------------------------------------------------
1173     /**
1174      * Returns an adjusted copy of this date-time.
1175      * <p>
1176      * This returns a {@code ZonedDateTime}, based on this one, with the date-time adjusted.
1177      * The adjustment takes place using the specified adjuster strategy object.
1178      * Read the documentation of the adjuster to understand what adjustment will be made.
1179      * <p>
1180      * A simple adjuster might simply set the one of the fields, such as the year field.
1181      * A more complex adjuster might set the date to the last day of the month.
1182      * A selection of common adjustments is provided in
1183      * {@link java.time.temporal.TemporalAdjusters TemporalAdjusters}.
1184      * These include finding the "last day of the month" and "next Wednesday".
1185      * Key date-time classes also implement the {@code TemporalAdjuster} interface,
1186      * such as {@link Month} and {@link java.time.MonthDay MonthDay}.
1187      * The adjuster is responsible for handling special cases, such as the varying
1188      * lengths of month and leap years.
1189      * <p>
1190      * For example this code returns a date on the last day of July:
1191      * <pre>
1192      *  import static java.time.Month.*;
1193      *  import static java.time.temporal.TemporalAdjusters.*;
1194      *
1195      *  result = zonedDateTime.with(JULY).with(lastDayOfMonth());
1196      * </pre>
1197      * <p>
1198      * The classes {@link LocalDate} and {@link LocalTime} implement {@code TemporalAdjuster},
1199      * thus this method can be used to change the date, time or offset:
1200      * <pre>
1201      *  result = zonedDateTime.with(date);
1202      *  result = zonedDateTime.with(time);
1203      * </pre>
1204      * <p>
1205      * {@link ZoneOffset} also implements {@code TemporalAdjuster} however using it
1206      * as an argument typically has no effect. The offset of a {@code ZonedDateTime} is
1207      * controlled primarily by the time-zone. As such, changing the offset does not generally
1208      * make sense, because there is only one valid offset for the local date-time and zone.
1209      * If the zoned date-time is in a daylight savings overlap, then the offset is used
1210      * to switch between the two valid offsets. In all other cases, the offset is ignored.
1211      * <p>
1212      * The result of this method is obtained by invoking the
1213      * {@link TemporalAdjuster#adjustInto(Temporal)} method on the
1214      * specified adjuster passing {@code this} as the argument.
1215      * <p>
1216      * This instance is immutable and unaffected by this method call.
1217      *
1218      * @param adjuster the adjuster to use, not null
1219      * @return a {@code ZonedDateTime} based on {@code this} with the adjustment made, not null
1220      * @throws DateTimeException if the adjustment cannot be made
1221      * @throws ArithmeticException if numeric overflow occurs
1222      */
1223     @Override
with(TemporalAdjuster adjuster)1224     public ZonedDateTime with(TemporalAdjuster adjuster) {
1225         // optimizations
1226         if (adjuster instanceof LocalDate) {
1227             return resolveLocal(LocalDateTime.of((LocalDate) adjuster, dateTime.toLocalTime()));
1228         } else if (adjuster instanceof LocalTime) {
1229             return resolveLocal(LocalDateTime.of(dateTime.toLocalDate(), (LocalTime) adjuster));
1230         } else if (adjuster instanceof LocalDateTime) {
1231             return resolveLocal((LocalDateTime) adjuster);
1232         } else if (adjuster instanceof OffsetDateTime odt) {
1233             return ofLocal(odt.toLocalDateTime(), zone, odt.getOffset());
1234         } else if (adjuster instanceof Instant instant) {
1235             return create(instant.getEpochSecond(), instant.getNano(), zone);
1236         } else if (adjuster instanceof ZoneOffset) {
1237             return resolveOffset((ZoneOffset) adjuster);
1238         }
1239         return (ZonedDateTime) adjuster.adjustInto(this);
1240     }
1241 
1242     /**
1243      * Returns a copy of this date-time with the specified field set to a new value.
1244      * <p>
1245      * This returns a {@code ZonedDateTime}, based on this one, with the value
1246      * for the specified field changed.
1247      * This can be used to change any supported field, such as the year, month or day-of-month.
1248      * If it is not possible to set the value, because the field is not supported or for
1249      * some other reason, an exception is thrown.
1250      * <p>
1251      * In some cases, changing the specified field can cause the resulting date-time to become invalid,
1252      * such as changing the month from 31st January to February would make the day-of-month invalid.
1253      * In cases like this, the field is responsible for resolving the date. Typically it will choose
1254      * the previous valid date, which would be the last valid day of February in this example.
1255      * <p>
1256      * If the field is a {@link ChronoField} then the adjustment is implemented here.
1257      * <p>
1258      * The {@code INSTANT_SECONDS} field will return a date-time with the specified instant.
1259      * The zone and nano-of-second are unchanged.
1260      * The result will have an offset derived from the new instant and original zone.
1261      * If the new instant value is outside the valid range then a {@code DateTimeException} will be thrown.
1262      * <p>
1263      * The {@code OFFSET_SECONDS} field will typically be ignored.
1264      * The offset of a {@code ZonedDateTime} is controlled primarily by the time-zone.
1265      * As such, changing the offset does not generally make sense, because there is only
1266      * one valid offset for the local date-time and zone.
1267      * If the zoned date-time is in a daylight savings overlap, then the offset is used
1268      * to switch between the two valid offsets. In all other cases, the offset is ignored.
1269      * If the new offset value is outside the valid range then a {@code DateTimeException} will be thrown.
1270      * <p>
1271      * The other {@link #isSupported(TemporalField) supported fields} will behave as per
1272      * the matching method on {@link LocalDateTime#with(TemporalField, long) LocalDateTime}.
1273      * The zone is not part of the calculation and will be unchanged.
1274      * When converting back to {@code ZonedDateTime}, if the local date-time is in an overlap,
1275      * then the offset will be retained if possible, otherwise the earlier offset will be used.
1276      * If in a gap, the local date-time will be adjusted forward by the length of the gap.
1277      * <p>
1278      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
1279      * <p>
1280      * If the field is not a {@code ChronoField}, then the result of this method
1281      * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
1282      * passing {@code this} as the argument. In this case, the field determines
1283      * whether and how to adjust the instant.
1284      * <p>
1285      * This instance is immutable and unaffected by this method call.
1286      *
1287      * @param field  the field to set in the result, not null
1288      * @param newValue  the new value of the field in the result
1289      * @return a {@code ZonedDateTime} based on {@code this} with the specified field set, not null
1290      * @throws DateTimeException if the field cannot be set
1291      * @throws UnsupportedTemporalTypeException if the field is not supported
1292      * @throws ArithmeticException if numeric overflow occurs
1293      */
1294     @Override
with(TemporalField field, long newValue)1295     public ZonedDateTime with(TemporalField field, long newValue) {
1296         if (field instanceof ChronoField chronoField) {
1297             switch (chronoField) {
1298                 case INSTANT_SECONDS:
1299                     return create(newValue, getNano(), zone);
1300                 case OFFSET_SECONDS:
1301                     ZoneOffset offset = ZoneOffset.ofTotalSeconds(chronoField.checkValidIntValue(newValue));
1302                     return resolveOffset(offset);
1303             }
1304             return resolveLocal(dateTime.with(field, newValue));
1305         }
1306         return field.adjustInto(this, newValue);
1307     }
1308 
1309     //-----------------------------------------------------------------------
1310     /**
1311      * Returns a copy of this {@code ZonedDateTime} with the year altered.
1312      * <p>
1313      * This operates on the local time-line,
1314      * {@link LocalDateTime#withYear(int) changing the year} of the local date-time.
1315      * This is then converted back to a {@code ZonedDateTime}, using the zone ID
1316      * to obtain the offset.
1317      * <p>
1318      * When converting back to {@code ZonedDateTime}, if the local date-time is in an overlap,
1319      * then the offset will be retained if possible, otherwise the earlier offset will be used.
1320      * If in a gap, the local date-time will be adjusted forward by the length of the gap.
1321      * <p>
1322      * This instance is immutable and unaffected by this method call.
1323      *
1324      * @param year  the year to set in the result, from MIN_YEAR to MAX_YEAR
1325      * @return a {@code ZonedDateTime} based on this date-time with the requested year, not null
1326      * @throws DateTimeException if the year value is invalid
1327      */
withYear(int year)1328     public ZonedDateTime withYear(int year) {
1329         return resolveLocal(dateTime.withYear(year));
1330     }
1331 
1332     /**
1333      * Returns a copy of this {@code ZonedDateTime} with the month-of-year altered.
1334      * <p>
1335      * This operates on the local time-line,
1336      * {@link LocalDateTime#withMonth(int) changing the month} of the local date-time.
1337      * This is then converted back to a {@code ZonedDateTime}, using the zone ID
1338      * to obtain the offset.
1339      * <p>
1340      * When converting back to {@code ZonedDateTime}, if the local date-time is in an overlap,
1341      * then the offset will be retained if possible, otherwise the earlier offset will be used.
1342      * If in a gap, the local date-time will be adjusted forward by the length of the gap.
1343      * <p>
1344      * This instance is immutable and unaffected by this method call.
1345      *
1346      * @param month  the month-of-year to set in the result, from 1 (January) to 12 (December)
1347      * @return a {@code ZonedDateTime} based on this date-time with the requested month, not null
1348      * @throws DateTimeException if the month-of-year value is invalid
1349      */
withMonth(int month)1350     public ZonedDateTime withMonth(int month) {
1351         return resolveLocal(dateTime.withMonth(month));
1352     }
1353 
1354     /**
1355      * Returns a copy of this {@code ZonedDateTime} with the day-of-month altered.
1356      * <p>
1357      * This operates on the local time-line,
1358      * {@link LocalDateTime#withDayOfMonth(int) changing the day-of-month} of the local date-time.
1359      * This is then converted back to a {@code ZonedDateTime}, using the zone ID
1360      * to obtain the offset.
1361      * <p>
1362      * When converting back to {@code ZonedDateTime}, if the local date-time is in an overlap,
1363      * then the offset will be retained if possible, otherwise the earlier offset will be used.
1364      * If in a gap, the local date-time will be adjusted forward by the length of the gap.
1365      * <p>
1366      * This instance is immutable and unaffected by this method call.
1367      *
1368      * @param dayOfMonth  the day-of-month to set in the result, from 1 to 28-31
1369      * @return a {@code ZonedDateTime} based on this date-time with the requested day, not null
1370      * @throws DateTimeException if the day-of-month value is invalid,
1371      *  or if the day-of-month is invalid for the month-year
1372      */
withDayOfMonth(int dayOfMonth)1373     public ZonedDateTime withDayOfMonth(int dayOfMonth) {
1374         return resolveLocal(dateTime.withDayOfMonth(dayOfMonth));
1375     }
1376 
1377     /**
1378      * Returns a copy of this {@code ZonedDateTime} with the day-of-year altered.
1379      * <p>
1380      * This operates on the local time-line,
1381      * {@link LocalDateTime#withDayOfYear(int) changing the day-of-year} of the local date-time.
1382      * This is then converted back to a {@code ZonedDateTime}, using the zone ID
1383      * to obtain the offset.
1384      * <p>
1385      * When converting back to {@code ZonedDateTime}, if the local date-time is in an overlap,
1386      * then the offset will be retained if possible, otherwise the earlier offset will be used.
1387      * If in a gap, the local date-time will be adjusted forward by the length of the gap.
1388      * <p>
1389      * This instance is immutable and unaffected by this method call.
1390      *
1391      * @param dayOfYear  the day-of-year to set in the result, from 1 to 365-366
1392      * @return a {@code ZonedDateTime} based on this date with the requested day, not null
1393      * @throws DateTimeException if the day-of-year value is invalid,
1394      *  or if the day-of-year is invalid for the year
1395      */
withDayOfYear(int dayOfYear)1396     public ZonedDateTime withDayOfYear(int dayOfYear) {
1397         return resolveLocal(dateTime.withDayOfYear(dayOfYear));
1398     }
1399 
1400     //-----------------------------------------------------------------------
1401     /**
1402      * Returns a copy of this {@code ZonedDateTime} with the hour-of-day altered.
1403      * <p>
1404      * This operates on the local time-line,
1405      * {@linkplain LocalDateTime#withHour(int) changing the time} of the local date-time.
1406      * This is then converted back to a {@code ZonedDateTime}, using the zone ID
1407      * to obtain the offset.
1408      * <p>
1409      * When converting back to {@code ZonedDateTime}, if the local date-time is in an overlap,
1410      * then the offset will be retained if possible, otherwise the earlier offset will be used.
1411      * If in a gap, the local date-time will be adjusted forward by the length of the gap.
1412      * <p>
1413      * This instance is immutable and unaffected by this method call.
1414      *
1415      * @param hour  the hour-of-day to set in the result, from 0 to 23
1416      * @return a {@code ZonedDateTime} based on this date-time with the requested hour, not null
1417      * @throws DateTimeException if the hour value is invalid
1418      */
withHour(int hour)1419     public ZonedDateTime withHour(int hour) {
1420         return resolveLocal(dateTime.withHour(hour));
1421     }
1422 
1423     /**
1424      * Returns a copy of this {@code ZonedDateTime} with the minute-of-hour altered.
1425      * <p>
1426      * This operates on the local time-line,
1427      * {@linkplain LocalDateTime#withMinute(int) changing the time} of the local date-time.
1428      * This is then converted back to a {@code ZonedDateTime}, using the zone ID
1429      * to obtain the offset.
1430      * <p>
1431      * When converting back to {@code ZonedDateTime}, if the local date-time is in an overlap,
1432      * then the offset will be retained if possible, otherwise the earlier offset will be used.
1433      * If in a gap, the local date-time will be adjusted forward by the length of the gap.
1434      * <p>
1435      * This instance is immutable and unaffected by this method call.
1436      *
1437      * @param minute  the minute-of-hour to set in the result, from 0 to 59
1438      * @return a {@code ZonedDateTime} based on this date-time with the requested minute, not null
1439      * @throws DateTimeException if the minute value is invalid
1440      */
withMinute(int minute)1441     public ZonedDateTime withMinute(int minute) {
1442         return resolveLocal(dateTime.withMinute(minute));
1443     }
1444 
1445     /**
1446      * Returns a copy of this {@code ZonedDateTime} with the second-of-minute altered.
1447      * <p>
1448      * This operates on the local time-line,
1449      * {@linkplain LocalDateTime#withSecond(int) changing the time} of the local date-time.
1450      * This is then converted back to a {@code ZonedDateTime}, using the zone ID
1451      * to obtain the offset.
1452      * <p>
1453      * When converting back to {@code ZonedDateTime}, if the local date-time is in an overlap,
1454      * then the offset will be retained if possible, otherwise the earlier offset will be used.
1455      * If in a gap, the local date-time will be adjusted forward by the length of the gap.
1456      * <p>
1457      * This instance is immutable and unaffected by this method call.
1458      *
1459      * @param second  the second-of-minute to set in the result, from 0 to 59
1460      * @return a {@code ZonedDateTime} based on this date-time with the requested second, not null
1461      * @throws DateTimeException if the second value is invalid
1462      */
withSecond(int second)1463     public ZonedDateTime withSecond(int second) {
1464         return resolveLocal(dateTime.withSecond(second));
1465     }
1466 
1467     /**
1468      * Returns a copy of this {@code ZonedDateTime} with the nano-of-second altered.
1469      * <p>
1470      * This operates on the local time-line,
1471      * {@linkplain LocalDateTime#withNano(int) changing the time} of the local date-time.
1472      * This is then converted back to a {@code ZonedDateTime}, using the zone ID
1473      * to obtain the offset.
1474      * <p>
1475      * When converting back to {@code ZonedDateTime}, if the local date-time is in an overlap,
1476      * then the offset will be retained if possible, otherwise the earlier offset will be used.
1477      * If in a gap, the local date-time will be adjusted forward by the length of the gap.
1478      * <p>
1479      * This instance is immutable and unaffected by this method call.
1480      *
1481      * @param nanoOfSecond  the nano-of-second to set in the result, from 0 to 999,999,999
1482      * @return a {@code ZonedDateTime} based on this date-time with the requested nanosecond, not null
1483      * @throws DateTimeException if the nano value is invalid
1484      */
withNano(int nanoOfSecond)1485     public ZonedDateTime withNano(int nanoOfSecond) {
1486         return resolveLocal(dateTime.withNano(nanoOfSecond));
1487     }
1488 
1489     //-----------------------------------------------------------------------
1490     /**
1491      * Returns a copy of this {@code ZonedDateTime} with the time truncated.
1492      * <p>
1493      * Truncation returns a copy of the original date-time with fields
1494      * smaller than the specified unit set to zero.
1495      * For example, truncating with the {@link ChronoUnit#MINUTES minutes} unit
1496      * will set the second-of-minute and nano-of-second field to zero.
1497      * <p>
1498      * The unit must have a {@linkplain TemporalUnit#getDuration() duration}
1499      * that divides into the length of a standard day without remainder.
1500      * This includes all supplied time units on {@link ChronoUnit} and
1501      * {@link ChronoUnit#DAYS DAYS}. Other units throw an exception.
1502      * <p>
1503      * This operates on the local time-line,
1504      * {@link LocalDateTime#truncatedTo(TemporalUnit) truncating}
1505      * the underlying local date-time. This is then converted back to a
1506      * {@code ZonedDateTime}, using the zone ID to obtain the offset.
1507      * <p>
1508      * When converting back to {@code ZonedDateTime}, if the local date-time is in an overlap,
1509      * then the offset will be retained if possible, otherwise the earlier offset will be used.
1510      * If in a gap, the local date-time will be adjusted forward by the length of the gap.
1511      * <p>
1512      * This instance is immutable and unaffected by this method call.
1513      *
1514      * @param unit  the unit to truncate to, not null
1515      * @return a {@code ZonedDateTime} based on this date-time with the time truncated, not null
1516      * @throws DateTimeException if unable to truncate
1517      * @throws UnsupportedTemporalTypeException if the unit is not supported
1518      */
truncatedTo(TemporalUnit unit)1519     public ZonedDateTime truncatedTo(TemporalUnit unit) {
1520         return resolveLocal(dateTime.truncatedTo(unit));
1521     }
1522 
1523     //-----------------------------------------------------------------------
1524     /**
1525      * Returns a copy of this date-time with the specified amount added.
1526      * <p>
1527      * This returns a {@code ZonedDateTime}, based on this one, with the specified amount added.
1528      * The amount is typically {@link Period} or {@link Duration} but may be
1529      * any other type implementing the {@link TemporalAmount} interface.
1530      * <p>
1531      * The calculation is delegated to the amount object by calling
1532      * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free
1533      * to implement the addition in any way it wishes, however it typically
1534      * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation
1535      * of the amount implementation to determine if it can be successfully added.
1536      * <p>
1537      * This instance is immutable and unaffected by this method call.
1538      *
1539      * @param amountToAdd  the amount to add, not null
1540      * @return a {@code ZonedDateTime} based on this date-time with the addition made, not null
1541      * @throws DateTimeException if the addition cannot be made
1542      * @throws ArithmeticException if numeric overflow occurs
1543      */
1544     @Override
plus(TemporalAmount amountToAdd)1545     public ZonedDateTime plus(TemporalAmount amountToAdd) {
1546         if (amountToAdd instanceof Period periodToAdd) {
1547             return resolveLocal(dateTime.plus(periodToAdd));
1548         }
1549         Objects.requireNonNull(amountToAdd, "amountToAdd");
1550         return (ZonedDateTime) amountToAdd.addTo(this);
1551     }
1552 
1553     /**
1554      * Returns a copy of this date-time with the specified amount added.
1555      * <p>
1556      * This returns a {@code ZonedDateTime}, based on this one, with the amount
1557      * in terms of the unit added. If it is not possible to add the amount, because the
1558      * unit is not supported or for some other reason, an exception is thrown.
1559      * <p>
1560      * If the field is a {@link ChronoUnit} then the addition is implemented here.
1561      * The zone is not part of the calculation and will be unchanged in the result.
1562      * The calculation for date and time units differ.
1563      * <p>
1564      * Date units operate on the local time-line.
1565      * The period is first added to the local date-time, then converted back
1566      * to a zoned date-time using the zone ID.
1567      * The conversion uses {@link #ofLocal(LocalDateTime, ZoneId, ZoneOffset)}
1568      * with the offset before the addition.
1569      * <p>
1570      * Time units operate on the instant time-line.
1571      * The period is first added to the local date-time, then converted back to
1572      * a zoned date-time using the zone ID.
1573      * The conversion uses {@link #ofInstant(LocalDateTime, ZoneOffset, ZoneId)}
1574      * with the offset before the addition.
1575      * <p>
1576      * If the field is not a {@code ChronoUnit}, then the result of this method
1577      * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
1578      * passing {@code this} as the argument. In this case, the unit determines
1579      * whether and how to perform the addition.
1580      * <p>
1581      * This instance is immutable and unaffected by this method call.
1582      *
1583      * @param amountToAdd  the amount of the unit to add to the result, may be negative
1584      * @param unit  the unit of the amount to add, not null
1585      * @return a {@code ZonedDateTime} based on this date-time with the specified amount added, not null
1586      * @throws DateTimeException if the addition cannot be made
1587      * @throws UnsupportedTemporalTypeException if the unit is not supported
1588      * @throws ArithmeticException if numeric overflow occurs
1589      */
1590     @Override
plus(long amountToAdd, TemporalUnit unit)1591     public ZonedDateTime plus(long amountToAdd, TemporalUnit unit) {
1592         if (unit instanceof ChronoUnit) {
1593             if (unit.isDateBased()) {
1594                 return resolveLocal(dateTime.plus(amountToAdd, unit));
1595             } else {
1596                 return resolveInstant(dateTime.plus(amountToAdd, unit));
1597             }
1598         }
1599         return unit.addTo(this, amountToAdd);
1600     }
1601 
1602     //-----------------------------------------------------------------------
1603     /**
1604      * Returns a copy of this {@code ZonedDateTime} with the specified number of years added.
1605      * <p>
1606      * This operates on the local time-line,
1607      * {@link LocalDateTime#plusYears(long) adding years} to the local date-time.
1608      * This is then converted back to a {@code ZonedDateTime}, using the zone ID
1609      * to obtain the offset.
1610      * <p>
1611      * When converting back to {@code ZonedDateTime}, if the local date-time is in an overlap,
1612      * then the offset will be retained if possible, otherwise the earlier offset will be used.
1613      * If in a gap, the local date-time will be adjusted forward by the length of the gap.
1614      * <p>
1615      * This instance is immutable and unaffected by this method call.
1616      *
1617      * @param years  the years to add, may be negative
1618      * @return a {@code ZonedDateTime} based on this date-time with the years added, not null
1619      * @throws DateTimeException if the result exceeds the supported date range
1620      */
plusYears(long years)1621     public ZonedDateTime plusYears(long years) {
1622         return resolveLocal(dateTime.plusYears(years));
1623     }
1624 
1625     /**
1626      * Returns a copy of this {@code ZonedDateTime} with the specified number of months added.
1627      * <p>
1628      * This operates on the local time-line,
1629      * {@link LocalDateTime#plusMonths(long) adding months} to the local date-time.
1630      * This is then converted back to a {@code ZonedDateTime}, using the zone ID
1631      * to obtain the offset.
1632      * <p>
1633      * When converting back to {@code ZonedDateTime}, if the local date-time is in an overlap,
1634      * then the offset will be retained if possible, otherwise the earlier offset will be used.
1635      * If in a gap, the local date-time will be adjusted forward by the length of the gap.
1636      * <p>
1637      * This instance is immutable and unaffected by this method call.
1638      *
1639      * @param months  the months to add, may be negative
1640      * @return a {@code ZonedDateTime} based on this date-time with the months added, not null
1641      * @throws DateTimeException if the result exceeds the supported date range
1642      */
plusMonths(long months)1643     public ZonedDateTime plusMonths(long months) {
1644         return resolveLocal(dateTime.plusMonths(months));
1645     }
1646 
1647     /**
1648      * Returns a copy of this {@code ZonedDateTime} with the specified number of weeks added.
1649      * <p>
1650      * This operates on the local time-line,
1651      * {@link LocalDateTime#plusWeeks(long) adding weeks} to the local date-time.
1652      * This is then converted back to a {@code ZonedDateTime}, using the zone ID
1653      * to obtain the offset.
1654      * <p>
1655      * When converting back to {@code ZonedDateTime}, if the local date-time is in an overlap,
1656      * then the offset will be retained if possible, otherwise the earlier offset will be used.
1657      * If in a gap, the local date-time will be adjusted forward by the length of the gap.
1658      * <p>
1659      * This instance is immutable and unaffected by this method call.
1660      *
1661      * @param weeks  the weeks to add, may be negative
1662      * @return a {@code ZonedDateTime} based on this date-time with the weeks added, not null
1663      * @throws DateTimeException if the result exceeds the supported date range
1664      */
plusWeeks(long weeks)1665     public ZonedDateTime plusWeeks(long weeks) {
1666         return resolveLocal(dateTime.plusWeeks(weeks));
1667     }
1668 
1669     /**
1670      * Returns a copy of this {@code ZonedDateTime} with the specified number of days added.
1671      * <p>
1672      * This operates on the local time-line,
1673      * {@link LocalDateTime#plusDays(long) adding days} to the local date-time.
1674      * This is then converted back to a {@code ZonedDateTime}, using the zone ID
1675      * to obtain the offset.
1676      * <p>
1677      * When converting back to {@code ZonedDateTime}, if the local date-time is in an overlap,
1678      * then the offset will be retained if possible, otherwise the earlier offset will be used.
1679      * If in a gap, the local date-time will be adjusted forward by the length of the gap.
1680      * <p>
1681      * This instance is immutable and unaffected by this method call.
1682      *
1683      * @param days  the days to add, may be negative
1684      * @return a {@code ZonedDateTime} based on this date-time with the days added, not null
1685      * @throws DateTimeException if the result exceeds the supported date range
1686      */
plusDays(long days)1687     public ZonedDateTime plusDays(long days) {
1688         return resolveLocal(dateTime.plusDays(days));
1689     }
1690 
1691     //-----------------------------------------------------------------------
1692     /**
1693      * Returns a copy of this {@code ZonedDateTime} with the specified number of hours added.
1694      * <p>
1695      * This operates on the instant time-line, such that adding one hour will
1696      * always be a duration of one hour later.
1697      * This may cause the local date-time to change by an amount other than one hour.
1698      * Note that this is a different approach to that used by days, months and years,
1699      * thus adding one day is not the same as adding 24 hours.
1700      * <p>
1701      * For example, consider a time-zone, such as 'Europe/Paris', where the
1702      * Autumn DST cutover means that the local times 02:00 to 02:59 occur twice
1703      * changing from offset +02:00 in summer to +01:00 in winter.
1704      * <ul>
1705      * <li>Adding one hour to 01:30+02:00 will result in 02:30+02:00
1706      *     (both in summer time)
1707      * <li>Adding one hour to 02:30+02:00 will result in 02:30+01:00
1708      *     (moving from summer to winter time)
1709      * <li>Adding one hour to 02:30+01:00 will result in 03:30+01:00
1710      *     (both in winter time)
1711      * <li>Adding three hours to 01:30+02:00 will result in 03:30+01:00
1712      *     (moving from summer to winter time)
1713      * </ul>
1714      * <p>
1715      * This instance is immutable and unaffected by this method call.
1716      *
1717      * @param hours  the hours to add, may be negative
1718      * @return a {@code ZonedDateTime} based on this date-time with the hours added, not null
1719      * @throws DateTimeException if the result exceeds the supported date range
1720      */
plusHours(long hours)1721     public ZonedDateTime plusHours(long hours) {
1722         return resolveInstant(dateTime.plusHours(hours));
1723     }
1724 
1725     /**
1726      * Returns a copy of this {@code ZonedDateTime} with the specified number of minutes added.
1727      * <p>
1728      * This operates on the instant time-line, such that adding one minute will
1729      * always be a duration of one minute later.
1730      * This may cause the local date-time to change by an amount other than one minute.
1731      * Note that this is a different approach to that used by days, months and years.
1732      * <p>
1733      * This instance is immutable and unaffected by this method call.
1734      *
1735      * @param minutes  the minutes to add, may be negative
1736      * @return a {@code ZonedDateTime} based on this date-time with the minutes added, not null
1737      * @throws DateTimeException if the result exceeds the supported date range
1738      */
plusMinutes(long minutes)1739     public ZonedDateTime plusMinutes(long minutes) {
1740         return resolveInstant(dateTime.plusMinutes(minutes));
1741     }
1742 
1743     /**
1744      * Returns a copy of this {@code ZonedDateTime} with the specified number of seconds added.
1745      * <p>
1746      * This operates on the instant time-line, such that adding one second will
1747      * always be a duration of one second later.
1748      * This may cause the local date-time to change by an amount other than one second.
1749      * Note that this is a different approach to that used by days, months and years.
1750      * <p>
1751      * This instance is immutable and unaffected by this method call.
1752      *
1753      * @param seconds  the seconds to add, may be negative
1754      * @return a {@code ZonedDateTime} based on this date-time with the seconds added, not null
1755      * @throws DateTimeException if the result exceeds the supported date range
1756      */
plusSeconds(long seconds)1757     public ZonedDateTime plusSeconds(long seconds) {
1758         return resolveInstant(dateTime.plusSeconds(seconds));
1759     }
1760 
1761     /**
1762      * Returns a copy of this {@code ZonedDateTime} with the specified number of nanoseconds added.
1763      * <p>
1764      * This operates on the instant time-line, such that adding one nano will
1765      * always be a duration of one nano later.
1766      * This may cause the local date-time to change by an amount other than one nano.
1767      * Note that this is a different approach to that used by days, months and years.
1768      * <p>
1769      * This instance is immutable and unaffected by this method call.
1770      *
1771      * @param nanos  the nanos to add, may be negative
1772      * @return a {@code ZonedDateTime} based on this date-time with the nanoseconds added, not null
1773      * @throws DateTimeException if the result exceeds the supported date range
1774      */
plusNanos(long nanos)1775     public ZonedDateTime plusNanos(long nanos) {
1776         return resolveInstant(dateTime.plusNanos(nanos));
1777     }
1778 
1779     //-----------------------------------------------------------------------
1780     /**
1781      * Returns a copy of this date-time with the specified amount subtracted.
1782      * <p>
1783      * This returns a {@code ZonedDateTime}, based on this one, with the specified amount subtracted.
1784      * The amount is typically {@link Period} or {@link Duration} but may be
1785      * any other type implementing the {@link TemporalAmount} interface.
1786      * <p>
1787      * The calculation is delegated to the amount object by calling
1788      * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free
1789      * to implement the subtraction in any way it wishes, however it typically
1790      * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation
1791      * of the amount implementation to determine if it can be successfully subtracted.
1792      * <p>
1793      * This instance is immutable and unaffected by this method call.
1794      *
1795      * @param amountToSubtract  the amount to subtract, not null
1796      * @return a {@code ZonedDateTime} based on this date-time with the subtraction made, not null
1797      * @throws DateTimeException if the subtraction cannot be made
1798      * @throws ArithmeticException if numeric overflow occurs
1799      */
1800     @Override
minus(TemporalAmount amountToSubtract)1801     public ZonedDateTime minus(TemporalAmount amountToSubtract) {
1802         if (amountToSubtract instanceof Period periodToSubtract) {
1803             return resolveLocal(dateTime.minus(periodToSubtract));
1804         }
1805         Objects.requireNonNull(amountToSubtract, "amountToSubtract");
1806         return (ZonedDateTime) amountToSubtract.subtractFrom(this);
1807     }
1808 
1809     /**
1810      * Returns a copy of this date-time with the specified amount subtracted.
1811      * <p>
1812      * This returns a {@code ZonedDateTime}, based on this one, with the amount
1813      * in terms of the unit subtracted. If it is not possible to subtract the amount,
1814      * because the unit is not supported or for some other reason, an exception is thrown.
1815      * <p>
1816      * The calculation for date and time units differ.
1817      * <p>
1818      * Date units operate on the local time-line.
1819      * The period is first subtracted from the local date-time, then converted back
1820      * to a zoned date-time using the zone ID.
1821      * The conversion uses {@link #ofLocal(LocalDateTime, ZoneId, ZoneOffset)}
1822      * with the offset before the subtraction.
1823      * <p>
1824      * Time units operate on the instant time-line.
1825      * The period is first subtracted from the local date-time, then converted back to
1826      * a zoned date-time using the zone ID.
1827      * The conversion uses {@link #ofInstant(LocalDateTime, ZoneOffset, ZoneId)}
1828      * with the offset before the subtraction.
1829      * <p>
1830      * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.
1831      * See that method for a full description of how addition, and thus subtraction, works.
1832      * <p>
1833      * This instance is immutable and unaffected by this method call.
1834      *
1835      * @param amountToSubtract  the amount of the unit to subtract from the result, may be negative
1836      * @param unit  the unit of the amount to subtract, not null
1837      * @return a {@code ZonedDateTime} based on this date-time with the specified amount subtracted, not null
1838      * @throws DateTimeException if the subtraction cannot be made
1839      * @throws UnsupportedTemporalTypeException if the unit is not supported
1840      * @throws ArithmeticException if numeric overflow occurs
1841      */
1842     @Override
minus(long amountToSubtract, TemporalUnit unit)1843     public ZonedDateTime minus(long amountToSubtract, TemporalUnit unit) {
1844         return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
1845     }
1846 
1847     //-----------------------------------------------------------------------
1848     /**
1849      * Returns a copy of this {@code ZonedDateTime} with the specified number of years subtracted.
1850      * <p>
1851      * This operates on the local time-line,
1852      * {@link LocalDateTime#minusYears(long) subtracting years} to the local date-time.
1853      * This is then converted back to a {@code ZonedDateTime}, using the zone ID
1854      * to obtain the offset.
1855      * <p>
1856      * When converting back to {@code ZonedDateTime}, if the local date-time is in an overlap,
1857      * then the offset will be retained if possible, otherwise the earlier offset will be used.
1858      * If in a gap, the local date-time will be adjusted forward by the length of the gap.
1859      * <p>
1860      * This instance is immutable and unaffected by this method call.
1861      *
1862      * @param years  the years to subtract, may be negative
1863      * @return a {@code ZonedDateTime} based on this date-time with the years subtracted, not null
1864      * @throws DateTimeException if the result exceeds the supported date range
1865      */
minusYears(long years)1866     public ZonedDateTime minusYears(long years) {
1867         return (years == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-years));
1868     }
1869 
1870     /**
1871      * Returns a copy of this {@code ZonedDateTime} with the specified number of months subtracted.
1872      * <p>
1873      * This operates on the local time-line,
1874      * {@link LocalDateTime#minusMonths(long) subtracting months} to the local date-time.
1875      * This is then converted back to a {@code ZonedDateTime}, using the zone ID
1876      * to obtain the offset.
1877      * <p>
1878      * When converting back to {@code ZonedDateTime}, if the local date-time is in an overlap,
1879      * then the offset will be retained if possible, otherwise the earlier offset will be used.
1880      * If in a gap, the local date-time will be adjusted forward by the length of the gap.
1881      * <p>
1882      * This instance is immutable and unaffected by this method call.
1883      *
1884      * @param months  the months to subtract, may be negative
1885      * @return a {@code ZonedDateTime} based on this date-time with the months subtracted, not null
1886      * @throws DateTimeException if the result exceeds the supported date range
1887      */
minusMonths(long months)1888     public ZonedDateTime minusMonths(long months) {
1889         return (months == Long.MIN_VALUE ? plusMonths(Long.MAX_VALUE).plusMonths(1) : plusMonths(-months));
1890     }
1891 
1892     /**
1893      * Returns a copy of this {@code ZonedDateTime} with the specified number of weeks subtracted.
1894      * <p>
1895      * This operates on the local time-line,
1896      * {@link LocalDateTime#minusWeeks(long) subtracting weeks} to the local date-time.
1897      * This is then converted back to a {@code ZonedDateTime}, using the zone ID
1898      * to obtain the offset.
1899      * <p>
1900      * When converting back to {@code ZonedDateTime}, if the local date-time is in an overlap,
1901      * then the offset will be retained if possible, otherwise the earlier offset will be used.
1902      * If in a gap, the local date-time will be adjusted forward by the length of the gap.
1903      * <p>
1904      * This instance is immutable and unaffected by this method call.
1905      *
1906      * @param weeks  the weeks to subtract, may be negative
1907      * @return a {@code ZonedDateTime} based on this date-time with the weeks subtracted, not null
1908      * @throws DateTimeException if the result exceeds the supported date range
1909      */
minusWeeks(long weeks)1910     public ZonedDateTime minusWeeks(long weeks) {
1911         return (weeks == Long.MIN_VALUE ? plusWeeks(Long.MAX_VALUE).plusWeeks(1) : plusWeeks(-weeks));
1912     }
1913 
1914     /**
1915      * Returns a copy of this {@code ZonedDateTime} with the specified number of days subtracted.
1916      * <p>
1917      * This operates on the local time-line,
1918      * {@link LocalDateTime#minusDays(long) subtracting days} to the local date-time.
1919      * This is then converted back to a {@code ZonedDateTime}, using the zone ID
1920      * to obtain the offset.
1921      * <p>
1922      * When converting back to {@code ZonedDateTime}, if the local date-time is in an overlap,
1923      * then the offset will be retained if possible, otherwise the earlier offset will be used.
1924      * If in a gap, the local date-time will be adjusted forward by the length of the gap.
1925      * <p>
1926      * This instance is immutable and unaffected by this method call.
1927      *
1928      * @param days  the days to subtract, may be negative
1929      * @return a {@code ZonedDateTime} based on this date-time with the days subtracted, not null
1930      * @throws DateTimeException if the result exceeds the supported date range
1931      */
minusDays(long days)1932     public ZonedDateTime minusDays(long days) {
1933         return (days == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-days));
1934     }
1935 
1936     //-----------------------------------------------------------------------
1937     /**
1938      * Returns a copy of this {@code ZonedDateTime} with the specified number of hours subtracted.
1939      * <p>
1940      * This operates on the instant time-line, such that subtracting one hour will
1941      * always be a duration of one hour earlier.
1942      * This may cause the local date-time to change by an amount other than one hour.
1943      * Note that this is a different approach to that used by days, months and years,
1944      * thus subtracting one day is not the same as adding 24 hours.
1945      * <p>
1946      * For example, consider a time-zone, such as 'Europe/Paris', where the
1947      * Autumn DST cutover means that the local times 02:00 to 02:59 occur twice
1948      * changing from offset +02:00 in summer to +01:00 in winter.
1949      * <ul>
1950      * <li>Subtracting one hour from 03:30+01:00 will result in 02:30+01:00
1951      *     (both in winter time)
1952      * <li>Subtracting one hour from 02:30+01:00 will result in 02:30+02:00
1953      *     (moving from winter to summer time)
1954      * <li>Subtracting one hour from 02:30+02:00 will result in 01:30+02:00
1955      *     (both in summer time)
1956      * <li>Subtracting three hours from 03:30+01:00 will result in 01:30+02:00
1957      *     (moving from winter to summer time)
1958      * </ul>
1959      * <p>
1960      * This instance is immutable and unaffected by this method call.
1961      *
1962      * @param hours  the hours to subtract, may be negative
1963      * @return a {@code ZonedDateTime} based on this date-time with the hours subtracted, not null
1964      * @throws DateTimeException if the result exceeds the supported date range
1965      */
minusHours(long hours)1966     public ZonedDateTime minusHours(long hours) {
1967         return (hours == Long.MIN_VALUE ? plusHours(Long.MAX_VALUE).plusHours(1) : plusHours(-hours));
1968     }
1969 
1970     /**
1971      * Returns a copy of this {@code ZonedDateTime} with the specified number of minutes subtracted.
1972      * <p>
1973      * This operates on the instant time-line, such that subtracting one minute will
1974      * always be a duration of one minute earlier.
1975      * This may cause the local date-time to change by an amount other than one minute.
1976      * Note that this is a different approach to that used by days, months and years.
1977      * <p>
1978      * This instance is immutable and unaffected by this method call.
1979      *
1980      * @param minutes  the minutes to subtract, may be negative
1981      * @return a {@code ZonedDateTime} based on this date-time with the minutes subtracted, not null
1982      * @throws DateTimeException if the result exceeds the supported date range
1983      */
minusMinutes(long minutes)1984     public ZonedDateTime minusMinutes(long minutes) {
1985         return (minutes == Long.MIN_VALUE ? plusMinutes(Long.MAX_VALUE).plusMinutes(1) : plusMinutes(-minutes));
1986     }
1987 
1988     /**
1989      * Returns a copy of this {@code ZonedDateTime} with the specified number of seconds subtracted.
1990      * <p>
1991      * This operates on the instant time-line, such that subtracting one second will
1992      * always be a duration of one second earlier.
1993      * This may cause the local date-time to change by an amount other than one second.
1994      * Note that this is a different approach to that used by days, months and years.
1995      * <p>
1996      * This instance is immutable and unaffected by this method call.
1997      *
1998      * @param seconds  the seconds to subtract, may be negative
1999      * @return a {@code ZonedDateTime} based on this date-time with the seconds subtracted, not null
2000      * @throws DateTimeException if the result exceeds the supported date range
2001      */
minusSeconds(long seconds)2002     public ZonedDateTime minusSeconds(long seconds) {
2003         return (seconds == Long.MIN_VALUE ? plusSeconds(Long.MAX_VALUE).plusSeconds(1) : plusSeconds(-seconds));
2004     }
2005 
2006     /**
2007      * Returns a copy of this {@code ZonedDateTime} with the specified number of nanoseconds subtracted.
2008      * <p>
2009      * This operates on the instant time-line, such that subtracting one nano will
2010      * always be a duration of one nano earlier.
2011      * This may cause the local date-time to change by an amount other than one nano.
2012      * Note that this is a different approach to that used by days, months and years.
2013      * <p>
2014      * This instance is immutable and unaffected by this method call.
2015      *
2016      * @param nanos  the nanos to subtract, may be negative
2017      * @return a {@code ZonedDateTime} based on this date-time with the nanoseconds subtracted, not null
2018      * @throws DateTimeException if the result exceeds the supported date range
2019      */
minusNanos(long nanos)2020     public ZonedDateTime minusNanos(long nanos) {
2021         return (nanos == Long.MIN_VALUE ? plusNanos(Long.MAX_VALUE).plusNanos(1) : plusNanos(-nanos));
2022     }
2023 
2024     //-----------------------------------------------------------------------
2025     /**
2026      * Queries this date-time using the specified query.
2027      * <p>
2028      * This queries this date-time using the specified query strategy object.
2029      * The {@code TemporalQuery} object defines the logic to be used to
2030      * obtain the result. Read the documentation of the query to understand
2031      * what the result of this method will be.
2032      * <p>
2033      * The result of this method is obtained by invoking the
2034      * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
2035      * specified query passing {@code this} as the argument.
2036      *
2037      * @param <R> the type of the result
2038      * @param query  the query to invoke, not null
2039      * @return the query result, null may be returned (defined by the query)
2040      * @throws DateTimeException if unable to query (defined by the query)
2041      * @throws ArithmeticException if numeric overflow occurs (defined by the query)
2042      */
2043     @SuppressWarnings("unchecked")
2044     @Override  // override for Javadoc
query(TemporalQuery<R> query)2045     public <R> R query(TemporalQuery<R> query) {
2046         if (query == TemporalQueries.localDate()) {
2047             return (R) toLocalDate();
2048         }
2049         return ChronoZonedDateTime.super.query(query);
2050     }
2051 
2052     /**
2053      * Calculates the amount of time until another date-time in terms of the specified unit.
2054      * <p>
2055      * This calculates the amount of time between two {@code ZonedDateTime}
2056      * objects in terms of a single {@code TemporalUnit}.
2057      * The start and end points are {@code this} and the specified date-time.
2058      * The result will be negative if the end is before the start.
2059      * For example, the amount in days between two date-times can be calculated
2060      * using {@code startDateTime.until(endDateTime, DAYS)}.
2061      * <p>
2062      * The {@code Temporal} passed to this method is converted to a
2063      * {@code ZonedDateTime} using {@link #from(TemporalAccessor)}.
2064      * If the time-zone differs between the two zoned date-times, the specified
2065      * end date-time is normalized to have the same zone as this date-time.
2066      * <p>
2067      * The calculation returns a whole number, representing the number of
2068      * complete units between the two date-times.
2069      * For example, the amount in months between 2012-06-15T00:00Z and 2012-08-14T23:59Z
2070      * will only be one month as it is one minute short of two months.
2071      * <p>
2072      * There are two equivalent ways of using this method.
2073      * The first is to invoke this method.
2074      * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
2075      * <pre>
2076      *   // these two lines are equivalent
2077      *   amount = start.until(end, MONTHS);
2078      *   amount = MONTHS.between(start, end);
2079      * </pre>
2080      * The choice should be made based on which makes the code more readable.
2081      * <p>
2082      * The calculation is implemented in this method for {@link ChronoUnit}.
2083      * The units {@code NANOS}, {@code MICROS}, {@code MILLIS}, {@code SECONDS},
2084      * {@code MINUTES}, {@code HOURS} and {@code HALF_DAYS}, {@code DAYS},
2085      * {@code WEEKS}, {@code MONTHS}, {@code YEARS}, {@code DECADES},
2086      * {@code CENTURIES}, {@code MILLENNIA} and {@code ERAS} are supported.
2087      * Other {@code ChronoUnit} values will throw an exception.
2088      * <p>
2089      * The calculation for date and time units differ.
2090      * <p>
2091      * Date units operate on the local time-line, using the local date-time.
2092      * For example, the period from noon on day 1 to noon the following day
2093      * in days will always be counted as exactly one day, irrespective of whether
2094      * there was a daylight savings change or not.
2095      * <p>
2096      * Time units operate on the instant time-line.
2097      * The calculation effectively converts both zoned date-times to instants
2098      * and then calculates the period between the instants.
2099      * For example, the period from noon on day 1 to noon the following day
2100      * in hours may be 23, 24 or 25 hours (or some other amount) depending on
2101      * whether there was a daylight savings change or not.
2102      * <p>
2103      * If the unit is not a {@code ChronoUnit}, then the result of this method
2104      * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
2105      * passing {@code this} as the first argument and the converted input temporal
2106      * as the second argument.
2107      * <p>
2108      * This instance is immutable and unaffected by this method call.
2109      *
2110      * @param endExclusive  the end date, exclusive, which is converted to a {@code ZonedDateTime}, not null
2111      * @param unit  the unit to measure the amount in, not null
2112      * @return the amount of time between this date-time and the end date-time
2113      * @throws DateTimeException if the amount cannot be calculated, or the end
2114      *  temporal cannot be converted to a {@code ZonedDateTime}
2115      * @throws UnsupportedTemporalTypeException if the unit is not supported
2116      * @throws ArithmeticException if numeric overflow occurs
2117      */
2118     @Override
until(Temporal endExclusive, TemporalUnit unit)2119     public long until(Temporal endExclusive, TemporalUnit unit) {
2120         ZonedDateTime end = ZonedDateTime.from(endExclusive);
2121         if (unit instanceof ChronoUnit) {
2122             ZonedDateTime start = this;
2123             try {
2124                 end = end.withZoneSameInstant(zone);
2125             } catch (DateTimeException ex) {
2126                 // end may be out of valid range. Adjust to end's zone.
2127                 start = withZoneSameInstant(end.zone);
2128             }
2129             if (unit.isDateBased()) {
2130                 return start.dateTime.until(end.dateTime, unit);
2131             } else {
2132                 return start.toOffsetDateTime().until(end.toOffsetDateTime(), unit);
2133             }
2134         }
2135         return unit.between(this, end);
2136     }
2137 
2138     /**
2139      * Formats this date-time using the specified formatter.
2140      * <p>
2141      * This date-time will be passed to the formatter to produce a string.
2142      *
2143      * @param formatter  the formatter to use, not null
2144      * @return the formatted date-time string, not null
2145      * @throws DateTimeException if an error occurs during printing
2146      */
2147     @Override  // override for Javadoc and performance
format(DateTimeFormatter formatter)2148     public String format(DateTimeFormatter formatter) {
2149         Objects.requireNonNull(formatter, "formatter");
2150         return formatter.format(this);
2151     }
2152 
2153     //-----------------------------------------------------------------------
2154     /**
2155      * Converts this date-time to an {@code OffsetDateTime}.
2156      * <p>
2157      * This creates an offset date-time using the local date-time and offset.
2158      * The zone ID is ignored.
2159      *
2160      * @return an offset date-time representing the same local date-time and offset, not null
2161      */
toOffsetDateTime()2162     public OffsetDateTime toOffsetDateTime() {
2163         return OffsetDateTime.of(dateTime, offset);
2164     }
2165 
2166     //-----------------------------------------------------------------------
2167     /**
2168      * Checks if this date-time is equal to another date-time.
2169      * <p>
2170      * The comparison is based on the offset date-time and the zone.
2171      * Only objects of type {@code ZonedDateTime} are compared, other types return false.
2172      *
2173      * @param obj  the object to check, null returns false
2174      * @return true if this is equal to the other date-time
2175      */
2176     @Override
equals(Object obj)2177     public boolean equals(Object obj) {
2178         if (this == obj) {
2179             return true;
2180         }
2181         return obj instanceof ZonedDateTime other
2182                 && dateTime.equals(other.dateTime)
2183                 && offset.equals(other.offset)
2184                 && zone.equals(other.zone);
2185     }
2186 
2187     /**
2188      * A hash code for this date-time.
2189      *
2190      * @return a suitable hash code
2191      */
2192     @Override
hashCode()2193     public int hashCode() {
2194         return dateTime.hashCode() ^ offset.hashCode() ^ Integer.rotateLeft(zone.hashCode(), 3);
2195     }
2196 
2197     //-----------------------------------------------------------------------
2198     /**
2199      * Outputs this date-time as a {@code String}, such as
2200      * {@code 2007-12-03T10:15:30+01:00[Europe/Paris]}.
2201      * <p>
2202      * The format consists of the {@code LocalDateTime} followed by the {@code ZoneOffset}.
2203      * If the {@code ZoneId} is not the same as the offset, then the ID is output.
2204      * The output is compatible with ISO-8601 if the offset and ID are the same.
2205      *
2206      * @return a string representation of this date-time, not null
2207      */
2208     @Override  // override for Javadoc
toString()2209     public String toString() {
2210         String str = dateTime.toString() + offset.toString();
2211         if (offset != zone) {
2212             str += '[' + zone.toString() + ']';
2213         }
2214         return str;
2215     }
2216 
2217     //-----------------------------------------------------------------------
2218     /**
2219      * Writes the object using a
2220      * <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>.
2221      * @serialData
2222      * <pre>
2223      *  out.writeByte(6);  // identifies a ZonedDateTime
2224      *  // the <a href="{@docRoot}/serialized-form.html#java.time.LocalDateTime">dateTime</a> excluding the one byte header
2225      *  // the <a href="{@docRoot}/serialized-form.html#java.time.ZoneOffset">offset</a> excluding the one byte header
2226      *  // the <a href="{@docRoot}/serialized-form.html#java.time.ZoneId">zone ID</a> excluding the one byte header
2227      * </pre>
2228      *
2229      * @return the instance of {@code Ser}, not null
2230      */
2231     @java.io.Serial
writeReplace()2232     private Object writeReplace() {
2233         return new Ser(Ser.ZONE_DATE_TIME_TYPE, this);
2234     }
2235 
2236     /**
2237      * Defend against malicious streams.
2238      *
2239      * @param s the stream to read
2240      * @throws InvalidObjectException always
2241      */
2242     @java.io.Serial
readObject(ObjectInputStream s)2243     private void readObject(ObjectInputStream s) throws InvalidObjectException {
2244         throw new InvalidObjectException("Deserialization via serialization delegate");
2245     }
2246 
writeExternal(DataOutput out)2247     void writeExternal(DataOutput out) throws IOException {
2248         dateTime.writeExternal(out);
2249         offset.writeExternal(out);
2250         zone.write(out);
2251     }
2252 
readExternal(ObjectInput in)2253     static ZonedDateTime readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
2254         LocalDateTime dateTime = LocalDateTime.readExternal(in);
2255         ZoneOffset offset = ZoneOffset.readExternal(in);
2256         ZoneId zone = (ZoneId) Ser.read(in);
2257         return ZonedDateTime.ofLenient(dateTime, offset, zone);
2258     }
2259 
2260 }
2261