Path: blob/master/src/java.base/share/classes/java/time/OffsetDateTime.java
41152 views
/*1* Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file:30*31* Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos32*33* All rights reserved.34*35* Redistribution and use in source and binary forms, with or without36* modification, are permitted provided that the following conditions are met:37*38* * Redistributions of source code must retain the above copyright notice,39* this list of conditions and the following disclaimer.40*41* * Redistributions in binary form must reproduce the above copyright notice,42* this list of conditions and the following disclaimer in the documentation43* and/or other materials provided with the distribution.44*45* * Neither the name of JSR-310 nor the names of its contributors46* may be used to endorse or promote products derived from this software47* without specific prior written permission.48*49* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS50* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT51* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR52* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR53* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,54* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,55* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR56* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF57* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING58* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS59* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.60*/61package java.time;6263import static java.time.temporal.ChronoField.EPOCH_DAY;64import static java.time.temporal.ChronoField.INSTANT_SECONDS;65import static java.time.temporal.ChronoField.NANO_OF_DAY;66import static java.time.temporal.ChronoField.OFFSET_SECONDS;67import static java.time.temporal.ChronoUnit.FOREVER;68import static java.time.temporal.ChronoUnit.NANOS;6970import java.io.IOException;71import java.io.ObjectInput;72import java.io.ObjectOutput;73import java.io.InvalidObjectException;74import java.io.ObjectInputStream;75import java.io.Serializable;76import java.time.chrono.IsoChronology;77import java.time.format.DateTimeFormatter;78import java.time.format.DateTimeParseException;79import java.time.temporal.ChronoField;80import java.time.temporal.ChronoUnit;81import java.time.temporal.Temporal;82import java.time.temporal.TemporalAccessor;83import java.time.temporal.TemporalAdjuster;84import java.time.temporal.TemporalAmount;85import java.time.temporal.TemporalField;86import java.time.temporal.TemporalQueries;87import java.time.temporal.TemporalQuery;88import java.time.temporal.TemporalUnit;89import java.time.temporal.UnsupportedTemporalTypeException;90import java.time.temporal.ValueRange;91import java.time.zone.ZoneRules;92import java.util.Comparator;93import java.util.Objects;9495/**96* A date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system,97* such as {@code 2007-12-03T10:15:30+01:00}.98* <p>99* {@code OffsetDateTime} is an immutable representation of a date-time with an offset.100* This class stores all date and time fields, to a precision of nanoseconds,101* as well as the offset from UTC/Greenwich. For example, the value102* "2nd October 2007 at 13:45:30.123456789 +02:00" can be stored in an {@code OffsetDateTime}.103* <p>104* {@code OffsetDateTime}, {@link java.time.ZonedDateTime} and {@link java.time.Instant} all store an instant105* on the time-line to nanosecond precision.106* {@code Instant} is the simplest, simply representing the instant.107* {@code OffsetDateTime} adds to the instant the offset from UTC/Greenwich, which allows108* the local date-time to be obtained.109* {@code ZonedDateTime} adds full time-zone rules.110* <p>111* It is intended that {@code ZonedDateTime} or {@code Instant} is used to model data112* in simpler applications. This class may be used when modeling date-time concepts in113* more detail, or when communicating to a database or in a network protocol.114* <p>115* This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>116* class; programmers should treat instances that are117* {@linkplain #equals(Object) equal} as interchangeable and should not118* use instances for synchronization, or unpredictable behavior may119* occur. For example, in a future release, synchronization may fail.120* The {@code equals} method should be used for comparisons.121*122* @implSpec123* This class is immutable and thread-safe.124*125* @since 1.8126*/127@jdk.internal.ValueBased128public final class OffsetDateTime129implements Temporal, TemporalAdjuster, Comparable<OffsetDateTime>, Serializable {130131/**132* The minimum supported {@code OffsetDateTime}, '-999999999-01-01T00:00:00+18:00'.133* This is the local date-time of midnight at the start of the minimum date134* in the maximum offset (larger offsets are earlier on the time-line).135* This combines {@link LocalDateTime#MIN} and {@link ZoneOffset#MAX}.136* This could be used by an application as a "far past" date-time.137*/138public static final OffsetDateTime MIN = LocalDateTime.MIN.atOffset(ZoneOffset.MAX);139/**140* The maximum supported {@code OffsetDateTime}, '+999999999-12-31T23:59:59.999999999-18:00'.141* This is the local date-time just before midnight at the end of the maximum date142* in the minimum offset (larger negative offsets are later on the time-line).143* This combines {@link LocalDateTime#MAX} and {@link ZoneOffset#MIN}.144* This could be used by an application as a "far future" date-time.145*/146public static final OffsetDateTime MAX = LocalDateTime.MAX.atOffset(ZoneOffset.MIN);147148/**149* Gets a comparator that compares two {@code OffsetDateTime} instances150* based solely on the instant.151* <p>152* This method differs from the comparison in {@link #compareTo} in that it153* only compares the underlying instant.154*155* @return a comparator that compares in time-line order156*157* @see #isAfter158* @see #isBefore159* @see #isEqual160*/161public static Comparator<OffsetDateTime> timeLineOrder() {162return OffsetDateTime::compareInstant;163}164165/**166* Compares this {@code OffsetDateTime} to another date-time.167* The comparison is based on the instant.168*169* @param datetime1 the first date-time to compare, not null170* @param datetime2 the other date-time to compare to, not null171* @return the comparator value, negative if less, positive if greater172*/173private static int compareInstant(OffsetDateTime datetime1, OffsetDateTime datetime2) {174if (datetime1.getOffset().equals(datetime2.getOffset())) {175return datetime1.toLocalDateTime().compareTo(datetime2.toLocalDateTime());176}177int cmp = Long.compare(datetime1.toEpochSecond(), datetime2.toEpochSecond());178if (cmp == 0) {179cmp = datetime1.toLocalTime().getNano() - datetime2.toLocalTime().getNano();180}181return cmp;182}183184/**185* Serialization version.186*/187@java.io.Serial188private static final long serialVersionUID = 2287754244819255394L;189190/**191* The local date-time.192*/193private final LocalDateTime dateTime;194/**195* The offset from UTC/Greenwich.196*/197private final ZoneOffset offset;198199//-----------------------------------------------------------------------200/**201* Obtains the current date-time from the system clock in the default time-zone.202* <p>203* This will query the {@link Clock#systemDefaultZone() system clock} in the default204* time-zone to obtain the current date-time.205* The offset will be calculated from the time-zone in the clock.206* <p>207* Using this method will prevent the ability to use an alternate clock for testing208* because the clock is hard-coded.209*210* @return the current date-time using the system clock, not null211*/212public static OffsetDateTime now() {213return now(Clock.systemDefaultZone());214}215216/**217* Obtains the current date-time from the system clock in the specified time-zone.218* <p>219* This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date-time.220* Specifying the time-zone avoids dependence on the default time-zone.221* The offset will be calculated from the specified time-zone.222* <p>223* Using this method will prevent the ability to use an alternate clock for testing224* because the clock is hard-coded.225*226* @param zone the zone ID to use, not null227* @return the current date-time using the system clock, not null228*/229public static OffsetDateTime now(ZoneId zone) {230return now(Clock.system(zone));231}232233/**234* Obtains the current date-time from the specified clock.235* <p>236* This will query the specified clock to obtain the current date-time.237* The offset will be calculated from the time-zone in the clock.238* <p>239* Using this method allows the use of an alternate clock for testing.240* The alternate clock may be introduced using {@link Clock dependency injection}.241*242* @param clock the clock to use, not null243* @return the current date-time, not null244*/245public static OffsetDateTime now(Clock clock) {246Objects.requireNonNull(clock, "clock");247final Instant now = clock.instant(); // called once248return ofInstant(now, clock.getZone().getRules().getOffset(now));249}250251//-----------------------------------------------------------------------252/**253* Obtains an instance of {@code OffsetDateTime} from a date, time and offset.254* <p>255* This creates an offset date-time with the specified local date, time and offset.256*257* @param date the local date, not null258* @param time the local time, not null259* @param offset the zone offset, not null260* @return the offset date-time, not null261*/262public static OffsetDateTime of(LocalDate date, LocalTime time, ZoneOffset offset) {263LocalDateTime dt = LocalDateTime.of(date, time);264return new OffsetDateTime(dt, offset);265}266267/**268* Obtains an instance of {@code OffsetDateTime} from a date-time and offset.269* <p>270* This creates an offset date-time with the specified local date-time and offset.271*272* @param dateTime the local date-time, not null273* @param offset the zone offset, not null274* @return the offset date-time, not null275*/276public static OffsetDateTime of(LocalDateTime dateTime, ZoneOffset offset) {277return new OffsetDateTime(dateTime, offset);278}279280/**281* Obtains an instance of {@code OffsetDateTime} from a year, month, day,282* hour, minute, second, nanosecond and offset.283* <p>284* This creates an offset date-time with the seven specified fields.285* <p>286* This method exists primarily for writing test cases.287* Non test-code will typically use other methods to create an offset time.288* {@code LocalDateTime} has five additional convenience variants of the289* equivalent factory method taking fewer arguments.290* They are not provided here to reduce the footprint of the API.291*292* @param year the year to represent, from MIN_YEAR to MAX_YEAR293* @param month the month-of-year to represent, from 1 (January) to 12 (December)294* @param dayOfMonth the day-of-month to represent, from 1 to 31295* @param hour the hour-of-day to represent, from 0 to 23296* @param minute the minute-of-hour to represent, from 0 to 59297* @param second the second-of-minute to represent, from 0 to 59298* @param nanoOfSecond the nano-of-second to represent, from 0 to 999,999,999299* @param offset the zone offset, not null300* @return the offset date-time, not null301* @throws DateTimeException if the value of any field is out of range, or302* if the day-of-month is invalid for the month-year303*/304public static OffsetDateTime of(305int year, int month, int dayOfMonth,306int hour, int minute, int second, int nanoOfSecond, ZoneOffset offset) {307LocalDateTime dt = LocalDateTime.of(year, month, dayOfMonth, hour, minute, second, nanoOfSecond);308return new OffsetDateTime(dt, offset);309}310311//-----------------------------------------------------------------------312/**313* Obtains an instance of {@code OffsetDateTime} from an {@code Instant} and zone ID.314* <p>315* This creates an offset date-time with the same instant as that specified.316* Finding the offset from UTC/Greenwich is simple as there is only one valid317* offset for each instant.318*319* @param instant the instant to create the date-time from, not null320* @param zone the time-zone, which may be an offset, not null321* @return the offset date-time, not null322* @throws DateTimeException if the result exceeds the supported range323*/324public static OffsetDateTime ofInstant(Instant instant, ZoneId zone) {325Objects.requireNonNull(instant, "instant");326Objects.requireNonNull(zone, "zone");327ZoneRules rules = zone.getRules();328ZoneOffset offset = rules.getOffset(instant);329LocalDateTime ldt = LocalDateTime.ofEpochSecond(instant.getEpochSecond(), instant.getNano(), offset);330return new OffsetDateTime(ldt, offset);331}332333//-----------------------------------------------------------------------334/**335* Obtains an instance of {@code OffsetDateTime} from a temporal object.336* <p>337* This obtains an offset date-time based on the specified temporal.338* A {@code TemporalAccessor} represents an arbitrary set of date and time information,339* which this factory converts to an instance of {@code OffsetDateTime}.340* <p>341* The conversion will first obtain a {@code ZoneOffset} from the temporal object.342* It will then try to obtain a {@code LocalDateTime}, falling back to an {@code Instant} if necessary.343* The result will be the combination of {@code ZoneOffset} with either344* with {@code LocalDateTime} or {@code Instant}.345* Implementations are permitted to perform optimizations such as accessing346* those fields that are equivalent to the relevant objects.347* <p>348* This method matches the signature of the functional interface {@link TemporalQuery}349* allowing it to be used as a query via method reference, {@code OffsetDateTime::from}.350*351* @param temporal the temporal object to convert, not null352* @return the offset date-time, not null353* @throws DateTimeException if unable to convert to an {@code OffsetDateTime}354*/355public static OffsetDateTime from(TemporalAccessor temporal) {356if (temporal instanceof OffsetDateTime) {357return (OffsetDateTime) temporal;358}359try {360ZoneOffset offset = ZoneOffset.from(temporal);361LocalDate date = temporal.query(TemporalQueries.localDate());362LocalTime time = temporal.query(TemporalQueries.localTime());363if (date != null && time != null) {364return OffsetDateTime.of(date, time, offset);365} else {366Instant instant = Instant.from(temporal);367return OffsetDateTime.ofInstant(instant, offset);368}369} catch (DateTimeException ex) {370throw new DateTimeException("Unable to obtain OffsetDateTime from TemporalAccessor: " +371temporal + " of type " + temporal.getClass().getName(), ex);372}373}374375//-----------------------------------------------------------------------376/**377* Obtains an instance of {@code OffsetDateTime} from a text string378* such as {@code 2007-12-03T10:15:30+01:00}.379* <p>380* The string must represent a valid date-time and is parsed using381* {@link java.time.format.DateTimeFormatter#ISO_OFFSET_DATE_TIME}.382*383* @param text the text to parse such as "2007-12-03T10:15:30+01:00", not null384* @return the parsed offset date-time, not null385* @throws DateTimeParseException if the text cannot be parsed386*/387public static OffsetDateTime parse(CharSequence text) {388return parse(text, DateTimeFormatter.ISO_OFFSET_DATE_TIME);389}390391/**392* Obtains an instance of {@code OffsetDateTime} from a text string using a specific formatter.393* <p>394* The text is parsed using the formatter, returning a date-time.395*396* @param text the text to parse, not null397* @param formatter the formatter to use, not null398* @return the parsed offset date-time, not null399* @throws DateTimeParseException if the text cannot be parsed400*/401public static OffsetDateTime parse(CharSequence text, DateTimeFormatter formatter) {402Objects.requireNonNull(formatter, "formatter");403return formatter.parse(text, OffsetDateTime::from);404}405406//-----------------------------------------------------------------------407/**408* Constructor.409*410* @param dateTime the local date-time, not null411* @param offset the zone offset, not null412*/413private OffsetDateTime(LocalDateTime dateTime, ZoneOffset offset) {414this.dateTime = Objects.requireNonNull(dateTime, "dateTime");415this.offset = Objects.requireNonNull(offset, "offset");416}417418/**419* Returns a new date-time based on this one, returning {@code this} where possible.420*421* @param dateTime the date-time to create with, not null422* @param offset the zone offset to create with, not null423*/424private OffsetDateTime with(LocalDateTime dateTime, ZoneOffset offset) {425if (this.dateTime == dateTime && this.offset.equals(offset)) {426return this;427}428return new OffsetDateTime(dateTime, offset);429}430431//-----------------------------------------------------------------------432/**433* Checks if the specified field is supported.434* <p>435* This checks if this date-time can be queried for the specified field.436* If false, then calling the {@link #range(TemporalField) range},437* {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}438* methods will throw an exception.439* <p>440* If the field is a {@link ChronoField} then the query is implemented here.441* The supported fields are:442* <ul>443* <li>{@code NANO_OF_SECOND}444* <li>{@code NANO_OF_DAY}445* <li>{@code MICRO_OF_SECOND}446* <li>{@code MICRO_OF_DAY}447* <li>{@code MILLI_OF_SECOND}448* <li>{@code MILLI_OF_DAY}449* <li>{@code SECOND_OF_MINUTE}450* <li>{@code SECOND_OF_DAY}451* <li>{@code MINUTE_OF_HOUR}452* <li>{@code MINUTE_OF_DAY}453* <li>{@code HOUR_OF_AMPM}454* <li>{@code CLOCK_HOUR_OF_AMPM}455* <li>{@code HOUR_OF_DAY}456* <li>{@code CLOCK_HOUR_OF_DAY}457* <li>{@code AMPM_OF_DAY}458* <li>{@code DAY_OF_WEEK}459* <li>{@code ALIGNED_DAY_OF_WEEK_IN_MONTH}460* <li>{@code ALIGNED_DAY_OF_WEEK_IN_YEAR}461* <li>{@code DAY_OF_MONTH}462* <li>{@code DAY_OF_YEAR}463* <li>{@code EPOCH_DAY}464* <li>{@code ALIGNED_WEEK_OF_MONTH}465* <li>{@code ALIGNED_WEEK_OF_YEAR}466* <li>{@code MONTH_OF_YEAR}467* <li>{@code PROLEPTIC_MONTH}468* <li>{@code YEAR_OF_ERA}469* <li>{@code YEAR}470* <li>{@code ERA}471* <li>{@code INSTANT_SECONDS}472* <li>{@code OFFSET_SECONDS}473* </ul>474* All other {@code ChronoField} instances will return false.475* <p>476* If the field is not a {@code ChronoField}, then the result of this method477* is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}478* passing {@code this} as the argument.479* Whether the field is supported is determined by the field.480*481* @param field the field to check, null returns false482* @return true if the field is supported on this date-time, false if not483*/484@Override485public boolean isSupported(TemporalField field) {486return field instanceof ChronoField || (field != null && field.isSupportedBy(this));487}488489/**490* Checks if the specified unit is supported.491* <p>492* This checks if the specified unit can be added to, or subtracted from, this date-time.493* If false, then calling the {@link #plus(long, TemporalUnit)} and494* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.495* <p>496* If the unit is a {@link ChronoUnit} then the query is implemented here.497* The supported units are:498* <ul>499* <li>{@code NANOS}500* <li>{@code MICROS}501* <li>{@code MILLIS}502* <li>{@code SECONDS}503* <li>{@code MINUTES}504* <li>{@code HOURS}505* <li>{@code HALF_DAYS}506* <li>{@code DAYS}507* <li>{@code WEEKS}508* <li>{@code MONTHS}509* <li>{@code YEARS}510* <li>{@code DECADES}511* <li>{@code CENTURIES}512* <li>{@code MILLENNIA}513* <li>{@code ERAS}514* </ul>515* All other {@code ChronoUnit} instances will return false.516* <p>517* If the unit is not a {@code ChronoUnit}, then the result of this method518* is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}519* passing {@code this} as the argument.520* Whether the unit is supported is determined by the unit.521*522* @param unit the unit to check, null returns false523* @return true if the unit can be added/subtracted, false if not524*/525@Override // override for Javadoc526public boolean isSupported(TemporalUnit unit) {527if (unit instanceof ChronoUnit) {528return unit != FOREVER;529}530return unit != null && unit.isSupportedBy(this);531}532533//-----------------------------------------------------------------------534/**535* Gets the range of valid values for the specified field.536* <p>537* The range object expresses the minimum and maximum valid values for a field.538* This date-time is used to enhance the accuracy of the returned range.539* If it is not possible to return the range, because the field is not supported540* or for some other reason, an exception is thrown.541* <p>542* If the field is a {@link ChronoField} then the query is implemented here.543* The {@link #isSupported(TemporalField) supported fields} will return544* appropriate range instances.545* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.546* <p>547* If the field is not a {@code ChronoField}, then the result of this method548* is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}549* passing {@code this} as the argument.550* Whether the range can be obtained is determined by the field.551*552* @param field the field to query the range for, not null553* @return the range of valid values for the field, not null554* @throws DateTimeException if the range for the field cannot be obtained555* @throws UnsupportedTemporalTypeException if the field is not supported556*/557@Override558public ValueRange range(TemporalField field) {559if (field instanceof ChronoField) {560if (field == INSTANT_SECONDS || field == OFFSET_SECONDS) {561return field.range();562}563return dateTime.range(field);564}565return field.rangeRefinedBy(this);566}567568/**569* Gets the value of the specified field from this date-time as an {@code int}.570* <p>571* This queries this date-time for the value of the specified field.572* The returned value will always be within the valid range of values for the field.573* If it is not possible to return the value, because the field is not supported574* or for some other reason, an exception is thrown.575* <p>576* If the field is a {@link ChronoField} then the query is implemented here.577* The {@link #isSupported(TemporalField) supported fields} will return valid578* values based on this date-time, except {@code NANO_OF_DAY}, {@code MICRO_OF_DAY},579* {@code EPOCH_DAY}, {@code PROLEPTIC_MONTH} and {@code INSTANT_SECONDS} which are too580* large to fit in an {@code int} and throw an {@code UnsupportedTemporalTypeException}.581* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.582* <p>583* If the field is not a {@code ChronoField}, then the result of this method584* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}585* passing {@code this} as the argument. Whether the value can be obtained,586* and what the value represents, is determined by the field.587*588* @param field the field to get, not null589* @return the value for the field590* @throws DateTimeException if a value for the field cannot be obtained or591* the value is outside the range of valid values for the field592* @throws UnsupportedTemporalTypeException if the field is not supported or593* the range of values exceeds an {@code int}594* @throws ArithmeticException if numeric overflow occurs595*/596@Override597public int get(TemporalField field) {598if (field instanceof ChronoField chronoField) {599switch (chronoField) {600case INSTANT_SECONDS:601throw new UnsupportedTemporalTypeException("Invalid field 'InstantSeconds' for get() method, use getLong() instead");602case OFFSET_SECONDS:603return getOffset().getTotalSeconds();604}605return dateTime.get(field);606}607return Temporal.super.get(field);608}609610/**611* Gets the value of the specified field from this date-time as a {@code long}.612* <p>613* This queries this date-time for the value of the specified field.614* If it is not possible to return the value, because the field is not supported615* or for some other reason, an exception is thrown.616* <p>617* If the field is a {@link ChronoField} then the query is implemented here.618* The {@link #isSupported(TemporalField) supported fields} will return valid619* values based on this date-time.620* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.621* <p>622* If the field is not a {@code ChronoField}, then the result of this method623* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}624* passing {@code this} as the argument. Whether the value can be obtained,625* and what the value represents, is determined by the field.626*627* @param field the field to get, not null628* @return the value for the field629* @throws DateTimeException if a value for the field cannot be obtained630* @throws UnsupportedTemporalTypeException if the field is not supported631* @throws ArithmeticException if numeric overflow occurs632*/633@Override634public long getLong(TemporalField field) {635if (field instanceof ChronoField chronoField) {636switch (chronoField) {637case INSTANT_SECONDS: return toEpochSecond();638case OFFSET_SECONDS: return getOffset().getTotalSeconds();639}640return dateTime.getLong(field);641}642return field.getFrom(this);643}644645//-----------------------------------------------------------------------646/**647* Gets the zone offset, such as '+01:00'.648* <p>649* This is the offset of the local date-time from UTC/Greenwich.650*651* @return the zone offset, not null652*/653public ZoneOffset getOffset() {654return offset;655}656657/**658* Returns a copy of this {@code OffsetDateTime} with the specified offset ensuring659* that the result has the same local date-time.660* <p>661* This method returns an object with the same {@code LocalDateTime} and the specified {@code ZoneOffset}.662* No calculation is needed or performed.663* For example, if this time represents {@code 2007-12-03T10:30+02:00} and the offset specified is664* {@code +03:00}, then this method will return {@code 2007-12-03T10:30+03:00}.665* <p>666* To take into account the difference between the offsets, and adjust the time fields,667* use {@link #withOffsetSameInstant}.668* <p>669* This instance is immutable and unaffected by this method call.670*671* @param offset the zone offset to change to, not null672* @return an {@code OffsetDateTime} based on this date-time with the requested offset, not null673*/674public OffsetDateTime withOffsetSameLocal(ZoneOffset offset) {675return with(dateTime, offset);676}677678/**679* Returns a copy of this {@code OffsetDateTime} with the specified offset ensuring680* that the result is at the same instant.681* <p>682* This method returns an object with the specified {@code ZoneOffset} and a {@code LocalDateTime}683* adjusted by the difference between the two offsets.684* This will result in the old and new objects representing the same instant.685* This is useful for finding the local time in a different offset.686* For example, if this time represents {@code 2007-12-03T10:30+02:00} and the offset specified is687* {@code +03:00}, then this method will return {@code 2007-12-03T11:30+03:00}.688* <p>689* To change the offset without adjusting the local time use {@link #withOffsetSameLocal}.690* <p>691* This instance is immutable and unaffected by this method call.692*693* @param offset the zone offset to change to, not null694* @return an {@code OffsetDateTime} based on this date-time with the requested offset, not null695* @throws DateTimeException if the result exceeds the supported date range696*/697public OffsetDateTime withOffsetSameInstant(ZoneOffset offset) {698if (offset.equals(this.offset)) {699return this;700}701int difference = offset.getTotalSeconds() - this.offset.getTotalSeconds();702LocalDateTime adjusted = dateTime.plusSeconds(difference);703return new OffsetDateTime(adjusted, offset);704}705706//-----------------------------------------------------------------------707/**708* Gets the {@code LocalDateTime} part of this date-time.709* <p>710* This returns a {@code LocalDateTime} with the same year, month, day and time711* as this date-time.712*713* @return the local date-time part of this date-time, not null714*/715public LocalDateTime toLocalDateTime() {716return dateTime;717}718719//-----------------------------------------------------------------------720/**721* Gets the {@code LocalDate} part of this date-time.722* <p>723* This returns a {@code LocalDate} with the same year, month and day724* as this date-time.725*726* @return the date part of this date-time, not null727*/728public LocalDate toLocalDate() {729return dateTime.toLocalDate();730}731732/**733* Gets the year field.734* <p>735* This method returns the primitive {@code int} value for the year.736* <p>737* The year returned by this method is proleptic as per {@code get(YEAR)}.738* To obtain the year-of-era, use {@code get(YEAR_OF_ERA)}.739*740* @return the year, from MIN_YEAR to MAX_YEAR741*/742public int getYear() {743return dateTime.getYear();744}745746/**747* Gets the month-of-year field from 1 to 12.748* <p>749* This method returns the month as an {@code int} from 1 to 12.750* Application code is frequently clearer if the enum {@link Month}751* is used by calling {@link #getMonth()}.752*753* @return the month-of-year, from 1 to 12754* @see #getMonth()755*/756public int getMonthValue() {757return dateTime.getMonthValue();758}759760/**761* Gets the month-of-year field using the {@code Month} enum.762* <p>763* This method returns the enum {@link Month} for the month.764* This avoids confusion as to what {@code int} values mean.765* If you need access to the primitive {@code int} value then the enum766* provides the {@link Month#getValue() int value}.767*768* @return the month-of-year, not null769* @see #getMonthValue()770*/771public Month getMonth() {772return dateTime.getMonth();773}774775/**776* Gets the day-of-month field.777* <p>778* This method returns the primitive {@code int} value for the day-of-month.779*780* @return the day-of-month, from 1 to 31781*/782public int getDayOfMonth() {783return dateTime.getDayOfMonth();784}785786/**787* Gets the day-of-year field.788* <p>789* This method returns the primitive {@code int} value for the day-of-year.790*791* @return the day-of-year, from 1 to 365, or 366 in a leap year792*/793public int getDayOfYear() {794return dateTime.getDayOfYear();795}796797/**798* Gets the day-of-week field, which is an enum {@code DayOfWeek}.799* <p>800* This method returns the enum {@link DayOfWeek} for the day-of-week.801* This avoids confusion as to what {@code int} values mean.802* If you need access to the primitive {@code int} value then the enum803* provides the {@link DayOfWeek#getValue() int value}.804* <p>805* Additional information can be obtained from the {@code DayOfWeek}.806* This includes textual names of the values.807*808* @return the day-of-week, not null809*/810public DayOfWeek getDayOfWeek() {811return dateTime.getDayOfWeek();812}813814//-----------------------------------------------------------------------815/**816* Gets the {@code LocalTime} part of this date-time.817* <p>818* This returns a {@code LocalTime} with the same hour, minute, second and819* nanosecond as this date-time.820*821* @return the time part of this date-time, not null822*/823public LocalTime toLocalTime() {824return dateTime.toLocalTime();825}826827/**828* Gets the hour-of-day field.829*830* @return the hour-of-day, from 0 to 23831*/832public int getHour() {833return dateTime.getHour();834}835836/**837* Gets the minute-of-hour field.838*839* @return the minute-of-hour, from 0 to 59840*/841public int getMinute() {842return dateTime.getMinute();843}844845/**846* Gets the second-of-minute field.847*848* @return the second-of-minute, from 0 to 59849*/850public int getSecond() {851return dateTime.getSecond();852}853854/**855* Gets the nano-of-second field.856*857* @return the nano-of-second, from 0 to 999,999,999858*/859public int getNano() {860return dateTime.getNano();861}862863//-----------------------------------------------------------------------864/**865* Returns an adjusted copy of this date-time.866* <p>867* This returns an {@code OffsetDateTime}, based on this one, with the date-time adjusted.868* The adjustment takes place using the specified adjuster strategy object.869* Read the documentation of the adjuster to understand what adjustment will be made.870* <p>871* A simple adjuster might simply set the one of the fields, such as the year field.872* A more complex adjuster might set the date to the last day of the month.873* A selection of common adjustments is provided in874* {@link java.time.temporal.TemporalAdjusters TemporalAdjusters}.875* These include finding the "last day of the month" and "next Wednesday".876* Key date-time classes also implement the {@code TemporalAdjuster} interface,877* such as {@link Month} and {@link java.time.MonthDay MonthDay}.878* The adjuster is responsible for handling special cases, such as the varying879* lengths of month and leap years.880* <p>881* For example this code returns a date on the last day of July:882* <pre>883* import static java.time.Month.*;884* import static java.time.temporal.TemporalAdjusters.*;885*886* result = offsetDateTime.with(JULY).with(lastDayOfMonth());887* </pre>888* <p>889* The classes {@link LocalDate}, {@link LocalTime} and {@link ZoneOffset} implement890* {@code TemporalAdjuster}, thus this method can be used to change the date, time or offset:891* <pre>892* result = offsetDateTime.with(date);893* result = offsetDateTime.with(time);894* result = offsetDateTime.with(offset);895* </pre>896* <p>897* The result of this method is obtained by invoking the898* {@link TemporalAdjuster#adjustInto(Temporal)} method on the899* specified adjuster passing {@code this} as the argument.900* <p>901* This instance is immutable and unaffected by this method call.902*903* @param adjuster the adjuster to use, not null904* @return an {@code OffsetDateTime} based on {@code this} with the adjustment made, not null905* @throws DateTimeException if the adjustment cannot be made906* @throws ArithmeticException if numeric overflow occurs907*/908@Override909public OffsetDateTime with(TemporalAdjuster adjuster) {910// optimizations911if (adjuster instanceof LocalDate || adjuster instanceof LocalTime || adjuster instanceof LocalDateTime) {912return with(dateTime.with(adjuster), offset);913} else if (adjuster instanceof Instant) {914return ofInstant((Instant) adjuster, offset);915} else if (adjuster instanceof ZoneOffset) {916return with(dateTime, (ZoneOffset) adjuster);917} else if (adjuster instanceof OffsetDateTime) {918return (OffsetDateTime) adjuster;919}920return (OffsetDateTime) adjuster.adjustInto(this);921}922923/**924* Returns a copy of this date-time with the specified field set to a new value.925* <p>926* This returns an {@code OffsetDateTime}, based on this one, with the value927* for the specified field changed.928* This can be used to change any supported field, such as the year, month or day-of-month.929* If it is not possible to set the value, because the field is not supported or for930* some other reason, an exception is thrown.931* <p>932* In some cases, changing the specified field can cause the resulting date-time to become invalid,933* such as changing the month from 31st January to February would make the day-of-month invalid.934* In cases like this, the field is responsible for resolving the date. Typically it will choose935* the previous valid date, which would be the last valid day of February in this example.936* <p>937* If the field is a {@link ChronoField} then the adjustment is implemented here.938* <p>939* The {@code INSTANT_SECONDS} field will return a date-time with the specified instant.940* The offset and nano-of-second are unchanged.941* If the new instant value is outside the valid range then a {@code DateTimeException} will be thrown.942* <p>943* The {@code OFFSET_SECONDS} field will return a date-time with the specified offset.944* The local date-time is unaltered. If the new offset value is outside the valid range945* then a {@code DateTimeException} will be thrown.946* <p>947* The other {@link #isSupported(TemporalField) supported fields} will behave as per948* the matching method on {@link LocalDateTime#with(TemporalField, long) LocalDateTime}.949* In this case, the offset is not part of the calculation and will be unchanged.950* <p>951* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.952* <p>953* If the field is not a {@code ChronoField}, then the result of this method954* is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}955* passing {@code this} as the argument. In this case, the field determines956* whether and how to adjust the instant.957* <p>958* This instance is immutable and unaffected by this method call.959*960* @param field the field to set in the result, not null961* @param newValue the new value of the field in the result962* @return an {@code OffsetDateTime} based on {@code this} with the specified field set, not null963* @throws DateTimeException if the field cannot be set964* @throws UnsupportedTemporalTypeException if the field is not supported965* @throws ArithmeticException if numeric overflow occurs966*/967@Override968public OffsetDateTime with(TemporalField field, long newValue) {969if (field instanceof ChronoField chronoField) {970switch (chronoField) {971case INSTANT_SECONDS: return ofInstant(Instant.ofEpochSecond(newValue, getNano()), offset);972case OFFSET_SECONDS: {973return with(dateTime, ZoneOffset.ofTotalSeconds(chronoField.checkValidIntValue(newValue)));974}975}976return with(dateTime.with(field, newValue), offset);977}978return field.adjustInto(this, newValue);979}980981//-----------------------------------------------------------------------982/**983* Returns a copy of this {@code OffsetDateTime} with the year altered.984* <p>985* The time and offset do not affect the calculation and will be the same in the result.986* If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.987* <p>988* This instance is immutable and unaffected by this method call.989*990* @param year the year to set in the result, from MIN_YEAR to MAX_YEAR991* @return an {@code OffsetDateTime} based on this date-time with the requested year, not null992* @throws DateTimeException if the year value is invalid993*/994public OffsetDateTime withYear(int year) {995return with(dateTime.withYear(year), offset);996}997998/**999* Returns a copy of this {@code OffsetDateTime} with the month-of-year altered.1000* <p>1001* The time and offset do not affect the calculation and will be the same in the result.1002* If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.1003* <p>1004* This instance is immutable and unaffected by this method call.1005*1006* @param month the month-of-year to set in the result, from 1 (January) to 12 (December)1007* @return an {@code OffsetDateTime} based on this date-time with the requested month, not null1008* @throws DateTimeException if the month-of-year value is invalid1009*/1010public OffsetDateTime withMonth(int month) {1011return with(dateTime.withMonth(month), offset);1012}10131014/**1015* Returns a copy of this {@code OffsetDateTime} with the day-of-month altered.1016* <p>1017* If the resulting {@code OffsetDateTime} is invalid, an exception is thrown.1018* The time and offset do not affect the calculation and will be the same in the result.1019* <p>1020* This instance is immutable and unaffected by this method call.1021*1022* @param dayOfMonth the day-of-month to set in the result, from 1 to 28-311023* @return an {@code OffsetDateTime} based on this date-time with the requested day, not null1024* @throws DateTimeException if the day-of-month value is invalid,1025* or if the day-of-month is invalid for the month-year1026*/1027public OffsetDateTime withDayOfMonth(int dayOfMonth) {1028return with(dateTime.withDayOfMonth(dayOfMonth), offset);1029}10301031/**1032* Returns a copy of this {@code OffsetDateTime} with the day-of-year altered.1033* <p>1034* The time and offset do not affect the calculation and will be the same in the result.1035* If the resulting {@code OffsetDateTime} is invalid, an exception is thrown.1036* <p>1037* This instance is immutable and unaffected by this method call.1038*1039* @param dayOfYear the day-of-year to set in the result, from 1 to 365-3661040* @return an {@code OffsetDateTime} based on this date with the requested day, not null1041* @throws DateTimeException if the day-of-year value is invalid,1042* or if the day-of-year is invalid for the year1043*/1044public OffsetDateTime withDayOfYear(int dayOfYear) {1045return with(dateTime.withDayOfYear(dayOfYear), offset);1046}10471048//-----------------------------------------------------------------------1049/**1050* Returns a copy of this {@code OffsetDateTime} with the hour-of-day altered.1051* <p>1052* The date and offset do not affect the calculation and will be the same in the result.1053* <p>1054* This instance is immutable and unaffected by this method call.1055*1056* @param hour the hour-of-day to set in the result, from 0 to 231057* @return an {@code OffsetDateTime} based on this date-time with the requested hour, not null1058* @throws DateTimeException if the hour value is invalid1059*/1060public OffsetDateTime withHour(int hour) {1061return with(dateTime.withHour(hour), offset);1062}10631064/**1065* Returns a copy of this {@code OffsetDateTime} with the minute-of-hour altered.1066* <p>1067* The date and offset do not affect the calculation and will be the same in the result.1068* <p>1069* This instance is immutable and unaffected by this method call.1070*1071* @param minute the minute-of-hour to set in the result, from 0 to 591072* @return an {@code OffsetDateTime} based on this date-time with the requested minute, not null1073* @throws DateTimeException if the minute value is invalid1074*/1075public OffsetDateTime withMinute(int minute) {1076return with(dateTime.withMinute(minute), offset);1077}10781079/**1080* Returns a copy of this {@code OffsetDateTime} with the second-of-minute altered.1081* <p>1082* The date and offset do not affect the calculation and will be the same in the result.1083* <p>1084* This instance is immutable and unaffected by this method call.1085*1086* @param second the second-of-minute to set in the result, from 0 to 591087* @return an {@code OffsetDateTime} based on this date-time with the requested second, not null1088* @throws DateTimeException if the second value is invalid1089*/1090public OffsetDateTime withSecond(int second) {1091return with(dateTime.withSecond(second), offset);1092}10931094/**1095* Returns a copy of this {@code OffsetDateTime} with the nano-of-second altered.1096* <p>1097* The date and offset do not affect the calculation and will be the same in the result.1098* <p>1099* This instance is immutable and unaffected by this method call.1100*1101* @param nanoOfSecond the nano-of-second to set in the result, from 0 to 999,999,9991102* @return an {@code OffsetDateTime} based on this date-time with the requested nanosecond, not null1103* @throws DateTimeException if the nano value is invalid1104*/1105public OffsetDateTime withNano(int nanoOfSecond) {1106return with(dateTime.withNano(nanoOfSecond), offset);1107}11081109//-----------------------------------------------------------------------1110/**1111* Returns a copy of this {@code OffsetDateTime} with the time truncated.1112* <p>1113* Truncation returns a copy of the original date-time with fields1114* smaller than the specified unit set to zero.1115* For example, truncating with the {@link ChronoUnit#MINUTES minutes} unit1116* will set the second-of-minute and nano-of-second field to zero.1117* <p>1118* The unit must have a {@linkplain TemporalUnit#getDuration() duration}1119* that divides into the length of a standard day without remainder.1120* This includes all supplied time units on {@link ChronoUnit} and1121* {@link ChronoUnit#DAYS DAYS}. Other units throw an exception.1122* <p>1123* The offset does not affect the calculation and will be the same in the result.1124* <p>1125* This instance is immutable and unaffected by this method call.1126*1127* @param unit the unit to truncate to, not null1128* @return an {@code OffsetDateTime} based on this date-time with the time truncated, not null1129* @throws DateTimeException if unable to truncate1130* @throws UnsupportedTemporalTypeException if the unit is not supported1131*/1132public OffsetDateTime truncatedTo(TemporalUnit unit) {1133return with(dateTime.truncatedTo(unit), offset);1134}11351136//-----------------------------------------------------------------------1137/**1138* Returns a copy of this date-time with the specified amount added.1139* <p>1140* This returns an {@code OffsetDateTime}, based on this one, with the specified amount added.1141* The amount is typically {@link Period} or {@link Duration} but may be1142* any other type implementing the {@link TemporalAmount} interface.1143* <p>1144* The calculation is delegated to the amount object by calling1145* {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free1146* to implement the addition in any way it wishes, however it typically1147* calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation1148* of the amount implementation to determine if it can be successfully added.1149* <p>1150* This instance is immutable and unaffected by this method call.1151*1152* @param amountToAdd the amount to add, not null1153* @return an {@code OffsetDateTime} based on this date-time with the addition made, not null1154* @throws DateTimeException if the addition cannot be made1155* @throws ArithmeticException if numeric overflow occurs1156*/1157@Override1158public OffsetDateTime plus(TemporalAmount amountToAdd) {1159return (OffsetDateTime) amountToAdd.addTo(this);1160}11611162/**1163* Returns a copy of this date-time with the specified amount added.1164* <p>1165* This returns an {@code OffsetDateTime}, based on this one, with the amount1166* in terms of the unit added. If it is not possible to add the amount, because the1167* unit is not supported or for some other reason, an exception is thrown.1168* <p>1169* If the field is a {@link ChronoUnit} then the addition is implemented by1170* {@link LocalDateTime#plus(long, TemporalUnit)}.1171* The offset is not part of the calculation and will be unchanged in the result.1172* <p>1173* If the field is not a {@code ChronoUnit}, then the result of this method1174* is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}1175* passing {@code this} as the argument. In this case, the unit determines1176* whether and how to perform the addition.1177* <p>1178* This instance is immutable and unaffected by this method call.1179*1180* @param amountToAdd the amount of the unit to add to the result, may be negative1181* @param unit the unit of the amount to add, not null1182* @return an {@code OffsetDateTime} based on this date-time with the specified amount added, not null1183* @throws DateTimeException if the addition cannot be made1184* @throws UnsupportedTemporalTypeException if the unit is not supported1185* @throws ArithmeticException if numeric overflow occurs1186*/1187@Override1188public OffsetDateTime plus(long amountToAdd, TemporalUnit unit) {1189if (unit instanceof ChronoUnit) {1190return with(dateTime.plus(amountToAdd, unit), offset);1191}1192return unit.addTo(this, amountToAdd);1193}11941195//-----------------------------------------------------------------------1196/**1197* Returns a copy of this {@code OffsetDateTime} with the specified number of years added.1198* <p>1199* This method adds the specified amount to the years field in three steps:1200* <ol>1201* <li>Add the input years to the year field</li>1202* <li>Check if the resulting date would be invalid</li>1203* <li>Adjust the day-of-month to the last valid day if necessary</li>1204* </ol>1205* <p>1206* For example, 2008-02-29 (leap year) plus one year would result in the1207* invalid date 2009-02-29 (standard year). Instead of returning an invalid1208* result, the last valid day of the month, 2009-02-28, is selected instead.1209* <p>1210* This instance is immutable and unaffected by this method call.1211*1212* @param years the years to add, may be negative1213* @return an {@code OffsetDateTime} based on this date-time with the years added, not null1214* @throws DateTimeException if the result exceeds the supported date range1215*/1216public OffsetDateTime plusYears(long years) {1217return with(dateTime.plusYears(years), offset);1218}12191220/**1221* Returns a copy of this {@code OffsetDateTime} with the specified number of months added.1222* <p>1223* This method adds the specified amount to the months field in three steps:1224* <ol>1225* <li>Add the input months to the month-of-year field</li>1226* <li>Check if the resulting date would be invalid</li>1227* <li>Adjust the day-of-month to the last valid day if necessary</li>1228* </ol>1229* <p>1230* For example, 2007-03-31 plus one month would result in the invalid date1231* 2007-04-31. Instead of returning an invalid result, the last valid day1232* of the month, 2007-04-30, is selected instead.1233* <p>1234* This instance is immutable and unaffected by this method call.1235*1236* @param months the months to add, may be negative1237* @return an {@code OffsetDateTime} based on this date-time with the months added, not null1238* @throws DateTimeException if the result exceeds the supported date range1239*/1240public OffsetDateTime plusMonths(long months) {1241return with(dateTime.plusMonths(months), offset);1242}12431244/**1245* Returns a copy of this OffsetDateTime with the specified number of weeks added.1246* <p>1247* This method adds the specified amount in weeks to the days field incrementing1248* the month and year fields as necessary to ensure the result remains valid.1249* The result is only invalid if the maximum/minimum year is exceeded.1250* <p>1251* For example, 2008-12-31 plus one week would result in 2009-01-07.1252* <p>1253* This instance is immutable and unaffected by this method call.1254*1255* @param weeks the weeks to add, may be negative1256* @return an {@code OffsetDateTime} based on this date-time with the weeks added, not null1257* @throws DateTimeException if the result exceeds the supported date range1258*/1259public OffsetDateTime plusWeeks(long weeks) {1260return with(dateTime.plusWeeks(weeks), offset);1261}12621263/**1264* Returns a copy of this OffsetDateTime with the specified number of days added.1265* <p>1266* This method adds the specified amount to the days field incrementing the1267* month and year fields as necessary to ensure the result remains valid.1268* The result is only invalid if the maximum/minimum year is exceeded.1269* <p>1270* For example, 2008-12-31 plus one day would result in 2009-01-01.1271* <p>1272* This instance is immutable and unaffected by this method call.1273*1274* @param days the days to add, may be negative1275* @return an {@code OffsetDateTime} based on this date-time with the days added, not null1276* @throws DateTimeException if the result exceeds the supported date range1277*/1278public OffsetDateTime plusDays(long days) {1279return with(dateTime.plusDays(days), offset);1280}12811282/**1283* Returns a copy of this {@code OffsetDateTime} with the specified number of hours added.1284* <p>1285* This instance is immutable and unaffected by this method call.1286*1287* @param hours the hours to add, may be negative1288* @return an {@code OffsetDateTime} based on this date-time with the hours added, not null1289* @throws DateTimeException if the result exceeds the supported date range1290*/1291public OffsetDateTime plusHours(long hours) {1292return with(dateTime.plusHours(hours), offset);1293}12941295/**1296* Returns a copy of this {@code OffsetDateTime} with the specified number of minutes added.1297* <p>1298* This instance is immutable and unaffected by this method call.1299*1300* @param minutes the minutes to add, may be negative1301* @return an {@code OffsetDateTime} based on this date-time with the minutes added, not null1302* @throws DateTimeException if the result exceeds the supported date range1303*/1304public OffsetDateTime plusMinutes(long minutes) {1305return with(dateTime.plusMinutes(minutes), offset);1306}13071308/**1309* Returns a copy of this {@code OffsetDateTime} with the specified number of seconds added.1310* <p>1311* This instance is immutable and unaffected by this method call.1312*1313* @param seconds the seconds to add, may be negative1314* @return an {@code OffsetDateTime} based on this date-time with the seconds added, not null1315* @throws DateTimeException if the result exceeds the supported date range1316*/1317public OffsetDateTime plusSeconds(long seconds) {1318return with(dateTime.plusSeconds(seconds), offset);1319}13201321/**1322* Returns a copy of this {@code OffsetDateTime} with the specified number of nanoseconds added.1323* <p>1324* This instance is immutable and unaffected by this method call.1325*1326* @param nanos the nanos to add, may be negative1327* @return an {@code OffsetDateTime} based on this date-time with the nanoseconds added, not null1328* @throws DateTimeException if the unit cannot be added to this type1329*/1330public OffsetDateTime plusNanos(long nanos) {1331return with(dateTime.plusNanos(nanos), offset);1332}13331334//-----------------------------------------------------------------------1335/**1336* Returns a copy of this date-time with the specified amount subtracted.1337* <p>1338* This returns an {@code OffsetDateTime}, based on this one, with the specified amount subtracted.1339* The amount is typically {@link Period} or {@link Duration} but may be1340* any other type implementing the {@link TemporalAmount} interface.1341* <p>1342* The calculation is delegated to the amount object by calling1343* {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free1344* to implement the subtraction in any way it wishes, however it typically1345* calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation1346* of the amount implementation to determine if it can be successfully subtracted.1347* <p>1348* This instance is immutable and unaffected by this method call.1349*1350* @param amountToSubtract the amount to subtract, not null1351* @return an {@code OffsetDateTime} based on this date-time with the subtraction made, not null1352* @throws DateTimeException if the subtraction cannot be made1353* @throws ArithmeticException if numeric overflow occurs1354*/1355@Override1356public OffsetDateTime minus(TemporalAmount amountToSubtract) {1357return (OffsetDateTime) amountToSubtract.subtractFrom(this);1358}13591360/**1361* Returns a copy of this date-time with the specified amount subtracted.1362* <p>1363* This returns an {@code OffsetDateTime}, based on this one, with the amount1364* in terms of the unit subtracted. If it is not possible to subtract the amount,1365* because the unit is not supported or for some other reason, an exception is thrown.1366* <p>1367* This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.1368* See that method for a full description of how addition, and thus subtraction, works.1369* <p>1370* This instance is immutable and unaffected by this method call.1371*1372* @param amountToSubtract the amount of the unit to subtract from the result, may be negative1373* @param unit the unit of the amount to subtract, not null1374* @return an {@code OffsetDateTime} based on this date-time with the specified amount subtracted, not null1375* @throws DateTimeException if the subtraction cannot be made1376* @throws UnsupportedTemporalTypeException if the unit is not supported1377* @throws ArithmeticException if numeric overflow occurs1378*/1379@Override1380public OffsetDateTime minus(long amountToSubtract, TemporalUnit unit) {1381return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));1382}13831384//-----------------------------------------------------------------------1385/**1386* Returns a copy of this {@code OffsetDateTime} with the specified number of years subtracted.1387* <p>1388* This method subtracts the specified amount from the years field in three steps:1389* <ol>1390* <li>Subtract the input years from the year field</li>1391* <li>Check if the resulting date would be invalid</li>1392* <li>Adjust the day-of-month to the last valid day if necessary</li>1393* </ol>1394* <p>1395* For example, 2008-02-29 (leap year) minus one year would result in the1396* invalid date 2007-02-29 (standard year). Instead of returning an invalid1397* result, the last valid day of the month, 2007-02-28, is selected instead.1398* <p>1399* This instance is immutable and unaffected by this method call.1400*1401* @param years the years to subtract, may be negative1402* @return an {@code OffsetDateTime} based on this date-time with the years subtracted, not null1403* @throws DateTimeException if the result exceeds the supported date range1404*/1405public OffsetDateTime minusYears(long years) {1406return (years == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-years));1407}14081409/**1410* Returns a copy of this {@code OffsetDateTime} with the specified number of months subtracted.1411* <p>1412* This method subtracts the specified amount from the months field in three steps:1413* <ol>1414* <li>Subtract the input months from the month-of-year field</li>1415* <li>Check if the resulting date would be invalid</li>1416* <li>Adjust the day-of-month to the last valid day if necessary</li>1417* </ol>1418* <p>1419* For example, 2007-03-31 minus one month would result in the invalid date1420* 2007-02-31. Instead of returning an invalid result, the last valid day1421* of the month, 2007-02-28, is selected instead.1422* <p>1423* This instance is immutable and unaffected by this method call.1424*1425* @param months the months to subtract, may be negative1426* @return an {@code OffsetDateTime} based on this date-time with the months subtracted, not null1427* @throws DateTimeException if the result exceeds the supported date range1428*/1429public OffsetDateTime minusMonths(long months) {1430return (months == Long.MIN_VALUE ? plusMonths(Long.MAX_VALUE).plusMonths(1) : plusMonths(-months));1431}14321433/**1434* Returns a copy of this {@code OffsetDateTime} with the specified number of weeks subtracted.1435* <p>1436* This method subtracts the specified amount in weeks from the days field decrementing1437* the month and year fields as necessary to ensure the result remains valid.1438* The result is only invalid if the maximum/minimum year is exceeded.1439* <p>1440* For example, 2009-01-07 minus one week would result in 2008-12-31.1441* <p>1442* This instance is immutable and unaffected by this method call.1443*1444* @param weeks the weeks to subtract, may be negative1445* @return an {@code OffsetDateTime} based on this date-time with the weeks subtracted, not null1446* @throws DateTimeException if the result exceeds the supported date range1447*/1448public OffsetDateTime minusWeeks(long weeks) {1449return (weeks == Long.MIN_VALUE ? plusWeeks(Long.MAX_VALUE).plusWeeks(1) : plusWeeks(-weeks));1450}14511452/**1453* Returns a copy of this {@code OffsetDateTime} with the specified number of days subtracted.1454* <p>1455* This method subtracts the specified amount from the days field decrementing the1456* month and year fields as necessary to ensure the result remains valid.1457* The result is only invalid if the maximum/minimum year is exceeded.1458* <p>1459* For example, 2009-01-01 minus one day would result in 2008-12-31.1460* <p>1461* This instance is immutable and unaffected by this method call.1462*1463* @param days the days to subtract, may be negative1464* @return an {@code OffsetDateTime} based on this date-time with the days subtracted, not null1465* @throws DateTimeException if the result exceeds the supported date range1466*/1467public OffsetDateTime minusDays(long days) {1468return (days == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-days));1469}14701471/**1472* Returns a copy of this {@code OffsetDateTime} with the specified number of hours subtracted.1473* <p>1474* This instance is immutable and unaffected by this method call.1475*1476* @param hours the hours to subtract, may be negative1477* @return an {@code OffsetDateTime} based on this date-time with the hours subtracted, not null1478* @throws DateTimeException if the result exceeds the supported date range1479*/1480public OffsetDateTime minusHours(long hours) {1481return (hours == Long.MIN_VALUE ? plusHours(Long.MAX_VALUE).plusHours(1) : plusHours(-hours));1482}14831484/**1485* Returns a copy of this {@code OffsetDateTime} with the specified number of minutes subtracted.1486* <p>1487* This instance is immutable and unaffected by this method call.1488*1489* @param minutes the minutes to subtract, may be negative1490* @return an {@code OffsetDateTime} based on this date-time with the minutes subtracted, not null1491* @throws DateTimeException if the result exceeds the supported date range1492*/1493public OffsetDateTime minusMinutes(long minutes) {1494return (minutes == Long.MIN_VALUE ? plusMinutes(Long.MAX_VALUE).plusMinutes(1) : plusMinutes(-minutes));1495}14961497/**1498* Returns a copy of this {@code OffsetDateTime} with the specified number of seconds subtracted.1499* <p>1500* This instance is immutable and unaffected by this method call.1501*1502* @param seconds the seconds to subtract, may be negative1503* @return an {@code OffsetDateTime} based on this date-time with the seconds subtracted, not null1504* @throws DateTimeException if the result exceeds the supported date range1505*/1506public OffsetDateTime minusSeconds(long seconds) {1507return (seconds == Long.MIN_VALUE ? plusSeconds(Long.MAX_VALUE).plusSeconds(1) : plusSeconds(-seconds));1508}15091510/**1511* Returns a copy of this {@code OffsetDateTime} with the specified number of nanoseconds subtracted.1512* <p>1513* This instance is immutable and unaffected by this method call.1514*1515* @param nanos the nanos to subtract, may be negative1516* @return an {@code OffsetDateTime} based on this date-time with the nanoseconds subtracted, not null1517* @throws DateTimeException if the result exceeds the supported date range1518*/1519public OffsetDateTime minusNanos(long nanos) {1520return (nanos == Long.MIN_VALUE ? plusNanos(Long.MAX_VALUE).plusNanos(1) : plusNanos(-nanos));1521}15221523//-----------------------------------------------------------------------1524/**1525* Queries this date-time using the specified query.1526* <p>1527* This queries this date-time using the specified query strategy object.1528* The {@code TemporalQuery} object defines the logic to be used to1529* obtain the result. Read the documentation of the query to understand1530* what the result of this method will be.1531* <p>1532* The result of this method is obtained by invoking the1533* {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the1534* specified query passing {@code this} as the argument.1535*1536* @param <R> the type of the result1537* @param query the query to invoke, not null1538* @return the query result, null may be returned (defined by the query)1539* @throws DateTimeException if unable to query (defined by the query)1540* @throws ArithmeticException if numeric overflow occurs (defined by the query)1541*/1542@SuppressWarnings("unchecked")1543@Override1544public <R> R query(TemporalQuery<R> query) {1545if (query == TemporalQueries.offset() || query == TemporalQueries.zone()) {1546return (R) getOffset();1547} else if (query == TemporalQueries.zoneId()) {1548return null;1549} else if (query == TemporalQueries.localDate()) {1550return (R) toLocalDate();1551} else if (query == TemporalQueries.localTime()) {1552return (R) toLocalTime();1553} else if (query == TemporalQueries.chronology()) {1554return (R) IsoChronology.INSTANCE;1555} else if (query == TemporalQueries.precision()) {1556return (R) NANOS;1557}1558// inline TemporalAccessor.super.query(query) as an optimization1559// non-JDK classes are not permitted to make this optimization1560return query.queryFrom(this);1561}15621563/**1564* Adjusts the specified temporal object to have the same offset, date1565* and time as this object.1566* <p>1567* This returns a temporal object of the same observable type as the input1568* with the offset, date and time changed to be the same as this.1569* <p>1570* The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}1571* three times, passing {@link ChronoField#EPOCH_DAY},1572* {@link ChronoField#NANO_OF_DAY} and {@link ChronoField#OFFSET_SECONDS} as the fields.1573* <p>1574* In most cases, it is clearer to reverse the calling pattern by using1575* {@link Temporal#with(TemporalAdjuster)}:1576* <pre>1577* // these two lines are equivalent, but the second approach is recommended1578* temporal = thisOffsetDateTime.adjustInto(temporal);1579* temporal = temporal.with(thisOffsetDateTime);1580* </pre>1581* <p>1582* This instance is immutable and unaffected by this method call.1583*1584* @param temporal the target object to be adjusted, not null1585* @return the adjusted object, not null1586* @throws DateTimeException if unable to make the adjustment1587* @throws ArithmeticException if numeric overflow occurs1588*/1589@Override1590public Temporal adjustInto(Temporal temporal) {1591// OffsetDateTime is treated as three separate fields, not an instant1592// this produces the most consistent set of results overall1593// the offset is set after the date and time, as it is typically a small1594// tweak to the result, with ZonedDateTime frequently ignoring the offset1595return temporal1596.with(EPOCH_DAY, toLocalDate().toEpochDay())1597.with(NANO_OF_DAY, toLocalTime().toNanoOfDay())1598.with(OFFSET_SECONDS, getOffset().getTotalSeconds());1599}16001601/**1602* Calculates the amount of time until another date-time in terms of the specified unit.1603* <p>1604* This calculates the amount of time between two {@code OffsetDateTime}1605* objects in terms of a single {@code TemporalUnit}.1606* The start and end points are {@code this} and the specified date-time.1607* The result will be negative if the end is before the start.1608* For example, the amount in days between two date-times can be calculated1609* using {@code startDateTime.until(endDateTime, DAYS)}.1610* <p>1611* The {@code Temporal} passed to this method is converted to a1612* {@code OffsetDateTime} using {@link #from(TemporalAccessor)}.1613* If the offset differs between the two date-times, the specified1614* end date-time is normalized to have the same offset as this date-time.1615* <p>1616* The calculation returns a whole number, representing the number of1617* complete units between the two date-times.1618* For example, the amount in months between 2012-06-15T00:00Z and 2012-08-14T23:59Z1619* will only be one month as it is one minute short of two months.1620* <p>1621* There are two equivalent ways of using this method.1622* The first is to invoke this method.1623* The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:1624* <pre>1625* // these two lines are equivalent1626* amount = start.until(end, MONTHS);1627* amount = MONTHS.between(start, end);1628* </pre>1629* The choice should be made based on which makes the code more readable.1630* <p>1631* The calculation is implemented in this method for {@link ChronoUnit}.1632* The units {@code NANOS}, {@code MICROS}, {@code MILLIS}, {@code SECONDS},1633* {@code MINUTES}, {@code HOURS} and {@code HALF_DAYS}, {@code DAYS},1634* {@code WEEKS}, {@code MONTHS}, {@code YEARS}, {@code DECADES},1635* {@code CENTURIES}, {@code MILLENNIA} and {@code ERAS} are supported.1636* Other {@code ChronoUnit} values will throw an exception.1637* <p>1638* If the unit is not a {@code ChronoUnit}, then the result of this method1639* is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}1640* passing {@code this} as the first argument and the converted input temporal1641* as the second argument.1642* <p>1643* This instance is immutable and unaffected by this method call.1644*1645* @param endExclusive the end date, exclusive, which is converted to an {@code OffsetDateTime}, not null1646* @param unit the unit to measure the amount in, not null1647* @return the amount of time between this date-time and the end date-time1648* @throws DateTimeException if the amount cannot be calculated, or the end1649* temporal cannot be converted to an {@code OffsetDateTime}1650* @throws UnsupportedTemporalTypeException if the unit is not supported1651* @throws ArithmeticException if numeric overflow occurs1652*/1653@Override1654public long until(Temporal endExclusive, TemporalUnit unit) {1655OffsetDateTime end = OffsetDateTime.from(endExclusive);1656if (unit instanceof ChronoUnit) {1657OffsetDateTime start = this;1658try {1659end = end.withOffsetSameInstant(offset);1660} catch (DateTimeException ex) {1661// end may be out of valid range. Adjust to end's offset.1662start = withOffsetSameInstant(end.offset);1663}1664return start.dateTime.until(end.dateTime, unit);1665}1666return unit.between(this, end);1667}16681669/**1670* Formats this date-time using the specified formatter.1671* <p>1672* This date-time will be passed to the formatter to produce a string.1673*1674* @param formatter the formatter to use, not null1675* @return the formatted date-time string, not null1676* @throws DateTimeException if an error occurs during printing1677*/1678public String format(DateTimeFormatter formatter) {1679Objects.requireNonNull(formatter, "formatter");1680return formatter.format(this);1681}16821683//-----------------------------------------------------------------------1684/**1685* Combines this date-time with a time-zone to create a {@code ZonedDateTime}1686* ensuring that the result has the same instant.1687* <p>1688* This returns a {@code ZonedDateTime} formed from this date-time and the specified time-zone.1689* This conversion will ignore the visible local date-time and use the underlying instant instead.1690* This avoids any problems with local time-line gaps or overlaps.1691* The result might have different values for fields such as hour, minute an even day.1692* <p>1693* To attempt to retain the values of the fields, use {@link #atZoneSimilarLocal(ZoneId)}.1694* To use the offset as the zone ID, use {@link #toZonedDateTime()}.1695*1696* @param zone the time-zone to use, not null1697* @return the zoned date-time formed from this date-time, not null1698*/1699public ZonedDateTime atZoneSameInstant(ZoneId zone) {1700return ZonedDateTime.ofInstant(dateTime, offset, zone);1701}17021703/**1704* Combines this date-time with a time-zone to create a {@code ZonedDateTime}1705* trying to keep the same local date and time.1706* <p>1707* This returns a {@code ZonedDateTime} formed from this date-time and the specified time-zone.1708* Where possible, the result will have the same local date-time as this object.1709* <p>1710* Time-zone rules, such as daylight savings, mean that not every time on the1711* local time-line exists. If the local date-time is in a gap or overlap according to1712* the rules then a resolver is used to determine the resultant local time and offset.1713* This method uses {@link ZonedDateTime#ofLocal(LocalDateTime, ZoneId, ZoneOffset)}1714* to retain the offset from this instance if possible.1715* <p>1716* Finer control over gaps and overlaps is available in two ways.1717* If you simply want to use the later offset at overlaps then call1718* {@link ZonedDateTime#withLaterOffsetAtOverlap()} immediately after this method.1719* <p>1720* To create a zoned date-time at the same instant irrespective of the local time-line,1721* use {@link #atZoneSameInstant(ZoneId)}.1722* To use the offset as the zone ID, use {@link #toZonedDateTime()}.1723*1724* @param zone the time-zone to use, not null1725* @return the zoned date-time formed from this date and the earliest valid time for the zone, not null1726*/1727public ZonedDateTime atZoneSimilarLocal(ZoneId zone) {1728return ZonedDateTime.ofLocal(dateTime, zone, offset);1729}17301731//-----------------------------------------------------------------------1732/**1733* Converts this date-time to an {@code OffsetTime}.1734* <p>1735* This returns an offset time with the same local time and offset.1736*1737* @return an OffsetTime representing the time and offset, not null1738*/1739public OffsetTime toOffsetTime() {1740return OffsetTime.of(dateTime.toLocalTime(), offset);1741}17421743/**1744* Converts this date-time to a {@code ZonedDateTime} using the offset as the zone ID.1745* <p>1746* This creates the simplest possible {@code ZonedDateTime} using the offset1747* as the zone ID.1748* <p>1749* To control the time-zone used, see {@link #atZoneSameInstant(ZoneId)} and1750* {@link #atZoneSimilarLocal(ZoneId)}.1751*1752* @return a zoned date-time representing the same local date-time and offset, not null1753*/1754public ZonedDateTime toZonedDateTime() {1755return ZonedDateTime.of(dateTime, offset);1756}17571758/**1759* Converts this date-time to an {@code Instant}.1760* <p>1761* This returns an {@code Instant} representing the same point on the1762* time-line as this date-time.1763*1764* @return an {@code Instant} representing the same instant, not null1765*/1766public Instant toInstant() {1767return dateTime.toInstant(offset);1768}17691770/**1771* Converts this date-time to the number of seconds from the epoch of 1970-01-01T00:00:00Z.1772* <p>1773* This allows this date-time to be converted to a value of the1774* {@link ChronoField#INSTANT_SECONDS epoch-seconds} field. This is primarily1775* intended for low-level conversions rather than general application usage.1776*1777* @return the number of seconds from the epoch of 1970-01-01T00:00:00Z1778*/1779public long toEpochSecond() {1780return dateTime.toEpochSecond(offset);1781}17821783//-----------------------------------------------------------------------1784/**1785* Compares this date-time to another date-time.1786* <p>1787* The comparison is based on the instant then on the local date-time.1788* It is "consistent with equals", as defined by {@link Comparable}.1789* <p>1790* For example, the following is the comparator order:1791* <ol>1792* <li>{@code 2008-12-03T10:30+01:00}</li>1793* <li>{@code 2008-12-03T11:00+01:00}</li>1794* <li>{@code 2008-12-03T12:00+02:00}</li>1795* <li>{@code 2008-12-03T11:30+01:00}</li>1796* <li>{@code 2008-12-03T12:00+01:00}</li>1797* <li>{@code 2008-12-03T12:30+01:00}</li>1798* </ol>1799* Values #2 and #3 represent the same instant on the time-line.1800* When two values represent the same instant, the local date-time is compared1801* to distinguish them. This step is needed to make the ordering1802* consistent with {@code equals()}.1803*1804* @param other the other date-time to compare to, not null1805* @return the comparator value, negative if less, positive if greater1806*/1807@Override1808public int compareTo(OffsetDateTime other) {1809int cmp = compareInstant(this, other);1810if (cmp == 0) {1811cmp = toLocalDateTime().compareTo(other.toLocalDateTime());1812}1813return cmp;1814}18151816//-----------------------------------------------------------------------1817/**1818* Checks if the instant of this date-time is after that of the specified date-time.1819* <p>1820* This method differs from the comparison in {@link #compareTo} and {@link #equals} in that it1821* only compares the instant of the date-time. This is equivalent to using1822* {@code dateTime1.toInstant().isAfter(dateTime2.toInstant());}.1823*1824* @param other the other date-time to compare to, not null1825* @return true if this is after the instant of the specified date-time1826*/1827public boolean isAfter(OffsetDateTime other) {1828long thisEpochSec = toEpochSecond();1829long otherEpochSec = other.toEpochSecond();1830return thisEpochSec > otherEpochSec ||1831(thisEpochSec == otherEpochSec && toLocalTime().getNano() > other.toLocalTime().getNano());1832}18331834/**1835* Checks if the instant of this date-time is before that of the specified date-time.1836* <p>1837* This method differs from the comparison in {@link #compareTo} in that it1838* only compares the instant of the date-time. This is equivalent to using1839* {@code dateTime1.toInstant().isBefore(dateTime2.toInstant());}.1840*1841* @param other the other date-time to compare to, not null1842* @return true if this is before the instant of the specified date-time1843*/1844public boolean isBefore(OffsetDateTime other) {1845long thisEpochSec = toEpochSecond();1846long otherEpochSec = other.toEpochSecond();1847return thisEpochSec < otherEpochSec ||1848(thisEpochSec == otherEpochSec && toLocalTime().getNano() < other.toLocalTime().getNano());1849}18501851/**1852* Checks if the instant of this date-time is equal to that of the specified date-time.1853* <p>1854* This method differs from the comparison in {@link #compareTo} and {@link #equals}1855* in that it only compares the instant of the date-time. This is equivalent to using1856* {@code dateTime1.toInstant().equals(dateTime2.toInstant());}.1857*1858* @param other the other date-time to compare to, not null1859* @return true if the instant equals the instant of the specified date-time1860*/1861public boolean isEqual(OffsetDateTime other) {1862return toEpochSecond() == other.toEpochSecond() &&1863toLocalTime().getNano() == other.toLocalTime().getNano();1864}18651866//-----------------------------------------------------------------------1867/**1868* Checks if this date-time is equal to another date-time.1869* <p>1870* The comparison is based on the local date-time and the offset.1871* To compare for the same instant on the time-line, use {@link #isEqual}.1872* Only objects of type {@code OffsetDateTime} are compared, other types return false.1873*1874* @param obj the object to check, null returns false1875* @return true if this is equal to the other date-time1876*/1877@Override1878public boolean equals(Object obj) {1879if (this == obj) {1880return true;1881}1882return (obj instanceof OffsetDateTime other)1883&& dateTime.equals(other.dateTime)1884&& offset.equals(other.offset);1885}18861887/**1888* A hash code for this date-time.1889*1890* @return a suitable hash code1891*/1892@Override1893public int hashCode() {1894return dateTime.hashCode() ^ offset.hashCode();1895}18961897//-----------------------------------------------------------------------1898/**1899* Outputs this date-time as a {@code String}, such as {@code 2007-12-03T10:15:30+01:00}.1900* <p>1901* The output will be one of the following ISO-8601 formats:1902* <ul>1903* <li>{@code uuuu-MM-dd'T'HH:mmXXXXX}</li>1904* <li>{@code uuuu-MM-dd'T'HH:mm:ssXXXXX}</li>1905* <li>{@code uuuu-MM-dd'T'HH:mm:ss.SSSXXXXX}</li>1906* <li>{@code uuuu-MM-dd'T'HH:mm:ss.SSSSSSXXXXX}</li>1907* <li>{@code uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSSXXXXX}</li>1908* </ul>1909* The format used will be the shortest that outputs the full value of1910* the time where the omitted parts are implied to be zero.1911*1912* @return a string representation of this date-time, not null1913*/1914@Override1915public String toString() {1916return dateTime.toString() + offset.toString();1917}19181919//-----------------------------------------------------------------------1920/**1921* Writes the object using a1922* <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>.1923* @serialData1924* <pre>1925* out.writeByte(10); // identifies an OffsetDateTime1926* // the <a href="{@docRoot}/serialized-form.html#java.time.LocalDateTime">datetime</a> excluding the one byte header1927* // the <a href="{@docRoot}/serialized-form.html#java.time.ZoneOffset">offset</a> excluding the one byte header1928* </pre>1929*1930* @return the instance of {@code Ser}, not null1931*/1932@java.io.Serial1933private Object writeReplace() {1934return new Ser(Ser.OFFSET_DATE_TIME_TYPE, this);1935}19361937/**1938* Defend against malicious streams.1939*1940* @param s the stream to read1941* @throws InvalidObjectException always1942*/1943@java.io.Serial1944private void readObject(ObjectInputStream s) throws InvalidObjectException {1945throw new InvalidObjectException("Deserialization via serialization delegate");1946}19471948void writeExternal(ObjectOutput out) throws IOException {1949dateTime.writeExternal(out);1950offset.writeExternal(out);1951}19521953static OffsetDateTime readExternal(ObjectInput in) throws IOException, ClassNotFoundException {1954LocalDateTime dateTime = LocalDateTime.readExternal(in);1955ZoneOffset offset = ZoneOffset.readExternal(in);1956return OffsetDateTime.of(dateTime, offset);1957}19581959}196019611962