Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/time/Instant.java
38829 views
/*1* Copyright (c) 2012, 2015, 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* <h3>Time-scale</h3>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*194* <p>195* This is a <a href="{@docRoot}/java/lang/doc-files/ValueBased.html">value-based</a>196* class; use of identity-sensitive operations (including reference equality197* ({@code ==}), identity hash code, or synchronization) on instances of198* {@code Instant} may have unpredictable results and should be avoided.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*/206public final class Instant207implements Temporal, TemporalAdjuster, Comparable<Instant>, Serializable {208209/**210* Constant for the 1970-01-01T00:00:00Z epoch instant.211*/212public static final Instant EPOCH = new Instant(0, 0);213/**214* The minimum supported epoch second.215*/216private static final long MIN_SECOND = -31557014167219200L;217/**218* The maximum supported epoch second.219*/220private static final long MAX_SECOND = 31556889864403199L;221/**222* The minimum supported {@code Instant}, '-1000000000-01-01T00:00Z'.223* This could be used by an application as a "far past" instant.224* <p>225* This is one year earlier than the minimum {@code LocalDateTime}.226* This provides sufficient values to handle the range of {@code ZoneOffset}227* which affect the instant in addition to the local date-time.228* The value is also chosen such that the value of the year fits in229* an {@code int}.230*/231public static final Instant MIN = Instant.ofEpochSecond(MIN_SECOND, 0);232/**233* The maximum supported {@code Instant}, '1000000000-12-31T23:59:59.999999999Z'.234* This could be used by an application as a "far future" instant.235* <p>236* This is one year later than the maximum {@code LocalDateTime}.237* This provides sufficient values to handle the range of {@code ZoneOffset}238* which affect the instant in addition to the local date-time.239* The value is also chosen such that the value of the year fits in240* an {@code int}.241*/242public static final Instant MAX = Instant.ofEpochSecond(MAX_SECOND, 999_999_999);243244/**245* Serialization version.246*/247private static final long serialVersionUID = -665713676816604388L;248249/**250* The number of seconds from the epoch of 1970-01-01T00:00:00Z.251*/252private final long seconds;253/**254* The number of nanoseconds, later along the time-line, from the seconds field.255* This is always positive, and never exceeds 999,999,999.256*/257private final int nanos;258259//-----------------------------------------------------------------------260/**261* Obtains the current instant from the system clock.262* <p>263* This will query the {@link Clock#systemUTC() system UTC clock} to264* obtain the current instant.265* <p>266* Using this method will prevent the ability to use an alternate time-source for267* testing because the clock is effectively hard-coded.268*269* @return the current instant using the system clock, not null270*/271public static Instant now() {272return Clock.systemUTC().instant();273}274275/**276* Obtains the current instant from the specified clock.277* <p>278* This will query the specified clock to obtain the current time.279* <p>280* Using this method allows the use of an alternate clock for testing.281* The alternate clock may be introduced using {@link Clock dependency injection}.282*283* @param clock the clock to use, not null284* @return the current instant, not null285*/286public static Instant now(Clock clock) {287Objects.requireNonNull(clock, "clock");288return clock.instant();289}290291//-----------------------------------------------------------------------292/**293* Obtains an instance of {@code Instant} using seconds from the294* epoch of 1970-01-01T00:00:00Z.295* <p>296* The nanosecond field is set to zero.297*298* @param epochSecond the number of seconds from 1970-01-01T00:00:00Z299* @return an instant, not null300* @throws DateTimeException if the instant exceeds the maximum or minimum instant301*/302public static Instant ofEpochSecond(long epochSecond) {303return create(epochSecond, 0);304}305306/**307* Obtains an instance of {@code Instant} using seconds from the308* epoch of 1970-01-01T00:00:00Z and nanosecond fraction of second.309* <p>310* This method allows an arbitrary number of nanoseconds to be passed in.311* The factory will alter the values of the second and nanosecond in order312* to ensure that the stored nanosecond is in the range 0 to 999,999,999.313* For example, the following will result in the exactly the same instant:314* <pre>315* Instant.ofEpochSecond(3, 1);316* Instant.ofEpochSecond(4, -999_999_999);317* Instant.ofEpochSecond(2, 1000_000_001);318* </pre>319*320* @param epochSecond the number of seconds from 1970-01-01T00:00:00Z321* @param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative322* @return an instant, not null323* @throws DateTimeException if the instant exceeds the maximum or minimum instant324* @throws ArithmeticException if numeric overflow occurs325*/326public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment) {327long secs = Math.addExact(epochSecond, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND));328int nos = (int)Math.floorMod(nanoAdjustment, NANOS_PER_SECOND);329return create(secs, nos);330}331332/**333* Obtains an instance of {@code Instant} using milliseconds from the334* epoch of 1970-01-01T00:00:00Z.335* <p>336* The seconds and nanoseconds are extracted from the specified milliseconds.337*338* @param epochMilli the number of milliseconds from 1970-01-01T00:00:00Z339* @return an instant, not null340* @throws DateTimeException if the instant exceeds the maximum or minimum instant341*/342public static Instant ofEpochMilli(long epochMilli) {343long secs = Math.floorDiv(epochMilli, 1000);344int mos = (int)Math.floorMod(epochMilli, 1000);345return create(secs, mos * 1000_000);346}347348//-----------------------------------------------------------------------349/**350* Obtains an instance of {@code Instant} from a temporal object.351* <p>352* This obtains an instant based on the specified temporal.353* A {@code TemporalAccessor} represents an arbitrary set of date and time information,354* which this factory converts to an instance of {@code Instant}.355* <p>356* The conversion extracts the {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS}357* and {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} fields.358* <p>359* This method matches the signature of the functional interface {@link TemporalQuery}360* allowing it to be used as a query via method reference, {@code Instant::from}.361*362* @param temporal the temporal object to convert, not null363* @return the instant, not null364* @throws DateTimeException if unable to convert to an {@code Instant}365*/366public static Instant from(TemporalAccessor temporal) {367if (temporal instanceof Instant) {368return (Instant) temporal;369}370Objects.requireNonNull(temporal, "temporal");371try {372long instantSecs = temporal.getLong(INSTANT_SECONDS);373int nanoOfSecond = temporal.get(NANO_OF_SECOND);374return Instant.ofEpochSecond(instantSecs, nanoOfSecond);375} catch (DateTimeException ex) {376throw new DateTimeException("Unable to obtain Instant from TemporalAccessor: " +377temporal + " of type " + temporal.getClass().getName(), ex);378}379}380381//-----------------------------------------------------------------------382/**383* Obtains an instance of {@code Instant} from a text string such as384* {@code 2007-12-03T10:15:30.00Z}.385* <p>386* The string must represent a valid instant in UTC and is parsed using387* {@link DateTimeFormatter#ISO_INSTANT}.388*389* @param text the text to parse, not null390* @return the parsed instant, not null391* @throws DateTimeParseException if the text cannot be parsed392*/393public static Instant parse(final CharSequence text) {394return DateTimeFormatter.ISO_INSTANT.parse(text, Instant::from);395}396397//-----------------------------------------------------------------------398/**399* Obtains an instance of {@code Instant} using seconds and nanoseconds.400*401* @param seconds the length of the duration in seconds402* @param nanoOfSecond the nano-of-second, from 0 to 999,999,999403* @throws DateTimeException if the instant exceeds the maximum or minimum instant404*/405private static Instant create(long seconds, int nanoOfSecond) {406if ((seconds | nanoOfSecond) == 0) {407return EPOCH;408}409if (seconds < MIN_SECOND || seconds > MAX_SECOND) {410throw new DateTimeException("Instant exceeds minimum or maximum instant");411}412return new Instant(seconds, nanoOfSecond);413}414415/**416* Constructs an instance of {@code Instant} using seconds from the epoch of417* 1970-01-01T00:00:00Z and nanosecond fraction of second.418*419* @param epochSecond the number of seconds from 1970-01-01T00:00:00Z420* @param nanos the nanoseconds within the second, must be positive421*/422private Instant(long epochSecond, int nanos) {423super();424this.seconds = epochSecond;425this.nanos = nanos;426}427428//-----------------------------------------------------------------------429/**430* Checks if the specified field is supported.431* <p>432* This checks if this instant can be queried for the specified field.433* If false, then calling the {@link #range(TemporalField) range},434* {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}435* methods will throw an exception.436* <p>437* If the field is a {@link ChronoField} then the query is implemented here.438* The supported fields are:439* <ul>440* <li>{@code NANO_OF_SECOND}441* <li>{@code MICRO_OF_SECOND}442* <li>{@code MILLI_OF_SECOND}443* <li>{@code INSTANT_SECONDS}444* </ul>445* All other {@code ChronoField} instances will return false.446* <p>447* If the field is not a {@code ChronoField}, then the result of this method448* is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}449* passing {@code this} as the argument.450* Whether the field is supported is determined by the field.451*452* @param field the field to check, null returns false453* @return true if the field is supported on this instant, false if not454*/455@Override456public boolean isSupported(TemporalField field) {457if (field instanceof ChronoField) {458return field == INSTANT_SECONDS || field == NANO_OF_SECOND || field == MICRO_OF_SECOND || field == MILLI_OF_SECOND;459}460return field != null && field.isSupportedBy(this);461}462463/**464* Checks if the specified unit is supported.465* <p>466* This checks if the specified unit can be added to, or subtracted from, this date-time.467* If false, then calling the {@link #plus(long, TemporalUnit)} and468* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.469* <p>470* If the unit is a {@link ChronoUnit} then the query is implemented here.471* The supported units are:472* <ul>473* <li>{@code NANOS}474* <li>{@code MICROS}475* <li>{@code MILLIS}476* <li>{@code SECONDS}477* <li>{@code MINUTES}478* <li>{@code HOURS}479* <li>{@code HALF_DAYS}480* <li>{@code DAYS}481* </ul>482* All other {@code ChronoUnit} instances will return false.483* <p>484* If the unit is not a {@code ChronoUnit}, then the result of this method485* is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}486* passing {@code this} as the argument.487* Whether the unit is supported is determined by the unit.488*489* @param unit the unit to check, null returns false490* @return true if the unit can be added/subtracted, false if not491*/492@Override493public boolean isSupported(TemporalUnit unit) {494if (unit instanceof ChronoUnit) {495return unit.isTimeBased() || unit == DAYS;496}497return unit != null && unit.isSupportedBy(this);498}499500//-----------------------------------------------------------------------501/**502* Gets the range of valid values for the specified field.503* <p>504* The range object expresses the minimum and maximum valid values for a field.505* This instant is used to enhance the accuracy of the returned range.506* If it is not possible to return the range, because the field is not supported507* or for some other reason, an exception is thrown.508* <p>509* If the field is a {@link ChronoField} then the query is implemented here.510* The {@link #isSupported(TemporalField) supported fields} will return511* appropriate range instances.512* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.513* <p>514* If the field is not a {@code ChronoField}, then the result of this method515* is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}516* passing {@code this} as the argument.517* Whether the range can be obtained is determined by the field.518*519* @param field the field to query the range for, not null520* @return the range of valid values for the field, not null521* @throws DateTimeException if the range for the field cannot be obtained522* @throws UnsupportedTemporalTypeException if the field is not supported523*/524@Override // override for Javadoc525public ValueRange range(TemporalField field) {526return Temporal.super.range(field);527}528529/**530* Gets the value of the specified field from this instant as an {@code int}.531* <p>532* This queries this instant for the value of the specified field.533* The returned value will always be within the valid range of values for the field.534* If it is not possible to return the value, because the field is not supported535* or for some other reason, an exception is thrown.536* <p>537* If the field is a {@link ChronoField} then the query is implemented here.538* The {@link #isSupported(TemporalField) supported fields} will return valid539* values based on this date-time, except {@code INSTANT_SECONDS} which is too540* large to fit in an {@code int} and throws a {@code DateTimeException}.541* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.542* <p>543* If the field is not a {@code ChronoField}, then the result of this method544* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}545* passing {@code this} as the argument. Whether the value can be obtained,546* and what the value represents, is determined by the field.547*548* @param field the field to get, not null549* @return the value for the field550* @throws DateTimeException if a value for the field cannot be obtained or551* the value is outside the range of valid values for the field552* @throws UnsupportedTemporalTypeException if the field is not supported or553* the range of values exceeds an {@code int}554* @throws ArithmeticException if numeric overflow occurs555*/556@Override // override for Javadoc and performance557public int get(TemporalField field) {558if (field instanceof ChronoField) {559switch ((ChronoField) field) {560case NANO_OF_SECOND: return nanos;561case MICRO_OF_SECOND: return nanos / 1000;562case MILLI_OF_SECOND: return nanos / 1000_000;563case INSTANT_SECONDS: INSTANT_SECONDS.checkValidIntValue(seconds);564}565throw new UnsupportedTemporalTypeException("Unsupported field: " + field);566}567return range(field).checkValidIntValue(field.getFrom(this), field);568}569570/**571* Gets the value of the specified field from this instant as a {@code long}.572* <p>573* This queries this instant for the value of the specified field.574* If it is not possible to return the value, because the field is not supported575* or for some other reason, an exception is thrown.576* <p>577* If the field is a {@link ChronoField} then the query is implemented here.578* The {@link #isSupported(TemporalField) supported fields} will return valid579* values based on this date-time.580* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.581* <p>582* If the field is not a {@code ChronoField}, then the result of this method583* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}584* passing {@code this} as the argument. Whether the value can be obtained,585* and what the value represents, is determined by the field.586*587* @param field the field to get, not null588* @return the value for the field589* @throws DateTimeException if a value for the field cannot be obtained590* @throws UnsupportedTemporalTypeException if the field is not supported591* @throws ArithmeticException if numeric overflow occurs592*/593@Override594public long getLong(TemporalField field) {595if (field instanceof ChronoField) {596switch ((ChronoField) field) {597case NANO_OF_SECOND: return nanos;598case MICRO_OF_SECOND: return nanos / 1000;599case MILLI_OF_SECOND: return nanos / 1000_000;600case INSTANT_SECONDS: return seconds;601}602throw new UnsupportedTemporalTypeException("Unsupported field: " + field);603}604return field.getFrom(this);605}606607//-----------------------------------------------------------------------608/**609* Gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z.610* <p>611* The epoch second count is a simple incrementing count of seconds where612* second 0 is 1970-01-01T00:00:00Z.613* The nanosecond part of the day is returned by {@code getNanosOfSecond}.614*615* @return the seconds from the epoch of 1970-01-01T00:00:00Z616*/617public long getEpochSecond() {618return seconds;619}620621/**622* Gets the number of nanoseconds, later along the time-line, from the start623* of the second.624* <p>625* The nanosecond-of-second value measures the total number of nanoseconds from626* the second returned by {@code getEpochSecond}.627*628* @return the nanoseconds within the second, always positive, never exceeds 999,999,999629*/630public int getNano() {631return nanos;632}633634//-------------------------------------------------------------------------635/**636* Returns an adjusted copy of this instant.637* <p>638* This returns an {@code Instant}, based on this one, with the instant adjusted.639* The adjustment takes place using the specified adjuster strategy object.640* Read the documentation of the adjuster to understand what adjustment will be made.641* <p>642* The result of this method is obtained by invoking the643* {@link TemporalAdjuster#adjustInto(Temporal)} method on the644* specified adjuster passing {@code this} as the argument.645* <p>646* This instance is immutable and unaffected by this method call.647*648* @param adjuster the adjuster to use, not null649* @return an {@code Instant} based on {@code this} with the adjustment made, not null650* @throws DateTimeException if the adjustment cannot be made651* @throws ArithmeticException if numeric overflow occurs652*/653@Override654public Instant with(TemporalAdjuster adjuster) {655return (Instant) adjuster.adjustInto(this);656}657658/**659* Returns a copy of this instant with the specified field set to a new value.660* <p>661* This returns an {@code Instant}, based on this one, with the value662* for the specified field changed.663* If it is not possible to set the value, because the field is not supported or for664* some other reason, an exception is thrown.665* <p>666* If the field is a {@link ChronoField} then the adjustment is implemented here.667* The supported fields behave as follows:668* <ul>669* <li>{@code NANO_OF_SECOND} -670* Returns an {@code Instant} with the specified nano-of-second.671* The epoch-second will be unchanged.672* <li>{@code MICRO_OF_SECOND} -673* Returns an {@code Instant} with the nano-of-second replaced by the specified674* micro-of-second multiplied by 1,000. The epoch-second will be unchanged.675* <li>{@code MILLI_OF_SECOND} -676* Returns an {@code Instant} with the nano-of-second replaced by the specified677* milli-of-second multiplied by 1,000,000. The epoch-second will be unchanged.678* <li>{@code INSTANT_SECONDS} -679* Returns an {@code Instant} with the specified epoch-second.680* The nano-of-second will be unchanged.681* </ul>682* <p>683* In all cases, if the new value is outside the valid range of values for the field684* then a {@code DateTimeException} will be thrown.685* <p>686* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.687* <p>688* If the field is not a {@code ChronoField}, then the result of this method689* is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}690* passing {@code this} as the argument. In this case, the field determines691* whether and how to adjust the instant.692* <p>693* This instance is immutable and unaffected by this method call.694*695* @param field the field to set in the result, not null696* @param newValue the new value of the field in the result697* @return an {@code Instant} based on {@code this} with the specified field set, not null698* @throws DateTimeException if the field cannot be set699* @throws UnsupportedTemporalTypeException if the field is not supported700* @throws ArithmeticException if numeric overflow occurs701*/702@Override703public Instant with(TemporalField field, long newValue) {704if (field instanceof ChronoField) {705ChronoField f = (ChronoField) field;706f.checkValidValue(newValue);707switch (f) {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 = (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 a {@code Instant} with the specified number of nanoseconds added.802* This is equivalent to {@link #plusNanos(long)}.803* <li>{@code MICROS} -804* Returns a {@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 a {@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 a {@code Instant} with the specified number of seconds added.813* This is equivalent to {@link #plusSeconds(long)}.814* <li>{@code MINUTES} -815* Returns a {@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 a {@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 a {@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 a {@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 a {@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 days 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) {1145ChronoUnit f = (ChronoUnit) unit;1146switch (f) {1147case NANOS: return nanosUntil(end);1148case MICROS: return nanosUntil(end) / 1000;1149case MILLIS: return Math.subtractExact(end.toEpochMilli(), toEpochMilli());1150case SECONDS: return secondsUntil(end);1151case MINUTES: return secondsUntil(end) / SECONDS_PER_MINUTE;1152case HOURS: return secondsUntil(end) / SECONDS_PER_HOUR;1153case HALF_DAYS: return secondsUntil(end) / (12 * SECONDS_PER_HOUR);1154case DAYS: return secondsUntil(end) / (SECONDS_PER_DAY);1155}1156throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);1157}1158return unit.between(this, end);1159}11601161private long nanosUntil(Instant end) {1162long secsDiff = Math.subtractExact(end.seconds, seconds);1163long totalNanos = Math.multiplyExact(secsDiff, NANOS_PER_SECOND);1164return Math.addExact(totalNanos, end.nanos - nanos);1165}11661167private long secondsUntil(Instant end) {1168long secsDiff = Math.subtractExact(end.seconds, seconds);1169long nanosDiff = end.nanos - nanos;1170if (secsDiff > 0 && nanosDiff < 0) {1171secsDiff--;1172} else if (secsDiff < 0 && nanosDiff > 0) {1173secsDiff++;1174}1175return secsDiff;1176}11771178//-----------------------------------------------------------------------1179/**1180* Combines this instant with an offset to create an {@code OffsetDateTime}.1181* <p>1182* This returns an {@code OffsetDateTime} formed from this instant at the1183* specified offset from UTC/Greenwich. An exception will be thrown if the1184* instant is too large to fit into an offset date-time.1185* <p>1186* This method is equivalent to1187* {@link OffsetDateTime#ofInstant(Instant, ZoneId) OffsetDateTime.ofInstant(this, offset)}.1188*1189* @param offset the offset to combine with, not null1190* @return the offset date-time formed from this instant and the specified offset, not null1191* @throws DateTimeException if the result exceeds the supported range1192*/1193public OffsetDateTime atOffset(ZoneOffset offset) {1194return OffsetDateTime.ofInstant(this, offset);1195}11961197/**1198* Combines this instant with a time-zone to create a {@code ZonedDateTime}.1199* <p>1200* This returns an {@code ZonedDateTime} formed from this instant at the1201* specified time-zone. An exception will be thrown if the instant is too1202* large to fit into a zoned date-time.1203* <p>1204* This method is equivalent to1205* {@link ZonedDateTime#ofInstant(Instant, ZoneId) ZonedDateTime.ofInstant(this, zone)}.1206*1207* @param zone the zone to combine with, not null1208* @return the zoned date-time formed from this instant and the specified zone, not null1209* @throws DateTimeException if the result exceeds the supported range1210*/1211public ZonedDateTime atZone(ZoneId zone) {1212return ZonedDateTime.ofInstant(this, zone);1213}12141215//-----------------------------------------------------------------------1216/**1217* Converts this instant to the number of milliseconds from the epoch1218* of 1970-01-01T00:00:00Z.1219* <p>1220* If this instant represents a point on the time-line too far in the future1221* or past to fit in a {@code long} milliseconds, then an exception is thrown.1222* <p>1223* If this instant has greater than millisecond precision, then the conversion1224* will drop any excess precision information as though the amount in nanoseconds1225* was subject to integer division by one million.1226*1227* @return the number of milliseconds since the epoch of 1970-01-01T00:00:00Z1228* @throws ArithmeticException if numeric overflow occurs1229*/1230public long toEpochMilli() {1231if (seconds < 0 && nanos > 0) {1232long millis = Math.multiplyExact(seconds+1, 1000);1233long adjustment = nanos / 1000_000 - 1000;1234return Math.addExact(millis, adjustment);1235} else {1236long millis = Math.multiplyExact(seconds, 1000);1237return Math.addExact(millis, nanos / 1000_000);1238}1239}12401241//-----------------------------------------------------------------------1242/**1243* Compares this instant to the specified instant.1244* <p>1245* The comparison is based on the time-line position of the instants.1246* It is "consistent with equals", as defined by {@link Comparable}.1247*1248* @param otherInstant the other instant to compare to, not null1249* @return the comparator value, negative if less, positive if greater1250* @throws NullPointerException if otherInstant is null1251*/1252@Override1253public int compareTo(Instant otherInstant) {1254int cmp = Long.compare(seconds, otherInstant.seconds);1255if (cmp != 0) {1256return cmp;1257}1258return nanos - otherInstant.nanos;1259}12601261/**1262* Checks if this instant is after the specified instant.1263* <p>1264* The comparison is based on the time-line position of the instants.1265*1266* @param otherInstant the other instant to compare to, not null1267* @return true if this instant is after the specified instant1268* @throws NullPointerException if otherInstant is null1269*/1270public boolean isAfter(Instant otherInstant) {1271return compareTo(otherInstant) > 0;1272}12731274/**1275* Checks if this instant is before the specified instant.1276* <p>1277* The comparison is based on the time-line position of the instants.1278*1279* @param otherInstant the other instant to compare to, not null1280* @return true if this instant is before the specified instant1281* @throws NullPointerException if otherInstant is null1282*/1283public boolean isBefore(Instant otherInstant) {1284return compareTo(otherInstant) < 0;1285}12861287//-----------------------------------------------------------------------1288/**1289* Checks if this instant is equal to the specified instant.1290* <p>1291* The comparison is based on the time-line position of the instants.1292*1293* @param otherInstant the other instant, null returns false1294* @return true if the other instant is equal to this one1295*/1296@Override1297public boolean equals(Object otherInstant) {1298if (this == otherInstant) {1299return true;1300}1301if (otherInstant instanceof Instant) {1302Instant other = (Instant) otherInstant;1303return this.seconds == other.seconds &&1304this.nanos == other.nanos;1305}1306return false;1307}13081309/**1310* Returns a hash code for this instant.1311*1312* @return a suitable hash code1313*/1314@Override1315public int hashCode() {1316return ((int) (seconds ^ (seconds >>> 32))) + 51 * nanos;1317}13181319//-----------------------------------------------------------------------1320/**1321* A string representation of this instant using ISO-8601 representation.1322* <p>1323* The format used is the same as {@link DateTimeFormatter#ISO_INSTANT}.1324*1325* @return an ISO-8601 representation of this instant, not null1326*/1327@Override1328public String toString() {1329return DateTimeFormatter.ISO_INSTANT.format(this);1330}13311332// -----------------------------------------------------------------------1333/**1334* Writes the object using a1335* <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>.1336* @serialData1337* <pre>1338* out.writeByte(2); // identifies an Instant1339* out.writeLong(seconds);1340* out.writeInt(nanos);1341* </pre>1342*1343* @return the instance of {@code Ser}, not null1344*/1345private Object writeReplace() {1346return new Ser(Ser.INSTANT_TYPE, this);1347}13481349/**1350* Defend against malicious streams.1351*1352* @param s the stream to read1353* @throws InvalidObjectException always1354*/1355private void readObject(ObjectInputStream s) throws InvalidObjectException {1356throw new InvalidObjectException("Deserialization via serialization delegate");1357}13581359void writeExternal(DataOutput out) throws IOException {1360out.writeLong(seconds);1361out.writeInt(nanos);1362}13631364static Instant readExternal(DataInput in) throws IOException {1365long seconds = in.readLong();1366int nanos = in.readInt();1367return Instant.ofEpochSecond(seconds, nanos);1368}13691370}137113721373