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