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