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