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