Path: blob/master/src/java.base/share/classes/java/time/OffsetTime.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.LocalTime.NANOS_PER_HOUR;64import static java.time.LocalTime.NANOS_PER_MINUTE;65import static java.time.LocalTime.NANOS_PER_SECOND;66import static java.time.LocalTime.SECONDS_PER_DAY;67import static java.time.temporal.ChronoField.NANO_OF_DAY;68import static java.time.temporal.ChronoField.OFFSET_SECONDS;69import static java.time.temporal.ChronoUnit.NANOS;7071import java.io.IOException;72import java.io.ObjectInput;73import java.io.ObjectOutput;74import java.io.InvalidObjectException;75import java.io.ObjectInputStream;76import java.io.Serializable;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.Objects;9394/**95* A time with an offset from UTC/Greenwich in the ISO-8601 calendar system,96* such as {@code 10:15:30+01:00}.97* <p>98* {@code OffsetTime} is an immutable date-time object that represents a time, often99* viewed as hour-minute-second-offset.100* This class stores all time fields, to a precision of nanoseconds,101* as well as a zone offset.102* For example, the value "13:45:30.123456789+02:00" can be stored103* in an {@code OffsetTime}.104* <p>105* This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>106* class; programmers should treat instances that are107* {@linkplain #equals(Object) equal} as interchangeable and should not108* use instances for synchronization, or unpredictable behavior may109* occur. For example, in a future release, synchronization may fail.110* The {@code equals} method should be used for comparisons.111*112* @implSpec113* This class is immutable and thread-safe.114*115* @since 1.8116*/117@jdk.internal.ValueBased118public final class OffsetTime119implements Temporal, TemporalAdjuster, Comparable<OffsetTime>, Serializable {120121/**122* The minimum supported {@code OffsetTime}, '00:00:00+18:00'.123* This is the time of midnight at the start of the day in the maximum offset124* (larger offsets are earlier on the time-line).125* This combines {@link LocalTime#MIN} and {@link ZoneOffset#MAX}.126* This could be used by an application as a "far past" date.127*/128public static final OffsetTime MIN = LocalTime.MIN.atOffset(ZoneOffset.MAX);129/**130* The maximum supported {@code OffsetTime}, '23:59:59.999999999-18:00'.131* This is the time just before midnight at the end of the day in the minimum offset132* (larger negative offsets are later on the time-line).133* This combines {@link LocalTime#MAX} and {@link ZoneOffset#MIN}.134* This could be used by an application as a "far future" date.135*/136public static final OffsetTime MAX = LocalTime.MAX.atOffset(ZoneOffset.MIN);137138/**139* Serialization version.140*/141@java.io.Serial142private static final long serialVersionUID = 7264499704384272492L;143144/**145* The local date-time.146*/147private final LocalTime time;148/**149* The offset from UTC/Greenwich.150*/151private final ZoneOffset offset;152153//-----------------------------------------------------------------------154/**155* Obtains the current time from the system clock in the default time-zone.156* <p>157* This will query the {@link Clock#systemDefaultZone() system clock} in the default158* time-zone to obtain the current time.159* The offset will be calculated from the time-zone in the clock.160* <p>161* Using this method will prevent the ability to use an alternate clock for testing162* because the clock is hard-coded.163*164* @return the current time using the system clock and default time-zone, not null165*/166public static OffsetTime now() {167return now(Clock.systemDefaultZone());168}169170/**171* Obtains the current time from the system clock in the specified time-zone.172* <p>173* This will query the {@link Clock#system(ZoneId) system clock} to obtain the current time.174* Specifying the time-zone avoids dependence on the default time-zone.175* The offset will be calculated from the specified time-zone.176* <p>177* Using this method will prevent the ability to use an alternate clock for testing178* because the clock is hard-coded.179*180* @param zone the zone ID to use, not null181* @return the current time using the system clock, not null182*/183public static OffsetTime now(ZoneId zone) {184return now(Clock.system(zone));185}186187/**188* Obtains the current time from the specified clock.189* <p>190* This will query the specified clock to obtain the current time.191* The offset will be calculated from the time-zone in the clock.192* <p>193* Using this method allows the use of an alternate clock for testing.194* The alternate clock may be introduced using {@link Clock dependency injection}.195*196* @param clock the clock to use, not null197* @return the current time, not null198*/199public static OffsetTime now(Clock clock) {200Objects.requireNonNull(clock, "clock");201final Instant now = clock.instant(); // called once202return ofInstant(now, clock.getZone().getRules().getOffset(now));203}204205//-----------------------------------------------------------------------206/**207* Obtains an instance of {@code OffsetTime} from a local time and an offset.208*209* @param time the local time, not null210* @param offset the zone offset, not null211* @return the offset time, not null212*/213public static OffsetTime of(LocalTime time, ZoneOffset offset) {214return new OffsetTime(time, offset);215}216217/**218* Obtains an instance of {@code OffsetTime} from an hour, minute, second and nanosecond.219* <p>220* This creates an offset time with the four specified fields.221* <p>222* This method exists primarily for writing test cases.223* Non test-code will typically use other methods to create an offset time.224* {@code LocalTime} has two additional convenience variants of the225* equivalent factory method taking fewer arguments.226* They are not provided here to reduce the footprint of the API.227*228* @param hour the hour-of-day to represent, from 0 to 23229* @param minute the minute-of-hour to represent, from 0 to 59230* @param second the second-of-minute to represent, from 0 to 59231* @param nanoOfSecond the nano-of-second to represent, from 0 to 999,999,999232* @param offset the zone offset, not null233* @return the offset time, not null234* @throws DateTimeException if the value of any field is out of range235*/236public static OffsetTime of(int hour, int minute, int second, int nanoOfSecond, ZoneOffset offset) {237return new OffsetTime(LocalTime.of(hour, minute, second, nanoOfSecond), offset);238}239240//-----------------------------------------------------------------------241/**242* Obtains an instance of {@code OffsetTime} from an {@code Instant} and zone ID.243* <p>244* This creates an offset time with the same instant as that specified.245* Finding the offset from UTC/Greenwich is simple as there is only one valid246* offset for each instant.247* <p>248* The date component of the instant is dropped during the conversion.249* This means that the conversion can never fail due to the instant being250* out of the valid range of dates.251*252* @param instant the instant to create the time from, not null253* @param zone the time-zone, which may be an offset, not null254* @return the offset time, not null255*/256public static OffsetTime ofInstant(Instant instant, ZoneId zone) {257Objects.requireNonNull(instant, "instant");258Objects.requireNonNull(zone, "zone");259ZoneRules rules = zone.getRules();260ZoneOffset offset = rules.getOffset(instant);261long localSecond = instant.getEpochSecond() + offset.getTotalSeconds(); // overflow caught later262int secsOfDay = Math.floorMod(localSecond, SECONDS_PER_DAY);263LocalTime time = LocalTime.ofNanoOfDay(secsOfDay * NANOS_PER_SECOND + instant.getNano());264return new OffsetTime(time, offset);265}266267//-----------------------------------------------------------------------268/**269* Obtains an instance of {@code OffsetTime} from a temporal object.270* <p>271* This obtains an offset time based on the specified temporal.272* A {@code TemporalAccessor} represents an arbitrary set of date and time information,273* which this factory converts to an instance of {@code OffsetTime}.274* <p>275* The conversion extracts and combines the {@code ZoneOffset} and the276* {@code LocalTime} from the temporal object.277* Implementations are permitted to perform optimizations such as accessing278* those fields that are equivalent to the relevant objects.279* <p>280* This method matches the signature of the functional interface {@link TemporalQuery}281* allowing it to be used as a query via method reference, {@code OffsetTime::from}.282*283* @param temporal the temporal object to convert, not null284* @return the offset time, not null285* @throws DateTimeException if unable to convert to an {@code OffsetTime}286*/287public static OffsetTime from(TemporalAccessor temporal) {288if (temporal instanceof OffsetTime) {289return (OffsetTime) temporal;290}291try {292LocalTime time = LocalTime.from(temporal);293ZoneOffset offset = ZoneOffset.from(temporal);294return new OffsetTime(time, offset);295} catch (DateTimeException ex) {296throw new DateTimeException("Unable to obtain OffsetTime from TemporalAccessor: " +297temporal + " of type " + temporal.getClass().getName(), ex);298}299}300301//-----------------------------------------------------------------------302/**303* Obtains an instance of {@code OffsetTime} from a text string such as {@code 10:15:30+01:00}.304* <p>305* The string must represent a valid time and is parsed using306* {@link java.time.format.DateTimeFormatter#ISO_OFFSET_TIME}.307*308* @param text the text to parse such as "10:15:30+01:00", not null309* @return the parsed local time, not null310* @throws DateTimeParseException if the text cannot be parsed311*/312public static OffsetTime parse(CharSequence text) {313return parse(text, DateTimeFormatter.ISO_OFFSET_TIME);314}315316/**317* Obtains an instance of {@code OffsetTime} from a text string using a specific formatter.318* <p>319* The text is parsed using the formatter, returning a time.320*321* @param text the text to parse, not null322* @param formatter the formatter to use, not null323* @return the parsed offset time, not null324* @throws DateTimeParseException if the text cannot be parsed325*/326public static OffsetTime parse(CharSequence text, DateTimeFormatter formatter) {327Objects.requireNonNull(formatter, "formatter");328return formatter.parse(text, OffsetTime::from);329}330331//-----------------------------------------------------------------------332/**333* Constructor.334*335* @param time the local time, not null336* @param offset the zone offset, not null337*/338private OffsetTime(LocalTime time, ZoneOffset offset) {339this.time = Objects.requireNonNull(time, "time");340this.offset = Objects.requireNonNull(offset, "offset");341}342343/**344* Returns a new time based on this one, returning {@code this} where possible.345*346* @param time the time to create with, not null347* @param offset the zone offset to create with, not null348*/349private OffsetTime with(LocalTime time, ZoneOffset offset) {350if (this.time == time && this.offset.equals(offset)) {351return this;352}353return new OffsetTime(time, offset);354}355356//-----------------------------------------------------------------------357/**358* Checks if the specified field is supported.359* <p>360* This checks if this time can be queried for the specified field.361* If false, then calling the {@link #range(TemporalField) range},362* {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}363* methods will throw an exception.364* <p>365* If the field is a {@link ChronoField} then the query is implemented here.366* The supported fields are:367* <ul>368* <li>{@code NANO_OF_SECOND}369* <li>{@code NANO_OF_DAY}370* <li>{@code MICRO_OF_SECOND}371* <li>{@code MICRO_OF_DAY}372* <li>{@code MILLI_OF_SECOND}373* <li>{@code MILLI_OF_DAY}374* <li>{@code SECOND_OF_MINUTE}375* <li>{@code SECOND_OF_DAY}376* <li>{@code MINUTE_OF_HOUR}377* <li>{@code MINUTE_OF_DAY}378* <li>{@code HOUR_OF_AMPM}379* <li>{@code CLOCK_HOUR_OF_AMPM}380* <li>{@code HOUR_OF_DAY}381* <li>{@code CLOCK_HOUR_OF_DAY}382* <li>{@code AMPM_OF_DAY}383* <li>{@code OFFSET_SECONDS}384* </ul>385* All other {@code ChronoField} instances will return false.386* <p>387* If the field is not a {@code ChronoField}, then the result of this method388* is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}389* passing {@code this} as the argument.390* Whether the field is supported is determined by the field.391*392* @param field the field to check, null returns false393* @return true if the field is supported on this time, false if not394*/395@Override396public boolean isSupported(TemporalField field) {397if (field instanceof ChronoField) {398return field.isTimeBased() || field == OFFSET_SECONDS;399}400return field != null && field.isSupportedBy(this);401}402403/**404* Checks if the specified unit is supported.405* <p>406* This checks if the specified unit can be added to, or subtracted from, this offset-time.407* If false, then calling the {@link #plus(long, TemporalUnit)} and408* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.409* <p>410* If the unit is a {@link ChronoUnit} then the query is implemented here.411* The supported units are:412* <ul>413* <li>{@code NANOS}414* <li>{@code MICROS}415* <li>{@code MILLIS}416* <li>{@code SECONDS}417* <li>{@code MINUTES}418* <li>{@code HOURS}419* <li>{@code HALF_DAYS}420* </ul>421* All other {@code ChronoUnit} instances will return false.422* <p>423* If the unit is not a {@code ChronoUnit}, then the result of this method424* is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}425* passing {@code this} as the argument.426* Whether the unit is supported is determined by the unit.427*428* @param unit the unit to check, null returns false429* @return true if the unit can be added/subtracted, false if not430*/431@Override // override for Javadoc432public boolean isSupported(TemporalUnit unit) {433if (unit instanceof ChronoUnit) {434return unit.isTimeBased();435}436return unit != null && unit.isSupportedBy(this);437}438439//-----------------------------------------------------------------------440/**441* Gets the range of valid values for the specified field.442* <p>443* The range object expresses the minimum and maximum valid values for a field.444* This time is used to enhance the accuracy of the returned range.445* If it is not possible to return the range, because the field is not supported446* or for some other reason, an exception is thrown.447* <p>448* If the field is a {@link ChronoField} then the query is implemented here.449* The {@link #isSupported(TemporalField) supported fields} will return450* appropriate range instances.451* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.452* <p>453* If the field is not a {@code ChronoField}, then the result of this method454* is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}455* passing {@code this} as the argument.456* Whether the range can be obtained is determined by the field.457*458* @param field the field to query the range for, not null459* @return the range of valid values for the field, not null460* @throws DateTimeException if the range for the field cannot be obtained461* @throws UnsupportedTemporalTypeException if the field is not supported462*/463@Override464public ValueRange range(TemporalField field) {465if (field instanceof ChronoField) {466if (field == OFFSET_SECONDS) {467return field.range();468}469return time.range(field);470}471return field.rangeRefinedBy(this);472}473474/**475* Gets the value of the specified field from this time as an {@code int}.476* <p>477* This queries this time for the value of the specified field.478* The returned value will always be within the valid range of values for the field.479* If it is not possible to return the value, because the field is not supported480* or for some other reason, an exception is thrown.481* <p>482* If the field is a {@link ChronoField} then the query is implemented here.483* The {@link #isSupported(TemporalField) supported fields} will return valid484* values based on this time, except {@code NANO_OF_DAY} and {@code MICRO_OF_DAY}485* which are too large to fit in an {@code int} and throw an {@code UnsupportedTemporalTypeException}.486* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.487* <p>488* If the field is not a {@code ChronoField}, then the result of this method489* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}490* passing {@code this} as the argument. Whether the value can be obtained,491* and what the value represents, is determined by the field.492*493* @param field the field to get, not null494* @return the value for the field495* @throws DateTimeException if a value for the field cannot be obtained or496* the value is outside the range of valid values for the field497* @throws UnsupportedTemporalTypeException if the field is not supported or498* the range of values exceeds an {@code int}499* @throws ArithmeticException if numeric overflow occurs500*/501@Override // override for Javadoc502public int get(TemporalField field) {503return Temporal.super.get(field);504}505506/**507* Gets the value of the specified field from this time as a {@code long}.508* <p>509* This queries this time for the value of the specified field.510* If it is not possible to return the value, because the field is not supported511* or for some other reason, an exception is thrown.512* <p>513* If the field is a {@link ChronoField} then the query is implemented here.514* The {@link #isSupported(TemporalField) supported fields} will return valid515* values based on this time.516* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.517* <p>518* If the field is not a {@code ChronoField}, then the result of this method519* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}520* passing {@code this} as the argument. Whether the value can be obtained,521* and what the value represents, is determined by the field.522*523* @param field the field to get, not null524* @return the value for the field525* @throws DateTimeException if a value for the field cannot be obtained526* @throws UnsupportedTemporalTypeException if the field is not supported527* @throws ArithmeticException if numeric overflow occurs528*/529@Override530public long getLong(TemporalField field) {531if (field instanceof ChronoField) {532if (field == OFFSET_SECONDS) {533return offset.getTotalSeconds();534}535return time.getLong(field);536}537return field.getFrom(this);538}539540//-----------------------------------------------------------------------541/**542* Gets the zone offset, such as '+01:00'.543* <p>544* This is the offset of the local time from UTC/Greenwich.545*546* @return the zone offset, not null547*/548public ZoneOffset getOffset() {549return offset;550}551552/**553* Returns a copy of this {@code OffsetTime} with the specified offset ensuring554* that the result has the same local time.555* <p>556* This method returns an object with the same {@code LocalTime} and the specified {@code ZoneOffset}.557* No calculation is needed or performed.558* For example, if this time represents {@code 10:30+02:00} and the offset specified is559* {@code +03:00}, then this method will return {@code 10:30+03:00}.560* <p>561* To take into account the difference between the offsets, and adjust the time fields,562* use {@link #withOffsetSameInstant}.563* <p>564* This instance is immutable and unaffected by this method call.565*566* @param offset the zone offset to change to, not null567* @return an {@code OffsetTime} based on this time with the requested offset, not null568*/569public OffsetTime withOffsetSameLocal(ZoneOffset offset) {570return offset != null && offset.equals(this.offset) ? this : new OffsetTime(time, offset);571}572573/**574* Returns a copy of this {@code OffsetTime} with the specified offset ensuring575* that the result is at the same instant on an implied day.576* <p>577* This method returns an object with the specified {@code ZoneOffset} and a {@code LocalTime}578* adjusted by the difference between the two offsets.579* This will result in the old and new objects representing the same instant on an implied day.580* This is useful for finding the local time in a different offset.581* For example, if this time represents {@code 10:30+02:00} and the offset specified is582* {@code +03:00}, then this method will return {@code 11:30+03:00}.583* <p>584* To change the offset without adjusting the local time use {@link #withOffsetSameLocal}.585* <p>586* This instance is immutable and unaffected by this method call.587*588* @param offset the zone offset to change to, not null589* @return an {@code OffsetTime} based on this time with the requested offset, not null590*/591public OffsetTime withOffsetSameInstant(ZoneOffset offset) {592if (offset.equals(this.offset)) {593return this;594}595int difference = offset.getTotalSeconds() - this.offset.getTotalSeconds();596LocalTime adjusted = time.plusSeconds(difference);597return new OffsetTime(adjusted, offset);598}599600//-----------------------------------------------------------------------601/**602* Gets the {@code LocalTime} part of this date-time.603* <p>604* This returns a {@code LocalTime} with the same hour, minute, second and605* nanosecond as this date-time.606*607* @return the time part of this date-time, not null608*/609public LocalTime toLocalTime() {610return time;611}612613//-----------------------------------------------------------------------614/**615* Gets the hour-of-day field.616*617* @return the hour-of-day, from 0 to 23618*/619public int getHour() {620return time.getHour();621}622623/**624* Gets the minute-of-hour field.625*626* @return the minute-of-hour, from 0 to 59627*/628public int getMinute() {629return time.getMinute();630}631632/**633* Gets the second-of-minute field.634*635* @return the second-of-minute, from 0 to 59636*/637public int getSecond() {638return time.getSecond();639}640641/**642* Gets the nano-of-second field.643*644* @return the nano-of-second, from 0 to 999,999,999645*/646public int getNano() {647return time.getNano();648}649650//-----------------------------------------------------------------------651/**652* Returns an adjusted copy of this time.653* <p>654* This returns an {@code OffsetTime}, based on this one, with the time adjusted.655* The adjustment takes place using the specified adjuster strategy object.656* Read the documentation of the adjuster to understand what adjustment will be made.657* <p>658* A simple adjuster might simply set the one of the fields, such as the hour field.659* A more complex adjuster might set the time to the last hour of the day.660* <p>661* The classes {@link LocalTime} and {@link ZoneOffset} implement {@code TemporalAdjuster},662* thus this method can be used to change the time or offset:663* <pre>664* result = offsetTime.with(time);665* result = offsetTime.with(offset);666* </pre>667* <p>668* The result of this method is obtained by invoking the669* {@link TemporalAdjuster#adjustInto(Temporal)} method on the670* specified adjuster passing {@code this} as the argument.671* <p>672* This instance is immutable and unaffected by this method call.673*674* @param adjuster the adjuster to use, not null675* @return an {@code OffsetTime} based on {@code this} with the adjustment made, not null676* @throws DateTimeException if the adjustment cannot be made677* @throws ArithmeticException if numeric overflow occurs678*/679@Override680public OffsetTime with(TemporalAdjuster adjuster) {681// optimizations682if (adjuster instanceof LocalTime) {683return with((LocalTime) adjuster, offset);684} else if (adjuster instanceof ZoneOffset) {685return with(time, (ZoneOffset) adjuster);686} else if (adjuster instanceof OffsetTime) {687return (OffsetTime) adjuster;688}689return (OffsetTime) adjuster.adjustInto(this);690}691692/**693* Returns a copy of this time with the specified field set to a new value.694* <p>695* This returns an {@code OffsetTime}, based on this one, with the value696* for the specified field changed.697* This can be used to change any supported field, such as the hour, minute or second.698* If it is not possible to set the value, because the field is not supported or for699* some other reason, an exception is thrown.700* <p>701* If the field is a {@link ChronoField} then the adjustment is implemented here.702* <p>703* The {@code OFFSET_SECONDS} field will return a time with the specified offset.704* The local time is unaltered. If the new offset value is outside the valid range705* then a {@code DateTimeException} will be thrown.706* <p>707* The other {@link #isSupported(TemporalField) supported fields} will behave as per708* the matching method on {@link LocalTime#with(TemporalField, long)} LocalTime}.709* In this case, the offset is not part of the calculation and will be unchanged.710* <p>711* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.712* <p>713* If the field is not a {@code ChronoField}, then the result of this method714* is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}715* passing {@code this} as the argument. In this case, the field determines716* whether and how to adjust the instant.717* <p>718* This instance is immutable and unaffected by this method call.719*720* @param field the field to set in the result, not null721* @param newValue the new value of the field in the result722* @return an {@code OffsetTime} based on {@code this} with the specified field set, not null723* @throws DateTimeException if the field cannot be set724* @throws UnsupportedTemporalTypeException if the field is not supported725* @throws ArithmeticException if numeric overflow occurs726*/727@Override728public OffsetTime with(TemporalField field, long newValue) {729if (field instanceof ChronoField) {730if (field == OFFSET_SECONDS) {731ChronoField f = (ChronoField) field;732return with(time, ZoneOffset.ofTotalSeconds(f.checkValidIntValue(newValue)));733}734return with(time.with(field, newValue), offset);735}736return field.adjustInto(this, newValue);737}738739//-----------------------------------------------------------------------740/**741* Returns a copy of this {@code OffsetTime} with the hour-of-day altered.742* <p>743* The offset does not affect the calculation and will be the same in the result.744* <p>745* This instance is immutable and unaffected by this method call.746*747* @param hour the hour-of-day to set in the result, from 0 to 23748* @return an {@code OffsetTime} based on this time with the requested hour, not null749* @throws DateTimeException if the hour value is invalid750*/751public OffsetTime withHour(int hour) {752return with(time.withHour(hour), offset);753}754755/**756* Returns a copy of this {@code OffsetTime} with the minute-of-hour altered.757* <p>758* The offset does not affect the calculation and will be the same in the result.759* <p>760* This instance is immutable and unaffected by this method call.761*762* @param minute the minute-of-hour to set in the result, from 0 to 59763* @return an {@code OffsetTime} based on this time with the requested minute, not null764* @throws DateTimeException if the minute value is invalid765*/766public OffsetTime withMinute(int minute) {767return with(time.withMinute(minute), offset);768}769770/**771* Returns a copy of this {@code OffsetTime} with the second-of-minute altered.772* <p>773* The offset does not affect the calculation and will be the same in the result.774* <p>775* This instance is immutable and unaffected by this method call.776*777* @param second the second-of-minute to set in the result, from 0 to 59778* @return an {@code OffsetTime} based on this time with the requested second, not null779* @throws DateTimeException if the second value is invalid780*/781public OffsetTime withSecond(int second) {782return with(time.withSecond(second), offset);783}784785/**786* Returns a copy of this {@code OffsetTime} with the nano-of-second altered.787* <p>788* The offset does not affect the calculation and will be the same in the result.789* <p>790* This instance is immutable and unaffected by this method call.791*792* @param nanoOfSecond the nano-of-second to set in the result, from 0 to 999,999,999793* @return an {@code OffsetTime} based on this time with the requested nanosecond, not null794* @throws DateTimeException if the nanos value is invalid795*/796public OffsetTime withNano(int nanoOfSecond) {797return with(time.withNano(nanoOfSecond), offset);798}799800//-----------------------------------------------------------------------801/**802* Returns a copy of this {@code OffsetTime} with the time truncated.803* <p>804* Truncation returns a copy of the original time with fields805* smaller than the specified unit set to zero.806* For example, truncating with the {@link ChronoUnit#MINUTES minutes} unit807* will set the second-of-minute and nano-of-second field to zero.808* <p>809* The unit must have a {@linkplain TemporalUnit#getDuration() duration}810* that divides into the length of a standard day without remainder.811* This includes all supplied time units on {@link ChronoUnit} and812* {@link ChronoUnit#DAYS DAYS}. Other units throw an exception.813* <p>814* The offset does not affect the calculation and will be the same in the result.815* <p>816* This instance is immutable and unaffected by this method call.817*818* @param unit the unit to truncate to, not null819* @return an {@code OffsetTime} based on this time with the time truncated, not null820* @throws DateTimeException if unable to truncate821* @throws UnsupportedTemporalTypeException if the unit is not supported822*/823public OffsetTime truncatedTo(TemporalUnit unit) {824return with(time.truncatedTo(unit), offset);825}826827//-----------------------------------------------------------------------828/**829* Returns a copy of this time with the specified amount added.830* <p>831* This returns an {@code OffsetTime}, based on this one, with the specified amount added.832* The amount is typically {@link Duration} but may be any other type implementing833* the {@link TemporalAmount} interface.834* <p>835* The calculation is delegated to the amount object by calling836* {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free837* to implement the addition in any way it wishes, however it typically838* calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation839* of the amount implementation to determine if it can be successfully added.840* <p>841* This instance is immutable and unaffected by this method call.842*843* @param amountToAdd the amount to add, not null844* @return an {@code OffsetTime} based on this time with the addition made, not null845* @throws DateTimeException if the addition cannot be made846* @throws ArithmeticException if numeric overflow occurs847*/848@Override849public OffsetTime plus(TemporalAmount amountToAdd) {850return (OffsetTime) amountToAdd.addTo(this);851}852853/**854* Returns a copy of this time with the specified amount added.855* <p>856* This returns an {@code OffsetTime}, based on this one, with the amount857* in terms of the unit added. If it is not possible to add the amount, because the858* unit is not supported or for some other reason, an exception is thrown.859* <p>860* If the field is a {@link ChronoUnit} then the addition is implemented by861* {@link LocalTime#plus(long, TemporalUnit)}.862* The offset is not part of the calculation and will be unchanged in the result.863* <p>864* If the field is not a {@code ChronoUnit}, then the result of this method865* is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}866* passing {@code this} as the argument. In this case, the unit determines867* whether and how to perform the addition.868* <p>869* This instance is immutable and unaffected by this method call.870*871* @param amountToAdd the amount of the unit to add to the result, may be negative872* @param unit the unit of the amount to add, not null873* @return an {@code OffsetTime} based on this time with the specified amount added, not null874* @throws DateTimeException if the addition cannot be made875* @throws UnsupportedTemporalTypeException if the unit is not supported876* @throws ArithmeticException if numeric overflow occurs877*/878@Override879public OffsetTime plus(long amountToAdd, TemporalUnit unit) {880if (unit instanceof ChronoUnit) {881return with(time.plus(amountToAdd, unit), offset);882}883return unit.addTo(this, amountToAdd);884}885886//-----------------------------------------------------------------------887/**888* Returns a copy of this {@code OffsetTime} with the specified number of hours added.889* <p>890* This adds the specified number of hours to this time, returning a new time.891* The calculation wraps around midnight.892* <p>893* This instance is immutable and unaffected by this method call.894*895* @param hours the hours to add, may be negative896* @return an {@code OffsetTime} based on this time with the hours added, not null897*/898public OffsetTime plusHours(long hours) {899return with(time.plusHours(hours), offset);900}901902/**903* Returns a copy of this {@code OffsetTime} with the specified number of minutes added.904* <p>905* This adds the specified number of minutes to this time, returning a new time.906* The calculation wraps around midnight.907* <p>908* This instance is immutable and unaffected by this method call.909*910* @param minutes the minutes to add, may be negative911* @return an {@code OffsetTime} based on this time with the minutes added, not null912*/913public OffsetTime plusMinutes(long minutes) {914return with(time.plusMinutes(minutes), offset);915}916917/**918* Returns a copy of this {@code OffsetTime} with the specified number of seconds added.919* <p>920* This adds the specified number of seconds to this time, returning a new time.921* The calculation wraps around midnight.922* <p>923* This instance is immutable and unaffected by this method call.924*925* @param seconds the seconds to add, may be negative926* @return an {@code OffsetTime} based on this time with the seconds added, not null927*/928public OffsetTime plusSeconds(long seconds) {929return with(time.plusSeconds(seconds), offset);930}931932/**933* Returns a copy of this {@code OffsetTime} with the specified number of nanoseconds added.934* <p>935* This adds the specified number of nanoseconds to this time, returning a new time.936* The calculation wraps around midnight.937* <p>938* This instance is immutable and unaffected by this method call.939*940* @param nanos the nanos to add, may be negative941* @return an {@code OffsetTime} based on this time with the nanoseconds added, not null942*/943public OffsetTime plusNanos(long nanos) {944return with(time.plusNanos(nanos), offset);945}946947//-----------------------------------------------------------------------948/**949* Returns a copy of this time with the specified amount subtracted.950* <p>951* This returns an {@code OffsetTime}, based on this one, with the specified amount subtracted.952* The amount is typically {@link Duration} but may be any other type implementing953* the {@link TemporalAmount} interface.954* <p>955* The calculation is delegated to the amount object by calling956* {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free957* to implement the subtraction in any way it wishes, however it typically958* calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation959* of the amount implementation to determine if it can be successfully subtracted.960* <p>961* This instance is immutable and unaffected by this method call.962*963* @param amountToSubtract the amount to subtract, not null964* @return an {@code OffsetTime} based on this time with the subtraction made, not null965* @throws DateTimeException if the subtraction cannot be made966* @throws ArithmeticException if numeric overflow occurs967*/968@Override969public OffsetTime minus(TemporalAmount amountToSubtract) {970return (OffsetTime) amountToSubtract.subtractFrom(this);971}972973/**974* Returns a copy of this time with the specified amount subtracted.975* <p>976* This returns an {@code OffsetTime}, based on this one, with the amount977* in terms of the unit subtracted. If it is not possible to subtract the amount,978* because the unit is not supported or for some other reason, an exception is thrown.979* <p>980* This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.981* See that method for a full description of how addition, and thus subtraction, works.982* <p>983* This instance is immutable and unaffected by this method call.984*985* @param amountToSubtract the amount of the unit to subtract from the result, may be negative986* @param unit the unit of the amount to subtract, not null987* @return an {@code OffsetTime} based on this time with the specified amount subtracted, not null988* @throws DateTimeException if the subtraction cannot be made989* @throws UnsupportedTemporalTypeException if the unit is not supported990* @throws ArithmeticException if numeric overflow occurs991*/992@Override993public OffsetTime minus(long amountToSubtract, TemporalUnit unit) {994return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));995}996997//-----------------------------------------------------------------------998/**999* Returns a copy of this {@code OffsetTime} with the specified number of hours subtracted.1000* <p>1001* This subtracts the specified number of hours from this time, returning a new time.1002* The calculation wraps around midnight.1003* <p>1004* This instance is immutable and unaffected by this method call.1005*1006* @param hours the hours to subtract, may be negative1007* @return an {@code OffsetTime} based on this time with the hours subtracted, not null1008*/1009public OffsetTime minusHours(long hours) {1010return with(time.minusHours(hours), offset);1011}10121013/**1014* Returns a copy of this {@code OffsetTime} with the specified number of minutes subtracted.1015* <p>1016* This subtracts the specified number of minutes from this time, returning a new time.1017* The calculation wraps around midnight.1018* <p>1019* This instance is immutable and unaffected by this method call.1020*1021* @param minutes the minutes to subtract, may be negative1022* @return an {@code OffsetTime} based on this time with the minutes subtracted, not null1023*/1024public OffsetTime minusMinutes(long minutes) {1025return with(time.minusMinutes(minutes), offset);1026}10271028/**1029* Returns a copy of this {@code OffsetTime} with the specified number of seconds subtracted.1030* <p>1031* This subtracts the specified number of seconds from this time, returning a new time.1032* The calculation wraps around midnight.1033* <p>1034* This instance is immutable and unaffected by this method call.1035*1036* @param seconds the seconds to subtract, may be negative1037* @return an {@code OffsetTime} based on this time with the seconds subtracted, not null1038*/1039public OffsetTime minusSeconds(long seconds) {1040return with(time.minusSeconds(seconds), offset);1041}10421043/**1044* Returns a copy of this {@code OffsetTime} with the specified number of nanoseconds subtracted.1045* <p>1046* This subtracts the specified number of nanoseconds from this time, returning a new time.1047* The calculation wraps around midnight.1048* <p>1049* This instance is immutable and unaffected by this method call.1050*1051* @param nanos the nanos to subtract, may be negative1052* @return an {@code OffsetTime} based on this time with the nanoseconds subtracted, not null1053*/1054public OffsetTime minusNanos(long nanos) {1055return with(time.minusNanos(nanos), offset);1056}10571058//-----------------------------------------------------------------------1059/**1060* Queries this time using the specified query.1061* <p>1062* This queries this time using the specified query strategy object.1063* The {@code TemporalQuery} object defines the logic to be used to1064* obtain the result. Read the documentation of the query to understand1065* what the result of this method will be.1066* <p>1067* The result of this method is obtained by invoking the1068* {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the1069* specified query passing {@code this} as the argument.1070*1071* @param <R> the type of the result1072* @param query the query to invoke, not null1073* @return the query result, null may be returned (defined by the query)1074* @throws DateTimeException if unable to query (defined by the query)1075* @throws ArithmeticException if numeric overflow occurs (defined by the query)1076*/1077@SuppressWarnings("unchecked")1078@Override1079public <R> R query(TemporalQuery<R> query) {1080if (query == TemporalQueries.offset() || query == TemporalQueries.zone()) {1081return (R) offset;1082} else if (query == TemporalQueries.zoneId() | query == TemporalQueries.chronology() || query == TemporalQueries.localDate()) {1083return null;1084} else if (query == TemporalQueries.localTime()) {1085return (R) time;1086} else if (query == TemporalQueries.precision()) {1087return (R) NANOS;1088}1089// inline TemporalAccessor.super.query(query) as an optimization1090// non-JDK classes are not permitted to make this optimization1091return query.queryFrom(this);1092}10931094/**1095* Adjusts the specified temporal object to have the same offset and time1096* as this object.1097* <p>1098* This returns a temporal object of the same observable type as the input1099* with the offset and time changed to be the same as this.1100* <p>1101* The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}1102* twice, passing {@link ChronoField#NANO_OF_DAY} and1103* {@link ChronoField#OFFSET_SECONDS} as the fields.1104* <p>1105* In most cases, it is clearer to reverse the calling pattern by using1106* {@link Temporal#with(TemporalAdjuster)}:1107* <pre>1108* // these two lines are equivalent, but the second approach is recommended1109* temporal = thisOffsetTime.adjustInto(temporal);1110* temporal = temporal.with(thisOffsetTime);1111* </pre>1112* <p>1113* This instance is immutable and unaffected by this method call.1114*1115* @param temporal the target object to be adjusted, not null1116* @return the adjusted object, not null1117* @throws DateTimeException if unable to make the adjustment1118* @throws ArithmeticException if numeric overflow occurs1119*/1120@Override1121public Temporal adjustInto(Temporal temporal) {1122return temporal1123.with(NANO_OF_DAY, time.toNanoOfDay())1124.with(OFFSET_SECONDS, offset.getTotalSeconds());1125}11261127/**1128* Calculates the amount of time until another time in terms of the specified unit.1129* <p>1130* This calculates the amount of time between two {@code OffsetTime}1131* objects in terms of a single {@code TemporalUnit}.1132* The start and end points are {@code this} and the specified time.1133* The result will be negative if the end is before the start.1134* For example, the amount in hours between two times can be calculated1135* using {@code startTime.until(endTime, HOURS)}.1136* <p>1137* The {@code Temporal} passed to this method is converted to a1138* {@code OffsetTime} using {@link #from(TemporalAccessor)}.1139* If the offset differs between the two times, then the specified1140* end time is normalized to have the same offset as this time.1141* <p>1142* The calculation returns a whole number, representing the number of1143* complete units between the two times.1144* For example, the amount in hours between 11:30Z and 13:29Z will only1145* be one hour as it is one minute short of two hours.1146* <p>1147* There are two equivalent ways of using this method.1148* The first is to invoke this method.1149* The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:1150* <pre>1151* // these two lines are equivalent1152* amount = start.until(end, MINUTES);1153* amount = MINUTES.between(start, end);1154* </pre>1155* The choice should be made based on which makes the code more readable.1156* <p>1157* The calculation is implemented in this method for {@link ChronoUnit}.1158* The units {@code NANOS}, {@code MICROS}, {@code MILLIS}, {@code SECONDS},1159* {@code MINUTES}, {@code HOURS} and {@code HALF_DAYS} are supported.1160* Other {@code ChronoUnit} values will throw an exception.1161* <p>1162* If the unit is not a {@code ChronoUnit}, then the result of this method1163* is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}1164* passing {@code this} as the first argument and the converted input temporal1165* as the second argument.1166* <p>1167* This instance is immutable and unaffected by this method call.1168*1169* @param endExclusive the end time, exclusive, which is converted to an {@code OffsetTime}, not null1170* @param unit the unit to measure the amount in, not null1171* @return the amount of time between this time and the end time1172* @throws DateTimeException if the amount cannot be calculated, or the end1173* temporal cannot be converted to an {@code OffsetTime}1174* @throws UnsupportedTemporalTypeException if the unit is not supported1175* @throws ArithmeticException if numeric overflow occurs1176*/1177@Override1178public long until(Temporal endExclusive, TemporalUnit unit) {1179OffsetTime end = OffsetTime.from(endExclusive);1180if (unit instanceof ChronoUnit chronoUnit) {1181long nanosUntil = end.toEpochNano() - toEpochNano(); // no overflow1182switch (chronoUnit) {1183case NANOS: return nanosUntil;1184case MICROS: return nanosUntil / 1000;1185case MILLIS: return nanosUntil / 1000_000;1186case SECONDS: return nanosUntil / NANOS_PER_SECOND;1187case MINUTES: return nanosUntil / NANOS_PER_MINUTE;1188case HOURS: return nanosUntil / NANOS_PER_HOUR;1189case HALF_DAYS: return nanosUntil / (12 * NANOS_PER_HOUR);1190}1191throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);1192}1193return unit.between(this, end);1194}11951196/**1197* Formats this time using the specified formatter.1198* <p>1199* This time will be passed to the formatter to produce a string.1200*1201* @param formatter the formatter to use, not null1202* @return the formatted time string, not null1203* @throws DateTimeException if an error occurs during printing1204*/1205public String format(DateTimeFormatter formatter) {1206Objects.requireNonNull(formatter, "formatter");1207return formatter.format(this);1208}12091210//-----------------------------------------------------------------------1211/**1212* Combines this time with a date to create an {@code OffsetDateTime}.1213* <p>1214* This returns an {@code OffsetDateTime} formed from this time and the specified date.1215* All possible combinations of date and time are valid.1216*1217* @param date the date to combine with, not null1218* @return the offset date-time formed from this time and the specified date, not null1219*/1220public OffsetDateTime atDate(LocalDate date) {1221return OffsetDateTime.of(date, time, offset);1222}12231224//-----------------------------------------------------------------------1225/**1226* Converts this time to epoch nanos based on 1970-01-01Z.1227*1228* @return the epoch nanos value1229*/1230private long toEpochNano() {1231long nod = time.toNanoOfDay();1232long offsetNanos = offset.getTotalSeconds() * NANOS_PER_SECOND;1233return nod - offsetNanos;1234}12351236/**1237* Converts this {@code OffsetTime} to the number of seconds since the epoch1238* of 1970-01-01T00:00:00Z.1239* <p>1240* This combines this offset time with the specified date to calculate the1241* epoch-second value, which is the number of elapsed seconds from1242* 1970-01-01T00:00:00Z.1243* Instants on the time-line after the epoch are positive, earlier1244* are negative.1245*1246* @param date the localdate, not null1247* @return the number of seconds since the epoch of 1970-01-01T00:00:00Z, may be negative1248* @since 91249*/1250public long toEpochSecond(LocalDate date) {1251Objects.requireNonNull(date, "date");1252long epochDay = date.toEpochDay();1253long secs = epochDay * 86400 + time.toSecondOfDay();1254secs -= offset.getTotalSeconds();1255return secs;1256}12571258//-----------------------------------------------------------------------1259/**1260* Compares this {@code OffsetTime} to another time.1261* <p>1262* The comparison is based first on the UTC equivalent instant, then on the local time.1263* It is "consistent with equals", as defined by {@link Comparable}.1264* <p>1265* For example, the following is the comparator order:1266* <ol>1267* <li>{@code 10:30+01:00}</li>1268* <li>{@code 11:00+01:00}</li>1269* <li>{@code 12:00+02:00}</li>1270* <li>{@code 11:30+01:00}</li>1271* <li>{@code 12:00+01:00}</li>1272* <li>{@code 12:30+01:00}</li>1273* </ol>1274* Values #2 and #3 represent the same instant on the time-line.1275* When two values represent the same instant, the local time is compared1276* to distinguish them. This step is needed to make the ordering1277* consistent with {@code equals()}.1278* <p>1279* To compare the underlying local time of two {@code TemporalAccessor} instances,1280* use {@link ChronoField#NANO_OF_DAY} as a comparator.1281*1282* @param other the other time to compare to, not null1283* @return the comparator value, negative if less, positive if greater1284*/1285@Override1286public int compareTo(OffsetTime other) {1287if (offset.equals(other.offset)) {1288return time.compareTo(other.time);1289}1290int compare = Long.compare(toEpochNano(), other.toEpochNano());1291if (compare == 0) {1292compare = time.compareTo(other.time);1293}1294return compare;1295}12961297//-----------------------------------------------------------------------1298/**1299* Checks if the instant of this {@code OffsetTime} is after that of the1300* specified time applying both times to a common date.1301* <p>1302* This method differs from the comparison in {@link #compareTo} in that it1303* only compares the instant of the time. This is equivalent to converting both1304* times to an instant using the same date and comparing the instants.1305*1306* @param other the other time to compare to, not null1307* @return true if this is after the instant of the specified time1308*/1309public boolean isAfter(OffsetTime other) {1310return toEpochNano() > other.toEpochNano();1311}13121313/**1314* Checks if the instant of this {@code OffsetTime} is before that of the1315* specified time applying both times to a common date.1316* <p>1317* This method differs from the comparison in {@link #compareTo} in that it1318* only compares the instant of the time. This is equivalent to converting both1319* times to an instant using the same date and comparing the instants.1320*1321* @param other the other time to compare to, not null1322* @return true if this is before the instant of the specified time1323*/1324public boolean isBefore(OffsetTime other) {1325return toEpochNano() < other.toEpochNano();1326}13271328/**1329* Checks if the instant of this {@code OffsetTime} is equal to that of the1330* specified time applying both times to a common date.1331* <p>1332* This method differs from the comparison in {@link #compareTo} and {@link #equals}1333* in that it only compares the instant of the time. This is equivalent to converting both1334* times to an instant using the same date and comparing the instants.1335*1336* @param other the other time to compare to, not null1337* @return true if this is equal to the instant of the specified time1338*/1339public boolean isEqual(OffsetTime other) {1340return toEpochNano() == other.toEpochNano();1341}13421343//-----------------------------------------------------------------------1344/**1345* Checks if this time is equal to another time.1346* <p>1347* The comparison is based on the local-time and the offset.1348* To compare for the same instant on the time-line, use {@link #isEqual(OffsetTime)}.1349* <p>1350* Only objects of type {@code OffsetTime} are compared, other types return false.1351* To compare the underlying local time of two {@code TemporalAccessor} instances,1352* use {@link ChronoField#NANO_OF_DAY} as a comparator.1353*1354* @param obj the object to check, null returns false1355* @return true if this is equal to the other time1356*/1357@Override1358public boolean equals(Object obj) {1359if (this == obj) {1360return true;1361}1362return (obj instanceof OffsetTime other)1363&& time.equals(other.time)1364&& offset.equals(other.offset);1365}13661367/**1368* A hash code for this time.1369*1370* @return a suitable hash code1371*/1372@Override1373public int hashCode() {1374return time.hashCode() ^ offset.hashCode();1375}13761377//-----------------------------------------------------------------------1378/**1379* Outputs this time as a {@code String}, such as {@code 10:15:30+01:00}.1380* <p>1381* The output will be one of the following ISO-8601 formats:1382* <ul>1383* <li>{@code HH:mmXXXXX}</li>1384* <li>{@code HH:mm:ssXXXXX}</li>1385* <li>{@code HH:mm:ss.SSSXXXXX}</li>1386* <li>{@code HH:mm:ss.SSSSSSXXXXX}</li>1387* <li>{@code HH:mm:ss.SSSSSSSSSXXXXX}</li>1388* </ul>1389* The format used will be the shortest that outputs the full value of1390* the time where the omitted parts are implied to be zero.1391*1392* @return a string representation of this time, not null1393*/1394@Override1395public String toString() {1396return time.toString() + offset.toString();1397}13981399//-----------------------------------------------------------------------1400/**1401* Writes the object using a1402* <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>.1403* @serialData1404* <pre>1405* out.writeByte(9); // identifies an OffsetTime1406* // the <a href="{@docRoot}/serialized-form.html#java.time.LocalTime">time</a> excluding the one byte header1407* // the <a href="{@docRoot}/serialized-form.html#java.time.ZoneOffset">offset</a> excluding the one byte header1408* </pre>1409*1410* @return the instance of {@code Ser}, not null1411*/1412@java.io.Serial1413private Object writeReplace() {1414return new Ser(Ser.OFFSET_TIME_TYPE, this);1415}14161417/**1418* Defend against malicious streams.1419*1420* @param s the stream to read1421* @throws InvalidObjectException always1422*/1423@java.io.Serial1424private void readObject(ObjectInputStream s) throws InvalidObjectException {1425throw new InvalidObjectException("Deserialization via serialization delegate");1426}14271428void writeExternal(ObjectOutput out) throws IOException {1429time.writeExternal(out);1430offset.writeExternal(out);1431}14321433static OffsetTime readExternal(ObjectInput in) throws IOException, ClassNotFoundException {1434LocalTime time = LocalTime.readExternal(in);1435ZoneOffset offset = ZoneOffset.readExternal(in);1436return OffsetTime.of(time, offset);1437}14381439}144014411442