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