Path: blob/master/src/java.base/share/classes/java/time/Instant.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_SECOND;64import static java.time.LocalTime.SECONDS_PER_DAY;65import static java.time.LocalTime.SECONDS_PER_HOUR;66import static java.time.LocalTime.SECONDS_PER_MINUTE;67import static java.time.temporal.ChronoField.INSTANT_SECONDS;68import static java.time.temporal.ChronoField.MICRO_OF_SECOND;69import static java.time.temporal.ChronoField.MILLI_OF_SECOND;70import static java.time.temporal.ChronoField.NANO_OF_SECOND;71import static java.time.temporal.ChronoUnit.DAYS;72import static java.time.temporal.ChronoUnit.NANOS;7374import java.io.DataInput;75import java.io.DataOutput;76import java.io.IOException;77import java.io.InvalidObjectException;78import java.io.ObjectInputStream;79import java.io.Serializable;80import java.time.format.DateTimeFormatter;81import java.time.format.DateTimeParseException;82import java.time.temporal.ChronoField;83import java.time.temporal.ChronoUnit;84import java.time.temporal.Temporal;85import java.time.temporal.TemporalAccessor;86import java.time.temporal.TemporalAdjuster;87import java.time.temporal.TemporalAmount;88import java.time.temporal.TemporalField;89import java.time.temporal.TemporalQueries;90import java.time.temporal.TemporalQuery;91import java.time.temporal.TemporalUnit;92import java.time.temporal.UnsupportedTemporalTypeException;93import java.time.temporal.ValueRange;94import java.util.Objects;9596/**97* An instantaneous point on the time-line.98* <p>99* This class models a single instantaneous point on the time-line.100* This might be used to record event time-stamps in the application.101* <p>102* The range of an instant requires the storage of a number larger than a {@code long}.103* To achieve this, the class stores a {@code long} representing epoch-seconds and an104* {@code int} representing nanosecond-of-second, which will always be between 0 and 999,999,999.105* The epoch-seconds are measured from the standard Java epoch of {@code 1970-01-01T00:00:00Z}106* where instants after the epoch have positive values, and earlier instants have negative values.107* For both the epoch-second and nanosecond parts, a larger value is always later on the time-line108* than a smaller value.109*110* <h2>Time-scale</h2>111* <p>112* The length of the solar day is the standard way that humans measure time.113* This has traditionally been subdivided into 24 hours of 60 minutes of 60 seconds,114* forming a 86400 second day.115* <p>116* Modern timekeeping is based on atomic clocks which precisely define an SI second117* relative to the transitions of a Caesium atom. The length of an SI second was defined118* to be very close to the 86400th fraction of a day.119* <p>120* Unfortunately, as the Earth rotates the length of the day varies.121* In addition, over time the average length of the day is getting longer as the Earth slows.122* As a result, the length of a solar day in 2012 is slightly longer than 86400 SI seconds.123* The actual length of any given day and the amount by which the Earth is slowing124* are not predictable and can only be determined by measurement.125* The UT1 time-scale captures the accurate length of day, but is only available some126* time after the day has completed.127* <p>128* The UTC time-scale is a standard approach to bundle up all the additional fractions129* of a second from UT1 into whole seconds, known as <i>leap-seconds</i>.130* A leap-second may be added or removed depending on the Earth's rotational changes.131* As such, UTC permits a day to have 86399 SI seconds or 86401 SI seconds where132* necessary in order to keep the day aligned with the Sun.133* <p>134* The modern UTC time-scale was introduced in 1972, introducing the concept of whole leap-seconds.135* Between 1958 and 1972, the definition of UTC was complex, with minor sub-second leaps and136* alterations to the length of the notional second. As of 2012, discussions are underway137* to change the definition of UTC again, with the potential to remove leap seconds or138* introduce other changes.139* <p>140* Given the complexity of accurate timekeeping described above, this Java API defines141* its own time-scale, the <i>Java Time-Scale</i>.142* <p>143* The Java Time-Scale divides each calendar day into exactly 86400144* subdivisions, known as seconds. These seconds may differ from the145* SI second. It closely matches the de facto international civil time146* scale, the definition of which changes from time to time.147* <p>148* The Java Time-Scale has slightly different definitions for different149* segments of the time-line, each based on the consensus international150* time scale that is used as the basis for civil time. Whenever the151* internationally-agreed time scale is modified or replaced, a new152* segment of the Java Time-Scale must be defined for it. Each segment153* must meet these requirements:154* <ul>155* <li>the Java Time-Scale shall closely match the underlying international156* civil time scale;</li>157* <li>the Java Time-Scale shall exactly match the international civil158* time scale at noon each day;</li>159* <li>the Java Time-Scale shall have a precisely-defined relationship to160* the international civil time scale.</li>161* </ul>162* There are currently, as of 2013, two segments in the Java time-scale.163* <p>164* For the segment from 1972-11-03 (exact boundary discussed below) until165* further notice, the consensus international time scale is UTC (with166* leap seconds). In this segment, the Java Time-Scale is identical to167* <a href="http://www.cl.cam.ac.uk/~mgk25/time/utc-sls/">UTC-SLS</a>.168* This is identical to UTC on days that do not have a leap second.169* On days that do have a leap second, the leap second is spread equally170* over the last 1000 seconds of the day, maintaining the appearance of171* exactly 86400 seconds per day.172* <p>173* For the segment prior to 1972-11-03, extending back arbitrarily far,174* the consensus international time scale is defined to be UT1, applied175* proleptically, which is equivalent to the (mean) solar time on the176* prime meridian (Greenwich). In this segment, the Java Time-Scale is177* identical to the consensus international time scale. The exact178* boundary between the two segments is the instant where UT1 = UTC179* between 1972-11-03T00:00 and 1972-11-04T12:00.180* <p>181* Implementations of the Java time-scale using the JSR-310 API are not182* required to provide any clock that is sub-second accurate, or that183* progresses monotonically or smoothly. Implementations are therefore184* not required to actually perform the UTC-SLS slew or to otherwise be185* aware of leap seconds. JSR-310 does, however, require that186* implementations must document the approach they use when defining a187* clock representing the current instant.188* See {@link Clock} for details on the available clocks.189* <p>190* The Java time-scale is used for all date-time classes.191* This includes {@code Instant}, {@code LocalDate}, {@code LocalTime}, {@code OffsetDateTime},192* {@code ZonedDateTime} and {@code Duration}.193* <p>194* This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>195* class; programmers should treat instances that are196* {@linkplain #equals(Object) equal} as interchangeable and should not197* use instances for synchronization, or unpredictable behavior may198* occur. For example, in a future release, synchronization may fail.199* The {@code equals} method should be used for comparisons.200*201* @implSpec202* This class is immutable and thread-safe.203*204* @since 1.8205*/206@jdk.internal.ValueBased207public final class Instant208implements Temporal, TemporalAdjuster, Comparable<Instant>, Serializable {209210/**211* Constant for the 1970-01-01T00:00:00Z epoch instant.212*/213public static final Instant EPOCH = new Instant(0, 0);214/**215* The minimum supported epoch second.216*/217private static final long MIN_SECOND = -31557014167219200L;218/**219* The maximum supported epoch second.220*/221private static final long MAX_SECOND = 31556889864403199L;222/**223* The minimum supported {@code Instant}, '-1000000000-01-01T00:00Z'.224* This could be used by an application as a "far past" instant.225* <p>226* This is one year earlier than the minimum {@code LocalDateTime}.227* This provides sufficient values to handle the range of {@code ZoneOffset}228* which affect the instant in addition to the local date-time.229* The value is also chosen such that the value of the year fits in230* an {@code int}.231*/232public static final Instant MIN = Instant.ofEpochSecond(MIN_SECOND, 0);233/**234* The maximum supported {@code Instant}, '1000000000-12-31T23:59:59.999999999Z'.235* This could be used by an application as a "far future" instant.236* <p>237* This is one year later than the maximum {@code LocalDateTime}.238* This provides sufficient values to handle the range of {@code ZoneOffset}239* which affect the instant in addition to the local date-time.240* The value is also chosen such that the value of the year fits in241* an {@code int}.242*/243public static final Instant MAX = Instant.ofEpochSecond(MAX_SECOND, 999_999_999);244245/**246* Serialization version.247*/248@java.io.Serial249private static final long serialVersionUID = -665713676816604388L;250251/**252* The number of seconds from the epoch of 1970-01-01T00:00:00Z.253*/254private final long seconds;255/**256* The number of nanoseconds, later along the time-line, from the seconds field.257* This is always positive, and never exceeds 999,999,999.258*/259private final int nanos;260261//-----------------------------------------------------------------------262/**263* Obtains the current instant from the system clock.264* <p>265* This will query the {@link Clock#systemUTC() system UTC clock} to266* obtain the current instant.267* <p>268* Using this method will prevent the ability to use an alternate time-source for269* testing because the clock is effectively hard-coded.270*271* @return the current instant using the system clock, not null272*/273public static Instant now() {274return Clock.systemUTC().instant();275}276277/**278* Obtains the current instant from the specified clock.279* <p>280* This will query the specified clock to obtain the current time.281* <p>282* Using this method allows the use of an alternate clock for testing.283* The alternate clock may be introduced using {@link Clock dependency injection}.284*285* @param clock the clock to use, not null286* @return the current instant, not null287*/288public static Instant now(Clock clock) {289Objects.requireNonNull(clock, "clock");290return clock.instant();291}292293//-----------------------------------------------------------------------294/**295* Obtains an instance of {@code Instant} using seconds from the296* epoch of 1970-01-01T00:00:00Z.297* <p>298* The nanosecond field is set to zero.299*300* @param epochSecond the number of seconds from 1970-01-01T00:00:00Z301* @return an instant, not null302* @throws DateTimeException if the instant exceeds the maximum or minimum instant303*/304public static Instant ofEpochSecond(long epochSecond) {305return create(epochSecond, 0);306}307308/**309* Obtains an instance of {@code Instant} using seconds from the310* epoch of 1970-01-01T00:00:00Z and nanosecond fraction of second.311* <p>312* This method allows an arbitrary number of nanoseconds to be passed in.313* The factory will alter the values of the second and nanosecond in order314* to ensure that the stored nanosecond is in the range 0 to 999,999,999.315* For example, the following will result in exactly the same instant:316* <pre>317* Instant.ofEpochSecond(3, 1);318* Instant.ofEpochSecond(4, -999_999_999);319* Instant.ofEpochSecond(2, 1000_000_001);320* </pre>321*322* @param epochSecond the number of seconds from 1970-01-01T00:00:00Z323* @param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative324* @return an instant, not null325* @throws DateTimeException if the instant exceeds the maximum or minimum instant326* @throws ArithmeticException if numeric overflow occurs327*/328public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment) {329long secs = Math.addExact(epochSecond, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND));330int nos = (int)Math.floorMod(nanoAdjustment, NANOS_PER_SECOND);331return create(secs, nos);332}333334/**335* Obtains an instance of {@code Instant} using milliseconds from the336* epoch of 1970-01-01T00:00:00Z.337* <p>338* The seconds and nanoseconds are extracted from the specified milliseconds.339*340* @param epochMilli the number of milliseconds from 1970-01-01T00:00:00Z341* @return an instant, not null342* @throws DateTimeException if the instant exceeds the maximum or minimum instant343*/344public static Instant ofEpochMilli(long epochMilli) {345long secs = Math.floorDiv(epochMilli, 1000);346int mos = Math.floorMod(epochMilli, 1000);347return create(secs, mos * 1000_000);348}349350//-----------------------------------------------------------------------351/**352* Obtains an instance of {@code Instant} from a temporal object.353* <p>354* This obtains an instant based on the specified temporal.355* A {@code TemporalAccessor} represents an arbitrary set of date and time information,356* which this factory converts to an instance of {@code Instant}.357* <p>358* The conversion extracts the {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS}359* and {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} fields.360* <p>361* This method matches the signature of the functional interface {@link TemporalQuery}362* allowing it to be used as a query via method reference, {@code Instant::from}.363*364* @param temporal the temporal object to convert, not null365* @return the instant, not null366* @throws DateTimeException if unable to convert to an {@code Instant}367*/368public static Instant from(TemporalAccessor temporal) {369if (temporal instanceof Instant) {370return (Instant) temporal;371}372Objects.requireNonNull(temporal, "temporal");373try {374long instantSecs = temporal.getLong(INSTANT_SECONDS);375int nanoOfSecond = temporal.get(NANO_OF_SECOND);376return Instant.ofEpochSecond(instantSecs, nanoOfSecond);377} catch (DateTimeException ex) {378throw new DateTimeException("Unable to obtain Instant from TemporalAccessor: " +379temporal + " of type " + temporal.getClass().getName(), ex);380}381}382383//-----------------------------------------------------------------------384/**385* Obtains an instance of {@code Instant} from a text string such as386* {@code 2007-12-03T10:15:30.00Z}.387* <p>388* The string must represent a valid instant in UTC and is parsed using389* {@link DateTimeFormatter#ISO_INSTANT}.390*391* @param text the text to parse, not null392* @return the parsed instant, not null393* @throws DateTimeParseException if the text cannot be parsed394*/395public static Instant parse(final CharSequence text) {396return DateTimeFormatter.ISO_INSTANT.parse(text, Instant::from);397}398399//-----------------------------------------------------------------------400/**401* Obtains an instance of {@code Instant} using seconds and nanoseconds.402*403* @param seconds the length of the duration in seconds404* @param nanoOfSecond the nano-of-second, from 0 to 999,999,999405* @throws DateTimeException if the instant exceeds the maximum or minimum instant406*/407private static Instant create(long seconds, int nanoOfSecond) {408if ((seconds | nanoOfSecond) == 0) {409return EPOCH;410}411if (seconds < MIN_SECOND || seconds > MAX_SECOND) {412throw new DateTimeException("Instant exceeds minimum or maximum instant");413}414return new Instant(seconds, nanoOfSecond);415}416417/**418* Constructs an instance of {@code Instant} using seconds from the epoch of419* 1970-01-01T00:00:00Z and nanosecond fraction of second.420*421* @param epochSecond the number of seconds from 1970-01-01T00:00:00Z422* @param nanos the nanoseconds within the second, must be positive423*/424private Instant(long epochSecond, int nanos) {425super();426this.seconds = epochSecond;427this.nanos = nanos;428}429430//-----------------------------------------------------------------------431/**432* Checks if the specified field is supported.433* <p>434* This checks if this instant can be queried for the specified field.435* If false, then calling the {@link #range(TemporalField) range},436* {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}437* methods will throw an exception.438* <p>439* If the field is a {@link ChronoField} then the query is implemented here.440* The supported fields are:441* <ul>442* <li>{@code NANO_OF_SECOND}443* <li>{@code MICRO_OF_SECOND}444* <li>{@code MILLI_OF_SECOND}445* <li>{@code INSTANT_SECONDS}446* </ul>447* All other {@code ChronoField} instances will return false.448* <p>449* If the field is not a {@code ChronoField}, then the result of this method450* is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}451* passing {@code this} as the argument.452* Whether the field is supported is determined by the field.453*454* @param field the field to check, null returns false455* @return true if the field is supported on this instant, false if not456*/457@Override458public boolean isSupported(TemporalField field) {459if (field instanceof ChronoField) {460return field == INSTANT_SECONDS || field == NANO_OF_SECOND || field == MICRO_OF_SECOND || field == MILLI_OF_SECOND;461}462return field != null && field.isSupportedBy(this);463}464465/**466* Checks if the specified unit is supported.467* <p>468* This checks if the specified unit can be added to, or subtracted from, this date-time.469* If false, then calling the {@link #plus(long, TemporalUnit)} and470* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.471* <p>472* If the unit is a {@link ChronoUnit} then the query is implemented here.473* The supported units are:474* <ul>475* <li>{@code NANOS}476* <li>{@code MICROS}477* <li>{@code MILLIS}478* <li>{@code SECONDS}479* <li>{@code MINUTES}480* <li>{@code HOURS}481* <li>{@code HALF_DAYS}482* <li>{@code DAYS}483* </ul>484* All other {@code ChronoUnit} instances will return false.485* <p>486* If the unit is not a {@code ChronoUnit}, then the result of this method487* is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}488* passing {@code this} as the argument.489* Whether the unit is supported is determined by the unit.490*491* @param unit the unit to check, null returns false492* @return true if the unit can be added/subtracted, false if not493*/494@Override495public boolean isSupported(TemporalUnit unit) {496if (unit instanceof ChronoUnit) {497return unit.isTimeBased() || unit == DAYS;498}499return unit != null && unit.isSupportedBy(this);500}501502//-----------------------------------------------------------------------503/**504* Gets the range of valid values for the specified field.505* <p>506* The range object expresses the minimum and maximum valid values for a field.507* This instant is used to enhance the accuracy of the returned range.508* If it is not possible to return the range, because the field is not supported509* or for some other reason, an exception is thrown.510* <p>511* If the field is a {@link ChronoField} then the query is implemented here.512* The {@link #isSupported(TemporalField) supported fields} will return513* appropriate range instances.514* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.515* <p>516* If the field is not a {@code ChronoField}, then the result of this method517* is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}518* passing {@code this} as the argument.519* Whether the range can be obtained is determined by the field.520*521* @param field the field to query the range for, not null522* @return the range of valid values for the field, not null523* @throws DateTimeException if the range for the field cannot be obtained524* @throws UnsupportedTemporalTypeException if the field is not supported525*/526@Override // override for Javadoc527public ValueRange range(TemporalField field) {528return Temporal.super.range(field);529}530531/**532* Gets the value of the specified field from this instant as an {@code int}.533* <p>534* This queries this instant for the value of the specified field.535* The returned value will always be within the valid range of values for the field.536* If it is not possible to return the value, because the field is not supported537* or for some other reason, an exception is thrown.538* <p>539* If the field is a {@link ChronoField} then the query is implemented here.540* The {@link #isSupported(TemporalField) supported fields} will return valid541* values based on this date-time, except {@code INSTANT_SECONDS} which is too542* large to fit in an {@code int} and throws a {@code DateTimeException}.543* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.544* <p>545* If the field is not a {@code ChronoField}, then the result of this method546* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}547* passing {@code this} as the argument. Whether the value can be obtained,548* and what the value represents, is determined by the field.549*550* @param field the field to get, not null551* @return the value for the field552* @throws DateTimeException if a value for the field cannot be obtained or553* the value is outside the range of valid values for the field554* @throws UnsupportedTemporalTypeException if the field is not supported or555* the range of values exceeds an {@code int}556* @throws ArithmeticException if numeric overflow occurs557*/558@Override // override for Javadoc and performance559public int get(TemporalField field) {560if (field instanceof ChronoField) {561switch ((ChronoField) field) {562case NANO_OF_SECOND: return nanos;563case MICRO_OF_SECOND: return nanos / 1000;564case MILLI_OF_SECOND: return nanos / 1000_000;565}566throw new UnsupportedTemporalTypeException("Unsupported field: " + field);567}568return range(field).checkValidIntValue(field.getFrom(this), field);569}570571/**572* Gets the value of the specified field from this instant as a {@code long}.573* <p>574* This queries this instant for the value of the specified field.575* If it is not possible to return the value, because the field is not supported576* or for some other reason, an exception is thrown.577* <p>578* If the field is a {@link ChronoField} then the query is implemented here.579* The {@link #isSupported(TemporalField) supported fields} will return valid580* values based on this date-time.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 obtained591* @throws UnsupportedTemporalTypeException if the field is not supported592* @throws ArithmeticException if numeric overflow occurs593*/594@Override595public long getLong(TemporalField field) {596if (field instanceof ChronoField) {597switch ((ChronoField) field) {598case NANO_OF_SECOND: return nanos;599case MICRO_OF_SECOND: return nanos / 1000;600case MILLI_OF_SECOND: return nanos / 1000_000;601case INSTANT_SECONDS: return seconds;602}603throw new UnsupportedTemporalTypeException("Unsupported field: " + field);604}605return field.getFrom(this);606}607608//-----------------------------------------------------------------------609/**610* Gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z.611* <p>612* The epoch second count is a simple incrementing count of seconds where613* second 0 is 1970-01-01T00:00:00Z.614* The nanosecond part is returned by {@link #getNano}.615*616* @return the seconds from the epoch of 1970-01-01T00:00:00Z617*/618public long getEpochSecond() {619return seconds;620}621622/**623* Gets the number of nanoseconds, later along the time-line, from the start624* of the second.625* <p>626* The nanosecond-of-second value measures the total number of nanoseconds from627* the second returned by {@link #getEpochSecond}.628*629* @return the nanoseconds within the second, always positive, never exceeds 999,999,999630*/631public int getNano() {632return nanos;633}634635//-------------------------------------------------------------------------636/**637* Returns an adjusted copy of this instant.638* <p>639* This returns an {@code Instant}, based on this one, with the instant adjusted.640* The adjustment takes place using the specified adjuster strategy object.641* Read the documentation of the adjuster to understand what adjustment will be made.642* <p>643* The result of this method is obtained by invoking the644* {@link TemporalAdjuster#adjustInto(Temporal)} method on the645* specified adjuster passing {@code this} as the argument.646* <p>647* This instance is immutable and unaffected by this method call.648*649* @param adjuster the adjuster to use, not null650* @return an {@code Instant} based on {@code this} with the adjustment made, not null651* @throws DateTimeException if the adjustment cannot be made652* @throws ArithmeticException if numeric overflow occurs653*/654@Override655public Instant with(TemporalAdjuster adjuster) {656return (Instant) adjuster.adjustInto(this);657}658659/**660* Returns a copy of this instant with the specified field set to a new value.661* <p>662* This returns an {@code Instant}, based on this one, with the value663* for the specified field changed.664* If it is not possible to set the value, because the field is not supported or for665* some other reason, an exception is thrown.666* <p>667* If the field is a {@link ChronoField} then the adjustment is implemented here.668* The supported fields behave as follows:669* <ul>670* <li>{@code NANO_OF_SECOND} -671* Returns an {@code Instant} with the specified nano-of-second.672* The epoch-second will be unchanged.673* <li>{@code MICRO_OF_SECOND} -674* Returns an {@code Instant} with the nano-of-second replaced by the specified675* micro-of-second multiplied by 1,000. The epoch-second will be unchanged.676* <li>{@code MILLI_OF_SECOND} -677* Returns an {@code Instant} with the nano-of-second replaced by the specified678* milli-of-second multiplied by 1,000,000. The epoch-second will be unchanged.679* <li>{@code INSTANT_SECONDS} -680* Returns an {@code Instant} with the specified epoch-second.681* The nano-of-second will be unchanged.682* </ul>683* <p>684* In all cases, if the new value is outside the valid range of values for the field685* then a {@code DateTimeException} will be thrown.686* <p>687* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.688* <p>689* If the field is not a {@code ChronoField}, then the result of this method690* is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}691* passing {@code this} as the argument. In this case, the field determines692* whether and how to adjust the instant.693* <p>694* This instance is immutable and unaffected by this method call.695*696* @param field the field to set in the result, not null697* @param newValue the new value of the field in the result698* @return an {@code Instant} based on {@code this} with the specified field set, not null699* @throws DateTimeException if the field cannot be set700* @throws UnsupportedTemporalTypeException if the field is not supported701* @throws ArithmeticException if numeric overflow occurs702*/703@Override704public Instant with(TemporalField field, long newValue) {705if (field instanceof ChronoField chronoField) {706chronoField.checkValidValue(newValue);707switch (chronoField) {708case MILLI_OF_SECOND: {709int nval = (int) newValue * 1000_000;710return (nval != nanos ? create(seconds, nval) : this);711}712case MICRO_OF_SECOND: {713int nval = (int) newValue * 1000;714return (nval != nanos ? create(seconds, nval) : this);715}716case NANO_OF_SECOND: return (newValue != nanos ? create(seconds, (int) newValue) : this);717case INSTANT_SECONDS: return (newValue != seconds ? create(newValue, nanos) : this);718}719throw new UnsupportedTemporalTypeException("Unsupported field: " + field);720}721return field.adjustInto(this, newValue);722}723724//-----------------------------------------------------------------------725/**726* Returns a copy of this {@code Instant} truncated to the specified unit.727* <p>728* Truncating the instant returns a copy of the original with fields729* smaller than the specified unit set to zero.730* The fields are calculated on the basis of using a UTC offset as seen731* in {@code toString}.732* For example, truncating with the {@link ChronoUnit#MINUTES MINUTES} unit will733* round down to the nearest minute, setting the seconds and nanoseconds to zero.734* <p>735* The unit must have a {@linkplain TemporalUnit#getDuration() duration}736* that divides into the length of a standard day without remainder.737* This includes all supplied time units on {@link ChronoUnit} and738* {@link ChronoUnit#DAYS DAYS}. Other units throw an exception.739* <p>740* This instance is immutable and unaffected by this method call.741*742* @param unit the unit to truncate to, not null743* @return an {@code Instant} based on this instant with the time truncated, not null744* @throws DateTimeException if the unit is invalid for truncation745* @throws UnsupportedTemporalTypeException if the unit is not supported746*/747public Instant truncatedTo(TemporalUnit unit) {748if (unit == ChronoUnit.NANOS) {749return this;750}751Duration unitDur = unit.getDuration();752if (unitDur.getSeconds() > LocalTime.SECONDS_PER_DAY) {753throw new UnsupportedTemporalTypeException("Unit is too large to be used for truncation");754}755long dur = unitDur.toNanos();756if ((LocalTime.NANOS_PER_DAY % dur) != 0) {757throw new UnsupportedTemporalTypeException("Unit must divide into a standard day without remainder");758}759long nod = (seconds % LocalTime.SECONDS_PER_DAY) * LocalTime.NANOS_PER_SECOND + nanos;760long result = Math.floorDiv(nod, dur) * dur;761return plusNanos(result - nod);762}763764//-----------------------------------------------------------------------765/**766* Returns a copy of this instant with the specified amount added.767* <p>768* This returns an {@code Instant}, based on this one, with the specified amount added.769* The amount is typically {@link Duration} but may be any other type implementing770* the {@link TemporalAmount} interface.771* <p>772* The calculation is delegated to the amount object by calling773* {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free774* to implement the addition in any way it wishes, however it typically775* calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation776* of the amount implementation to determine if it can be successfully added.777* <p>778* This instance is immutable and unaffected by this method call.779*780* @param amountToAdd the amount to add, not null781* @return an {@code Instant} based on this instant with the addition made, not null782* @throws DateTimeException if the addition cannot be made783* @throws ArithmeticException if numeric overflow occurs784*/785@Override786public Instant plus(TemporalAmount amountToAdd) {787return (Instant) amountToAdd.addTo(this);788}789790/**791* Returns a copy of this instant with the specified amount added.792* <p>793* This returns an {@code Instant}, based on this one, with the amount794* in terms of the unit added. If it is not possible to add the amount, because the795* unit is not supported or for some other reason, an exception is thrown.796* <p>797* If the field is a {@link ChronoUnit} then the addition is implemented here.798* The supported fields behave as follows:799* <ul>800* <li>{@code NANOS} -801* Returns an {@code Instant} with the specified number of nanoseconds added.802* This is equivalent to {@link #plusNanos(long)}.803* <li>{@code MICROS} -804* Returns an {@code Instant} with the specified number of microseconds added.805* This is equivalent to {@link #plusNanos(long)} with the amount806* multiplied by 1,000.807* <li>{@code MILLIS} -808* Returns an {@code Instant} with the specified number of milliseconds added.809* This is equivalent to {@link #plusNanos(long)} with the amount810* multiplied by 1,000,000.811* <li>{@code SECONDS} -812* Returns an {@code Instant} with the specified number of seconds added.813* This is equivalent to {@link #plusSeconds(long)}.814* <li>{@code MINUTES} -815* Returns an {@code Instant} with the specified number of minutes added.816* This is equivalent to {@link #plusSeconds(long)} with the amount817* multiplied by 60.818* <li>{@code HOURS} -819* Returns an {@code Instant} with the specified number of hours added.820* This is equivalent to {@link #plusSeconds(long)} with the amount821* multiplied by 3,600.822* <li>{@code HALF_DAYS} -823* Returns an {@code Instant} with the specified number of half-days added.824* This is equivalent to {@link #plusSeconds(long)} with the amount825* multiplied by 43,200 (12 hours).826* <li>{@code DAYS} -827* Returns an {@code Instant} with the specified number of days added.828* This is equivalent to {@link #plusSeconds(long)} with the amount829* multiplied by 86,400 (24 hours).830* </ul>831* <p>832* All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}.833* <p>834* If the field is not a {@code ChronoUnit}, then the result of this method835* is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}836* passing {@code this} as the argument. In this case, the unit determines837* whether and how to perform the addition.838* <p>839* This instance is immutable and unaffected by this method call.840*841* @param amountToAdd the amount of the unit to add to the result, may be negative842* @param unit the unit of the amount to add, not null843* @return an {@code Instant} based on this instant with the specified amount added, not null844* @throws DateTimeException if the addition cannot be made845* @throws UnsupportedTemporalTypeException if the unit is not supported846* @throws ArithmeticException if numeric overflow occurs847*/848@Override849public Instant plus(long amountToAdd, TemporalUnit unit) {850if (unit instanceof ChronoUnit) {851switch ((ChronoUnit) unit) {852case NANOS: return plusNanos(amountToAdd);853case MICROS: return plus(amountToAdd / 1000_000, (amountToAdd % 1000_000) * 1000);854case MILLIS: return plusMillis(amountToAdd);855case SECONDS: return plusSeconds(amountToAdd);856case MINUTES: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_MINUTE));857case HOURS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_HOUR));858case HALF_DAYS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY / 2));859case DAYS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY));860}861throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);862}863return unit.addTo(this, amountToAdd);864}865866//-----------------------------------------------------------------------867/**868* Returns a copy of this instant with the specified duration in seconds added.869* <p>870* This instance is immutable and unaffected by this method call.871*872* @param secondsToAdd the seconds to add, positive or negative873* @return an {@code Instant} based on this instant with the specified seconds added, not null874* @throws DateTimeException if the result exceeds the maximum or minimum instant875* @throws ArithmeticException if numeric overflow occurs876*/877public Instant plusSeconds(long secondsToAdd) {878return plus(secondsToAdd, 0);879}880881/**882* Returns a copy of this instant with the specified duration in milliseconds added.883* <p>884* This instance is immutable and unaffected by this method call.885*886* @param millisToAdd the milliseconds to add, positive or negative887* @return an {@code Instant} based on this instant with the specified milliseconds added, not null888* @throws DateTimeException if the result exceeds the maximum or minimum instant889* @throws ArithmeticException if numeric overflow occurs890*/891public Instant plusMillis(long millisToAdd) {892return plus(millisToAdd / 1000, (millisToAdd % 1000) * 1000_000);893}894895/**896* Returns a copy of this instant with the specified duration in nanoseconds added.897* <p>898* This instance is immutable and unaffected by this method call.899*900* @param nanosToAdd the nanoseconds to add, positive or negative901* @return an {@code Instant} based on this instant with the specified nanoseconds added, not null902* @throws DateTimeException if the result exceeds the maximum or minimum instant903* @throws ArithmeticException if numeric overflow occurs904*/905public Instant plusNanos(long nanosToAdd) {906return plus(0, nanosToAdd);907}908909/**910* Returns a copy of this instant with the specified duration added.911* <p>912* This instance is immutable and unaffected by this method call.913*914* @param secondsToAdd the seconds to add, positive or negative915* @param nanosToAdd the nanos to add, positive or negative916* @return an {@code Instant} based on this instant with the specified seconds added, not null917* @throws DateTimeException if the result exceeds the maximum or minimum instant918* @throws ArithmeticException if numeric overflow occurs919*/920private Instant plus(long secondsToAdd, long nanosToAdd) {921if ((secondsToAdd | nanosToAdd) == 0) {922return this;923}924long epochSec = Math.addExact(seconds, secondsToAdd);925epochSec = Math.addExact(epochSec, nanosToAdd / NANOS_PER_SECOND);926nanosToAdd = nanosToAdd % NANOS_PER_SECOND;927long nanoAdjustment = nanos + nanosToAdd; // safe int+NANOS_PER_SECOND928return ofEpochSecond(epochSec, nanoAdjustment);929}930931//-----------------------------------------------------------------------932/**933* Returns a copy of this instant with the specified amount subtracted.934* <p>935* This returns an {@code Instant}, based on this one, with the specified amount subtracted.936* The amount is typically {@link Duration} but may be any other type implementing937* the {@link TemporalAmount} interface.938* <p>939* The calculation is delegated to the amount object by calling940* {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free941* to implement the subtraction in any way it wishes, however it typically942* calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation943* of the amount implementation to determine if it can be successfully subtracted.944* <p>945* This instance is immutable and unaffected by this method call.946*947* @param amountToSubtract the amount to subtract, not null948* @return an {@code Instant} based on this instant with the subtraction made, not null949* @throws DateTimeException if the subtraction cannot be made950* @throws ArithmeticException if numeric overflow occurs951*/952@Override953public Instant minus(TemporalAmount amountToSubtract) {954return (Instant) amountToSubtract.subtractFrom(this);955}956957/**958* Returns a copy of this instant with the specified amount subtracted.959* <p>960* This returns an {@code Instant}, based on this one, with the amount961* in terms of the unit subtracted. If it is not possible to subtract the amount,962* because the unit is not supported or for some other reason, an exception is thrown.963* <p>964* This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.965* See that method for a full description of how addition, and thus subtraction, works.966* <p>967* This instance is immutable and unaffected by this method call.968*969* @param amountToSubtract the amount of the unit to subtract from the result, may be negative970* @param unit the unit of the amount to subtract, not null971* @return an {@code Instant} based on this instant with the specified amount subtracted, not null972* @throws DateTimeException if the subtraction cannot be made973* @throws UnsupportedTemporalTypeException if the unit is not supported974* @throws ArithmeticException if numeric overflow occurs975*/976@Override977public Instant minus(long amountToSubtract, TemporalUnit unit) {978return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));979}980981//-----------------------------------------------------------------------982/**983* Returns a copy of this instant with the specified duration in seconds subtracted.984* <p>985* This instance is immutable and unaffected by this method call.986*987* @param secondsToSubtract the seconds to subtract, positive or negative988* @return an {@code Instant} based on this instant with the specified seconds subtracted, not null989* @throws DateTimeException if the result exceeds the maximum or minimum instant990* @throws ArithmeticException if numeric overflow occurs991*/992public Instant minusSeconds(long secondsToSubtract) {993if (secondsToSubtract == Long.MIN_VALUE) {994return plusSeconds(Long.MAX_VALUE).plusSeconds(1);995}996return plusSeconds(-secondsToSubtract);997}998999/**1000* Returns a copy of this instant with the specified duration in milliseconds subtracted.1001* <p>1002* This instance is immutable and unaffected by this method call.1003*1004* @param millisToSubtract the milliseconds to subtract, positive or negative1005* @return an {@code Instant} based on this instant with the specified milliseconds subtracted, not null1006* @throws DateTimeException if the result exceeds the maximum or minimum instant1007* @throws ArithmeticException if numeric overflow occurs1008*/1009public Instant minusMillis(long millisToSubtract) {1010if (millisToSubtract == Long.MIN_VALUE) {1011return plusMillis(Long.MAX_VALUE).plusMillis(1);1012}1013return plusMillis(-millisToSubtract);1014}10151016/**1017* Returns a copy of this instant with the specified duration in nanoseconds subtracted.1018* <p>1019* This instance is immutable and unaffected by this method call.1020*1021* @param nanosToSubtract the nanoseconds to subtract, positive or negative1022* @return an {@code Instant} based on this instant with the specified nanoseconds subtracted, not null1023* @throws DateTimeException if the result exceeds the maximum or minimum instant1024* @throws ArithmeticException if numeric overflow occurs1025*/1026public Instant minusNanos(long nanosToSubtract) {1027if (nanosToSubtract == Long.MIN_VALUE) {1028return plusNanos(Long.MAX_VALUE).plusNanos(1);1029}1030return plusNanos(-nanosToSubtract);1031}10321033//-------------------------------------------------------------------------1034/**1035* Queries this instant using the specified query.1036* <p>1037* This queries this instant using the specified query strategy object.1038* The {@code TemporalQuery} object defines the logic to be used to1039* obtain the result. Read the documentation of the query to understand1040* what the result of this method will be.1041* <p>1042* The result of this method is obtained by invoking the1043* {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the1044* specified query passing {@code this} as the argument.1045*1046* @param <R> the type of the result1047* @param query the query to invoke, not null1048* @return the query result, null may be returned (defined by the query)1049* @throws DateTimeException if unable to query (defined by the query)1050* @throws ArithmeticException if numeric overflow occurs (defined by the query)1051*/1052@SuppressWarnings("unchecked")1053@Override1054public <R> R query(TemporalQuery<R> query) {1055if (query == TemporalQueries.precision()) {1056return (R) NANOS;1057}1058// inline TemporalAccessor.super.query(query) as an optimization1059if (query == TemporalQueries.chronology() || query == TemporalQueries.zoneId() ||1060query == TemporalQueries.zone() || query == TemporalQueries.offset() ||1061query == TemporalQueries.localDate() || query == TemporalQueries.localTime()) {1062return null;1063}1064return query.queryFrom(this);1065}10661067/**1068* Adjusts the specified temporal object to have this instant.1069* <p>1070* This returns a temporal object of the same observable type as the input1071* with the instant changed to be the same as this.1072* <p>1073* The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}1074* twice, passing {@link ChronoField#INSTANT_SECONDS} and1075* {@link ChronoField#NANO_OF_SECOND} as the fields.1076* <p>1077* In most cases, it is clearer to reverse the calling pattern by using1078* {@link Temporal#with(TemporalAdjuster)}:1079* <pre>1080* // these two lines are equivalent, but the second approach is recommended1081* temporal = thisInstant.adjustInto(temporal);1082* temporal = temporal.with(thisInstant);1083* </pre>1084* <p>1085* This instance is immutable and unaffected by this method call.1086*1087* @param temporal the target object to be adjusted, not null1088* @return the adjusted object, not null1089* @throws DateTimeException if unable to make the adjustment1090* @throws ArithmeticException if numeric overflow occurs1091*/1092@Override1093public Temporal adjustInto(Temporal temporal) {1094return temporal.with(INSTANT_SECONDS, seconds).with(NANO_OF_SECOND, nanos);1095}10961097/**1098* Calculates the amount of time until another instant in terms of the specified unit.1099* <p>1100* This calculates the amount of time between two {@code Instant}1101* objects in terms of a single {@code TemporalUnit}.1102* The start and end points are {@code this} and the specified instant.1103* The result will be negative if the end is before the start.1104* The calculation returns a whole number, representing the number of1105* complete units between the two instants.1106* The {@code Temporal} passed to this method is converted to a1107* {@code Instant} using {@link #from(TemporalAccessor)}.1108* For example, the amount in seconds between two dates can be calculated1109* using {@code startInstant.until(endInstant, SECONDS)}.1110* <p>1111* There are two equivalent ways of using this method.1112* The first is to invoke this method.1113* The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:1114* <pre>1115* // these two lines are equivalent1116* amount = start.until(end, SECONDS);1117* amount = SECONDS.between(start, end);1118* </pre>1119* The choice should be made based on which makes the code more readable.1120* <p>1121* The calculation is implemented in this method for {@link ChronoUnit}.1122* The units {@code NANOS}, {@code MICROS}, {@code MILLIS}, {@code SECONDS},1123* {@code MINUTES}, {@code HOURS}, {@code HALF_DAYS} and {@code DAYS}1124* are supported. Other {@code ChronoUnit} values will throw an exception.1125* <p>1126* If the unit is not a {@code ChronoUnit}, then the result of this method1127* is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}1128* passing {@code this} as the first argument and the converted input temporal1129* as the second argument.1130* <p>1131* This instance is immutable and unaffected by this method call.1132*1133* @param endExclusive the end date, exclusive, which is converted to an {@code Instant}, not null1134* @param unit the unit to measure the amount in, not null1135* @return the amount of time between this instant and the end instant1136* @throws DateTimeException if the amount cannot be calculated, or the end1137* temporal cannot be converted to an {@code Instant}1138* @throws UnsupportedTemporalTypeException if the unit is not supported1139* @throws ArithmeticException if numeric overflow occurs1140*/1141@Override1142public long until(Temporal endExclusive, TemporalUnit unit) {1143Instant end = Instant.from(endExclusive);1144if (unit instanceof ChronoUnit chronoUnit) {1145switch (chronoUnit) {1146case NANOS: return nanosUntil(end);1147case MICROS: return nanosUntil(end) / 1000;1148case MILLIS: return Math.subtractExact(end.toEpochMilli(), toEpochMilli());1149case SECONDS: return secondsUntil(end);1150case MINUTES: return secondsUntil(end) / SECONDS_PER_MINUTE;1151case HOURS: return secondsUntil(end) / SECONDS_PER_HOUR;1152case HALF_DAYS: return secondsUntil(end) / (12 * SECONDS_PER_HOUR);1153case DAYS: return secondsUntil(end) / (SECONDS_PER_DAY);1154}1155throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);1156}1157return unit.between(this, end);1158}11591160private long nanosUntil(Instant end) {1161long secsDiff = Math.subtractExact(end.seconds, seconds);1162long totalNanos = Math.multiplyExact(secsDiff, NANOS_PER_SECOND);1163return Math.addExact(totalNanos, end.nanos - nanos);1164}11651166private long secondsUntil(Instant end) {1167long secsDiff = Math.subtractExact(end.seconds, seconds);1168long nanosDiff = end.nanos - nanos;1169if (secsDiff > 0 && nanosDiff < 0) {1170secsDiff--;1171} else if (secsDiff < 0 && nanosDiff > 0) {1172secsDiff++;1173}1174return secsDiff;1175}11761177//-----------------------------------------------------------------------1178/**1179* Combines this instant with an offset to create an {@code OffsetDateTime}.1180* <p>1181* This returns an {@code OffsetDateTime} formed from this instant at the1182* specified offset from UTC/Greenwich. An exception will be thrown if the1183* instant is too large to fit into an offset date-time.1184* <p>1185* This method is equivalent to1186* {@link OffsetDateTime#ofInstant(Instant, ZoneId) OffsetDateTime.ofInstant(this, offset)}.1187*1188* @param offset the offset to combine with, not null1189* @return the offset date-time formed from this instant and the specified offset, not null1190* @throws DateTimeException if the result exceeds the supported range1191*/1192public OffsetDateTime atOffset(ZoneOffset offset) {1193return OffsetDateTime.ofInstant(this, offset);1194}11951196/**1197* Combines this instant with a time-zone to create a {@code ZonedDateTime}.1198* <p>1199* This returns an {@code ZonedDateTime} formed from this instant at the1200* specified time-zone. An exception will be thrown if the instant is too1201* large to fit into a zoned date-time.1202* <p>1203* This method is equivalent to1204* {@link ZonedDateTime#ofInstant(Instant, ZoneId) ZonedDateTime.ofInstant(this, zone)}.1205*1206* @param zone the zone to combine with, not null1207* @return the zoned date-time formed from this instant and the specified zone, not null1208* @throws DateTimeException if the result exceeds the supported range1209*/1210public ZonedDateTime atZone(ZoneId zone) {1211return ZonedDateTime.ofInstant(this, zone);1212}12131214//-----------------------------------------------------------------------1215/**1216* Converts this instant to the number of milliseconds from the epoch1217* of 1970-01-01T00:00:00Z.1218* <p>1219* If this instant represents a point on the time-line too far in the future1220* or past to fit in a {@code long} milliseconds, then an exception is thrown.1221* <p>1222* If this instant has greater than millisecond precision, then the conversion1223* will drop any excess precision information as though the amount in nanoseconds1224* was subject to integer division by one million.1225*1226* @return the number of milliseconds since the epoch of 1970-01-01T00:00:00Z1227* @throws ArithmeticException if numeric overflow occurs1228*/1229public long toEpochMilli() {1230if (seconds < 0 && nanos > 0) {1231long millis = Math.multiplyExact(seconds+1, 1000);1232long adjustment = nanos / 1000_000 - 1000;1233return Math.addExact(millis, adjustment);1234} else {1235long millis = Math.multiplyExact(seconds, 1000);1236return Math.addExact(millis, nanos / 1000_000);1237}1238}12391240//-----------------------------------------------------------------------1241/**1242* Compares this instant to the specified instant.1243* <p>1244* The comparison is based on the time-line position of the instants.1245* It is "consistent with equals", as defined by {@link Comparable}.1246*1247* @param otherInstant the other instant to compare to, not null1248* @return the comparator value, negative if less, positive if greater1249* @throws NullPointerException if otherInstant is null1250*/1251@Override1252public int compareTo(Instant otherInstant) {1253int cmp = Long.compare(seconds, otherInstant.seconds);1254if (cmp != 0) {1255return cmp;1256}1257return nanos - otherInstant.nanos;1258}12591260/**1261* Checks if this instant is after the specified instant.1262* <p>1263* The comparison is based on the time-line position of the instants.1264*1265* @param otherInstant the other instant to compare to, not null1266* @return true if this instant is after the specified instant1267* @throws NullPointerException if otherInstant is null1268*/1269public boolean isAfter(Instant otherInstant) {1270return compareTo(otherInstant) > 0;1271}12721273/**1274* Checks if this instant is before the specified instant.1275* <p>1276* The comparison is based on the time-line position of the instants.1277*1278* @param otherInstant the other instant to compare to, not null1279* @return true if this instant is before the specified instant1280* @throws NullPointerException if otherInstant is null1281*/1282public boolean isBefore(Instant otherInstant) {1283return compareTo(otherInstant) < 0;1284}12851286//-----------------------------------------------------------------------1287/**1288* Checks if this instant is equal to the specified instant.1289* <p>1290* The comparison is based on the time-line position of the instants.1291*1292* @param other the other instant, null returns false1293* @return true if the other instant is equal to this one1294*/1295@Override1296public boolean equals(Object other) {1297if (this == other) {1298return true;1299}1300return (other instanceof Instant otherInstant)1301&& this.seconds == otherInstant.seconds1302&& this.nanos == otherInstant.nanos;1303}13041305/**1306* Returns a hash code for this instant.1307*1308* @return a suitable hash code1309*/1310@Override1311public int hashCode() {1312return ((int) (seconds ^ (seconds >>> 32))) + 51 * nanos;1313}13141315//-----------------------------------------------------------------------1316/**1317* A string representation of this instant using ISO-8601 representation.1318* <p>1319* The format used is the same as {@link DateTimeFormatter#ISO_INSTANT}.1320*1321* @return an ISO-8601 representation of this instant, not null1322*/1323@Override1324public String toString() {1325return DateTimeFormatter.ISO_INSTANT.format(this);1326}13271328// -----------------------------------------------------------------------1329/**1330* Writes the object using a1331* <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>.1332* @serialData1333* <pre>1334* out.writeByte(2); // identifies an Instant1335* out.writeLong(seconds);1336* out.writeInt(nanos);1337* </pre>1338*1339* @return the instance of {@code Ser}, not null1340*/1341@java.io.Serial1342private Object writeReplace() {1343return new Ser(Ser.INSTANT_TYPE, this);1344}13451346/**1347* Defend against malicious streams.1348*1349* @param s the stream to read1350* @throws InvalidObjectException always1351*/1352@java.io.Serial1353private void readObject(ObjectInputStream s) throws InvalidObjectException {1354throw new InvalidObjectException("Deserialization via serialization delegate");1355}13561357void writeExternal(DataOutput out) throws IOException {1358out.writeLong(seconds);1359out.writeInt(nanos);1360}13611362static Instant readExternal(DataInput in) throws IOException {1363long seconds = in.readLong();1364int nanos = in.readInt();1365return Instant.ofEpochSecond(seconds, nanos);1366}13671368}136913701371