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