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