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