1 /*
2  * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 /*
27  * This file is available under and governed by the GNU General Public
28  * License version 2 only, as published by the Free Software Foundation.
29  * However, the following notice accompanied the original version of this
30  * file:
31  *
32  * Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos
33  *
34  * All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions are met:
38  *
39  *  * Redistributions of source code must retain the above copyright notice,
40  *    this list of conditions and the following disclaimer.
41  *
42  *  * Redistributions in binary form must reproduce the above copyright notice,
43  *    this list of conditions and the following disclaimer in the documentation
44  *    and/or other materials provided with the distribution.
45  *
46  *  * Neither the name of JSR-310 nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
61  */
62 package java.time;
63 
64 import static java.time.LocalTime.NANOS_PER_SECOND;
65 import static java.time.LocalTime.SECONDS_PER_DAY;
66 import static java.time.LocalTime.SECONDS_PER_HOUR;
67 import static java.time.LocalTime.SECONDS_PER_MINUTE;
68 import static java.time.temporal.ChronoField.INSTANT_SECONDS;
69 import static java.time.temporal.ChronoField.MICRO_OF_SECOND;
70 import static java.time.temporal.ChronoField.MILLI_OF_SECOND;
71 import static java.time.temporal.ChronoField.NANO_OF_SECOND;
72 import static java.time.temporal.ChronoUnit.DAYS;
73 import static java.time.temporal.ChronoUnit.NANOS;
74 
75 import java.io.DataInput;
76 import java.io.DataOutput;
77 import java.io.IOException;
78 import java.io.InvalidObjectException;
79 import java.io.ObjectInputStream;
80 import java.io.Serializable;
81 import java.time.format.DateTimeFormatter;
82 import java.time.format.DateTimeParseException;
83 import java.time.temporal.ChronoField;
84 import java.time.temporal.ChronoUnit;
85 import java.time.temporal.Temporal;
86 import java.time.temporal.TemporalAccessor;
87 import java.time.temporal.TemporalAdjuster;
88 import java.time.temporal.TemporalAmount;
89 import java.time.temporal.TemporalField;
90 import java.time.temporal.TemporalQueries;
91 import java.time.temporal.TemporalQuery;
92 import java.time.temporal.TemporalUnit;
93 import java.time.temporal.UnsupportedTemporalTypeException;
94 import java.time.temporal.ValueRange;
95 import java.util.Objects;
96 
97 // Android-changed: removed ValueBased paragraph.
98 /**
99  * An instantaneous point on the time-line.
100  * <p>
101  * This class models a single instantaneous point on the time-line.
102  * This might be used to record event time-stamps in the application.
103  * <p>
104  * The range of an instant requires the storage of a number larger than a {@code long}.
105  * To achieve this, the class stores a {@code long} representing epoch-seconds and an
106  * {@code int} representing nanosecond-of-second, which will always be between 0 and 999,999,999.
107  * The epoch-seconds are measured from the standard Java epoch of {@code 1970-01-01T00:00:00Z}
108  * where instants after the epoch have positive values, and earlier instants have negative values.
109  * For both the epoch-second and nanosecond parts, a larger value is always later on the time-line
110  * than a smaller value.
111  *
112  * <h2>Time-scale</h2>
113  * <p>
114  * The length of the solar day is the standard way that humans measure time.
115  * This has traditionally been subdivided into 24 hours of 60 minutes of 60 seconds,
116  * forming a 86400 second day.
117  * <p>
118  * Modern timekeeping is based on atomic clocks which precisely define an SI second
119  * relative to the transitions of a Caesium atom. The length of an SI second was defined
120  * to be very close to the 86400th fraction of a day.
121  * <p>
122  * Unfortunately, as the Earth rotates the length of the day varies.
123  * In addition, over time the average length of the day is getting longer as the Earth slows.
124  * As a result, the length of a solar day in 2012 is slightly longer than 86400 SI seconds.
125  * The actual length of any given day and the amount by which the Earth is slowing
126  * are not predictable and can only be determined by measurement.
127  * The UT1 time-scale captures the accurate length of day, but is only available some
128  * time after the day has completed.
129  * <p>
130  * The UTC time-scale is a standard approach to bundle up all the additional fractions
131  * of a second from UT1 into whole seconds, known as <i>leap-seconds</i>.
132  * A leap-second may be added or removed depending on the Earth's rotational changes.
133  * As such, UTC permits a day to have 86399 SI seconds or 86401 SI seconds where
134  * necessary in order to keep the day aligned with the Sun.
135  * <p>
136  * The modern UTC time-scale was introduced in 1972, introducing the concept of whole leap-seconds.
137  * Between 1958 and 1972, the definition of UTC was complex, with minor sub-second leaps and
138  * alterations to the length of the notional second. As of 2012, discussions are underway
139  * to change the definition of UTC again, with the potential to remove leap seconds or
140  * introduce other changes.
141  * <p>
142  * Given the complexity of accurate timekeeping described above, this Java API defines
143  * its own time-scale, the <i>Java Time-Scale</i>.
144  * <p>
145  * The Java Time-Scale divides each calendar day into exactly 86400
146  * subdivisions, known as seconds.  These seconds may differ from the
147  * SI second.  It closely matches the de facto international civil time
148  * scale, the definition of which changes from time to time.
149  * <p>
150  * The Java Time-Scale has slightly different definitions for different
151  * segments of the time-line, each based on the consensus international
152  * time scale that is used as the basis for civil time. Whenever the
153  * internationally-agreed time scale is modified or replaced, a new
154  * segment of the Java Time-Scale must be defined for it.  Each segment
155  * must meet these requirements:
156  * <ul>
157  * <li>the Java Time-Scale shall closely match the underlying international
158  *  civil time scale;</li>
159  * <li>the Java Time-Scale shall exactly match the international civil
160  *  time scale at noon each day;</li>
161  * <li>the Java Time-Scale shall have a precisely-defined relationship to
162  *  the international civil time scale.</li>
163  * </ul>
164  * There are currently, as of 2013, two segments in the Java time-scale.
165  * <p>
166  * For the segment from 1972-11-03 (exact boundary discussed below) until
167  * further notice, the consensus international time scale is UTC (with
168  * leap seconds).  In this segment, the Java Time-Scale is identical to
169  * <a href="http://www.cl.cam.ac.uk/~mgk25/time/utc-sls/">UTC-SLS</a>.
170  * This is identical to UTC on days that do not have a leap second.
171  * On days that do have a leap second, the leap second is spread equally
172  * over the last 1000 seconds of the day, maintaining the appearance of
173  * exactly 86400 seconds per day.
174  * <p>
175  * For the segment prior to 1972-11-03, extending back arbitrarily far,
176  * the consensus international time scale is defined to be UT1, applied
177  * proleptically, which is equivalent to the (mean) solar time on the
178  * prime meridian (Greenwich). In this segment, the Java Time-Scale is
179  * identical to the consensus international time scale. The exact
180  * boundary between the two segments is the instant where UT1 = UTC
181  * between 1972-11-03T00:00 and 1972-11-04T12:00.
182  * <p>
183  * Implementations of the Java time-scale using the JSR-310 API are not
184  * required to provide any clock that is sub-second accurate, or that
185  * progresses monotonically or smoothly. Implementations are therefore
186  * not required to actually perform the UTC-SLS slew or to otherwise be
187  * aware of leap seconds. JSR-310 does, however, require that
188  * implementations must document the approach they use when defining a
189  * clock representing the current instant.
190  * See {@link Clock} for details on the available clocks.
191  * <p>
192  * The Java time-scale is used for all date-time classes.
193  * This includes {@code Instant}, {@code LocalDate}, {@code LocalTime}, {@code OffsetDateTime},
194  * {@code ZonedDateTime} and {@code Duration}.
195  *
196  * @implSpec
197  * This class is immutable and thread-safe.
198  *
199  * @since 1.8
200  */
201 public final class Instant
202         implements Temporal, TemporalAdjuster, Comparable<Instant>, Serializable {
203 
204     /**
205      * Constant for the 1970-01-01T00:00:00Z epoch instant.
206      */
207     public static final Instant EPOCH = new Instant(0, 0);
208     /**
209      * The minimum supported epoch second.
210      */
211     private static final long MIN_SECOND = -31557014167219200L;
212     /**
213      * The maximum supported epoch second.
214      */
215     private static final long MAX_SECOND = 31556889864403199L;
216     /**
217      * The minimum supported {@code Instant}, '-1000000000-01-01T00:00Z'.
218      * This could be used by an application as a "far past" instant.
219      * <p>
220      * This is one year earlier than the minimum {@code LocalDateTime}.
221      * This provides sufficient values to handle the range of {@code ZoneOffset}
222      * which affect the instant in addition to the local date-time.
223      * The value is also chosen such that the value of the year fits in
224      * an {@code int}.
225      */
226     public static final Instant MIN = Instant.ofEpochSecond(MIN_SECOND, 0);
227     /**
228      * The maximum supported {@code Instant}, '1000000000-12-31T23:59:59.999999999Z'.
229      * This could be used by an application as a "far future" instant.
230      * <p>
231      * This is one year later than the maximum {@code LocalDateTime}.
232      * This provides sufficient values to handle the range of {@code ZoneOffset}
233      * which affect the instant in addition to the local date-time.
234      * The value is also chosen such that the value of the year fits in
235      * an {@code int}.
236      */
237     public static final Instant MAX = Instant.ofEpochSecond(MAX_SECOND, 999_999_999);
238 
239     /**
240      * Serialization version.
241      */
242     @java.io.Serial
243     private static final long serialVersionUID = -665713676816604388L;
244 
245     /**
246      * The number of seconds from the epoch of 1970-01-01T00:00:00Z.
247      */
248     private final long seconds;
249     /**
250      * The number of nanoseconds, later along the time-line, from the seconds field.
251      * This is always positive, and never exceeds 999,999,999.
252      */
253     private final int nanos;
254 
255     //-----------------------------------------------------------------------
256     /**
257      * Obtains the current instant from the system clock.
258      * <p>
259      * This will query the {@link Clock#systemUTC() system UTC clock} to
260      * obtain the current instant.
261      * <p>
262      * Using this method will prevent the ability to use an alternate time-source for
263      * testing because the clock is effectively hard-coded.
264      *
265      * @return the current instant using the system clock, not null
266      */
now()267     public static Instant now() {
268         return Clock.currentInstant();
269     }
270 
271     /**
272      * Obtains the current instant from the specified clock.
273      * <p>
274      * This will query the specified clock to obtain the current time.
275      * <p>
276      * Using this method allows the use of an alternate clock for testing.
277      * The alternate clock may be introduced using {@link Clock dependency injection}.
278      *
279      * @param clock  the clock to use, not null
280      * @return the current instant, not null
281      */
now(Clock clock)282     public static Instant now(Clock clock) {
283         Objects.requireNonNull(clock, "clock");
284         return clock.instant();
285     }
286 
287     //-----------------------------------------------------------------------
288     /**
289      * Obtains an instance of {@code Instant} using seconds from the
290      * epoch of 1970-01-01T00:00:00Z.
291      * <p>
292      * The nanosecond field is set to zero.
293      *
294      * @param epochSecond  the number of seconds from 1970-01-01T00:00:00Z
295      * @return an instant, not null
296      * @throws DateTimeException if the instant exceeds the maximum or minimum instant
297      */
ofEpochSecond(long epochSecond)298     public static Instant ofEpochSecond(long epochSecond) {
299         return create(epochSecond, 0);
300     }
301 
302     /**
303      * Obtains an instance of {@code Instant} using seconds from the
304      * epoch of 1970-01-01T00:00:00Z and nanosecond fraction of second.
305      * <p>
306      * This method allows an arbitrary number of nanoseconds to be passed in.
307      * The factory will alter the values of the second and nanosecond in order
308      * to ensure that the stored nanosecond is in the range 0 to 999,999,999.
309      * For example, the following will result in exactly the same instant:
310      * <pre>
311      *  Instant.ofEpochSecond(3, 1);
312      *  Instant.ofEpochSecond(4, -999_999_999);
313      *  Instant.ofEpochSecond(2, 1000_000_001);
314      * </pre>
315      *
316      * @param epochSecond  the number of seconds from 1970-01-01T00:00:00Z
317      * @param nanoAdjustment  the nanosecond adjustment to the number of seconds, positive or negative
318      * @return an instant, not null
319      * @throws DateTimeException if the instant exceeds the maximum or minimum instant
320      * @throws ArithmeticException if numeric overflow occurs
321      */
ofEpochSecond(long epochSecond, long nanoAdjustment)322     public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment) {
323         long secs = Math.addExact(epochSecond, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND));
324         int nos = (int)Math.floorMod(nanoAdjustment, NANOS_PER_SECOND);
325         return create(secs, nos);
326     }
327 
328     /**
329      * Obtains an instance of {@code Instant} using milliseconds from the
330      * epoch of 1970-01-01T00:00:00Z.
331      * <p>
332      * The seconds and nanoseconds are extracted from the specified milliseconds.
333      *
334      * @param epochMilli  the number of milliseconds from 1970-01-01T00:00:00Z
335      * @return an instant, not null
336      * @throws DateTimeException if the instant exceeds the maximum or minimum instant
337      */
ofEpochMilli(long epochMilli)338     public static Instant ofEpochMilli(long epochMilli) {
339         long secs = Math.floorDiv(epochMilli, 1000);
340         int mos = Math.floorMod(epochMilli, 1000);
341         return create(secs, mos * 1000_000);
342     }
343 
344     //-----------------------------------------------------------------------
345     /**
346      * Obtains an instance of {@code Instant} from a temporal object.
347      * <p>
348      * This obtains an instant based on the specified temporal.
349      * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
350      * which this factory converts to an instance of {@code Instant}.
351      * <p>
352      * The conversion extracts the {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS}
353      * and {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} fields.
354      * <p>
355      * This method matches the signature of the functional interface {@link TemporalQuery}
356      * allowing it to be used as a query via method reference, {@code Instant::from}.
357      *
358      * @param temporal  the temporal object to convert, not null
359      * @return the instant, not null
360      * @throws DateTimeException if unable to convert to an {@code Instant}
361      */
from(TemporalAccessor temporal)362     public static Instant from(TemporalAccessor temporal) {
363         if (temporal instanceof Instant) {
364             return (Instant) temporal;
365         }
366         Objects.requireNonNull(temporal, "temporal");
367         try {
368             long instantSecs = temporal.getLong(INSTANT_SECONDS);
369             int nanoOfSecond = temporal.get(NANO_OF_SECOND);
370             return Instant.ofEpochSecond(instantSecs, nanoOfSecond);
371         } catch (DateTimeException ex) {
372             throw new DateTimeException("Unable to obtain Instant from TemporalAccessor: " +
373                     temporal + " of type " + temporal.getClass().getName(), ex);
374         }
375     }
376 
377     //-----------------------------------------------------------------------
378     /**
379      * Obtains an instance of {@code Instant} from a text string such as
380      * {@code 2007-12-03T10:15:30.00Z}.
381      * <p>
382      * The string must represent a valid instant in UTC and is parsed using
383      * {@link DateTimeFormatter#ISO_INSTANT}.
384      *
385      * @param text  the text to parse, not null
386      * @return the parsed instant, not null
387      * @throws DateTimeParseException if the text cannot be parsed
388      */
parse(final CharSequence text)389     public static Instant parse(final CharSequence text) {
390         return DateTimeFormatter.ISO_INSTANT.parse(text, Instant::from);
391     }
392 
393     //-----------------------------------------------------------------------
394     /**
395      * Obtains an instance of {@code Instant} using seconds and nanoseconds.
396      *
397      * @param seconds  the length of the duration in seconds
398      * @param nanoOfSecond  the nano-of-second, from 0 to 999,999,999
399      * @throws DateTimeException if the instant exceeds the maximum or minimum instant
400      */
create(long seconds, int nanoOfSecond)401     private static Instant create(long seconds, int nanoOfSecond) {
402         if ((seconds | nanoOfSecond) == 0) {
403             return EPOCH;
404         }
405         if (seconds < MIN_SECOND || seconds > MAX_SECOND) {
406             throw new DateTimeException("Instant exceeds minimum or maximum instant");
407         }
408         return new Instant(seconds, nanoOfSecond);
409     }
410 
411     /**
412      * Constructs an instance of {@code Instant} using seconds from the epoch of
413      * 1970-01-01T00:00:00Z and nanosecond fraction of second.
414      *
415      * @param epochSecond  the number of seconds from 1970-01-01T00:00:00Z
416      * @param nanos  the nanoseconds within the second, must be positive
417      */
Instant(long epochSecond, int nanos)418     private Instant(long epochSecond, int nanos) {
419         super();
420         this.seconds = epochSecond;
421         this.nanos = nanos;
422     }
423 
424     //-----------------------------------------------------------------------
425     /**
426      * Checks if the specified field is supported.
427      * <p>
428      * This checks if this instant can be queried for the specified field.
429      * If false, then calling the {@link #range(TemporalField) range},
430      * {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}
431      * methods will throw an exception.
432      * <p>
433      * If the field is a {@link ChronoField} then the query is implemented here.
434      * The supported fields are:
435      * <ul>
436      * <li>{@code NANO_OF_SECOND}
437      * <li>{@code MICRO_OF_SECOND}
438      * <li>{@code MILLI_OF_SECOND}
439      * <li>{@code INSTANT_SECONDS}
440      * </ul>
441      * All other {@code ChronoField} instances will return false.
442      * <p>
443      * If the field is not a {@code ChronoField}, then the result of this method
444      * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
445      * passing {@code this} as the argument.
446      * Whether the field is supported is determined by the field.
447      *
448      * @param field  the field to check, null returns false
449      * @return true if the field is supported on this instant, false if not
450      */
451     @Override
isSupported(TemporalField field)452     public boolean isSupported(TemporalField field) {
453         if (field instanceof ChronoField) {
454             return field == INSTANT_SECONDS || field == NANO_OF_SECOND || field == MICRO_OF_SECOND || field == MILLI_OF_SECOND;
455         }
456         return field != null && field.isSupportedBy(this);
457     }
458 
459     /**
460      * Checks if the specified unit is supported.
461      * <p>
462      * This checks if the specified unit can be added to, or subtracted from, this date-time.
463      * If false, then calling the {@link #plus(long, TemporalUnit)} and
464      * {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
465      * <p>
466      * If the unit is a {@link ChronoUnit} then the query is implemented here.
467      * The supported units are:
468      * <ul>
469      * <li>{@code NANOS}
470      * <li>{@code MICROS}
471      * <li>{@code MILLIS}
472      * <li>{@code SECONDS}
473      * <li>{@code MINUTES}
474      * <li>{@code HOURS}
475      * <li>{@code HALF_DAYS}
476      * <li>{@code DAYS}
477      * </ul>
478      * All other {@code ChronoUnit} instances will return false.
479      * <p>
480      * If the unit is not a {@code ChronoUnit}, then the result of this method
481      * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}
482      * passing {@code this} as the argument.
483      * Whether the unit is supported is determined by the unit.
484      *
485      * @param unit  the unit to check, null returns false
486      * @return true if the unit can be added/subtracted, false if not
487      */
488     @Override
isSupported(TemporalUnit unit)489     public boolean isSupported(TemporalUnit unit) {
490         if (unit instanceof ChronoUnit) {
491             return unit.isTimeBased() || unit == DAYS;
492         }
493         return unit != null && unit.isSupportedBy(this);
494     }
495 
496     //-----------------------------------------------------------------------
497     /**
498      * Gets the range of valid values for the specified field.
499      * <p>
500      * The range object expresses the minimum and maximum valid values for a field.
501      * This instant is used to enhance the accuracy of the returned range.
502      * If it is not possible to return the range, because the field is not supported
503      * or for some other reason, an exception is thrown.
504      * <p>
505      * If the field is a {@link ChronoField} then the query is implemented here.
506      * The {@link #isSupported(TemporalField) supported fields} will return
507      * appropriate range instances.
508      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
509      * <p>
510      * If the field is not a {@code ChronoField}, then the result of this method
511      * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
512      * passing {@code this} as the argument.
513      * Whether the range can be obtained is determined by the field.
514      *
515      * @param field  the field to query the range for, not null
516      * @return the range of valid values for the field, not null
517      * @throws DateTimeException if the range for the field cannot be obtained
518      * @throws UnsupportedTemporalTypeException if the field is not supported
519      */
520     @Override  // override for Javadoc
range(TemporalField field)521     public ValueRange range(TemporalField field) {
522         return Temporal.super.range(field);
523     }
524 
525     /**
526      * Gets the value of the specified field from this instant as an {@code int}.
527      * <p>
528      * This queries this instant for the value of the specified field.
529      * The returned value will always be within the valid range of values for the field.
530      * If it is not possible to return the value, because the field is not supported
531      * or for some other reason, an exception is thrown.
532      * <p>
533      * If the field is a {@link ChronoField} then the query is implemented here.
534      * The {@link #isSupported(TemporalField) supported fields} will return valid
535      * values based on this date-time, except {@code INSTANT_SECONDS} which is too
536      * large to fit in an {@code int} and throws a {@code DateTimeException}.
537      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
538      * <p>
539      * If the field is not a {@code ChronoField}, then the result of this method
540      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
541      * passing {@code this} as the argument. Whether the value can be obtained,
542      * and what the value represents, is determined by the field.
543      *
544      * @param field  the field to get, not null
545      * @return the value for the field
546      * @throws DateTimeException if a value for the field cannot be obtained or
547      *         the value is outside the range of valid values for the field
548      * @throws UnsupportedTemporalTypeException if the field is not supported or
549      *         the range of values exceeds an {@code int}
550      * @throws ArithmeticException if numeric overflow occurs
551      */
552     @Override  // override for Javadoc and performance
get(TemporalField field)553     public int get(TemporalField field) {
554         if (field instanceof ChronoField) {
555             switch ((ChronoField) field) {
556                 case NANO_OF_SECOND: return nanos;
557                 case MICRO_OF_SECOND: return nanos / 1000;
558                 case MILLI_OF_SECOND: return nanos / 1000_000;
559             }
560             throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
561         }
562         return range(field).checkValidIntValue(field.getFrom(this), field);
563     }
564 
565     /**
566      * Gets the value of the specified field from this instant as a {@code long}.
567      * <p>
568      * This queries this instant for the value of the specified field.
569      * If it is not possible to return the value, because the field is not supported
570      * or for some other reason, an exception is thrown.
571      * <p>
572      * If the field is a {@link ChronoField} then the query is implemented here.
573      * The {@link #isSupported(TemporalField) supported fields} will return valid
574      * values based on this date-time.
575      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
576      * <p>
577      * If the field is not a {@code ChronoField}, then the result of this method
578      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
579      * passing {@code this} as the argument. Whether the value can be obtained,
580      * and what the value represents, is determined by the field.
581      *
582      * @param field  the field to get, not null
583      * @return the value for the field
584      * @throws DateTimeException if a value for the field cannot be obtained
585      * @throws UnsupportedTemporalTypeException if the field is not supported
586      * @throws ArithmeticException if numeric overflow occurs
587      */
588     @Override
getLong(TemporalField field)589     public long getLong(TemporalField field) {
590         if (field instanceof ChronoField) {
591             switch ((ChronoField) field) {
592                 case NANO_OF_SECOND: return nanos;
593                 case MICRO_OF_SECOND: return nanos / 1000;
594                 case MILLI_OF_SECOND: return nanos / 1000_000;
595                 case INSTANT_SECONDS: return seconds;
596             }
597             throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
598         }
599         return field.getFrom(this);
600     }
601 
602     //-----------------------------------------------------------------------
603     /**
604      * Gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z.
605      * <p>
606      * The epoch second count is a simple incrementing count of seconds where
607      * second 0 is 1970-01-01T00:00:00Z.
608      * The nanosecond part is returned by {@link #getNano}.
609      *
610      * @return the seconds from the epoch of 1970-01-01T00:00:00Z
611      */
getEpochSecond()612     public long getEpochSecond() {
613         return seconds;
614     }
615 
616     /**
617      * Gets the number of nanoseconds, later along the time-line, from the start
618      * of the second.
619      * <p>
620      * The nanosecond-of-second value measures the total number of nanoseconds from
621      * the second returned by {@link #getEpochSecond}.
622      *
623      * @return the nanoseconds within the second, always positive, never exceeds 999,999,999
624      */
getNano()625     public int getNano() {
626         return nanos;
627     }
628 
629     //-------------------------------------------------------------------------
630     /**
631      * Returns an adjusted copy of this instant.
632      * <p>
633      * This returns an {@code Instant}, based on this one, with the instant adjusted.
634      * The adjustment takes place using the specified adjuster strategy object.
635      * Read the documentation of the adjuster to understand what adjustment will be made.
636      * <p>
637      * The result of this method is obtained by invoking the
638      * {@link TemporalAdjuster#adjustInto(Temporal)} method on the
639      * specified adjuster passing {@code this} as the argument.
640      * <p>
641      * This instance is immutable and unaffected by this method call.
642      *
643      * @param adjuster the adjuster to use, not null
644      * @return an {@code Instant} based on {@code this} with the adjustment made, not null
645      * @throws DateTimeException if the adjustment cannot be made
646      * @throws ArithmeticException if numeric overflow occurs
647      */
648     @Override
with(TemporalAdjuster adjuster)649     public Instant with(TemporalAdjuster adjuster) {
650         return (Instant) adjuster.adjustInto(this);
651     }
652 
653     /**
654      * Returns a copy of this instant with the specified field set to a new value.
655      * <p>
656      * This returns an {@code Instant}, based on this one, with the value
657      * for the specified field changed.
658      * If it is not possible to set the value, because the field is not supported or for
659      * some other reason, an exception is thrown.
660      * <p>
661      * If the field is a {@link ChronoField} then the adjustment is implemented here.
662      * The supported fields behave as follows:
663      * <ul>
664      * <li>{@code NANO_OF_SECOND} -
665      *  Returns an {@code Instant} with the specified nano-of-second.
666      *  The epoch-second will be unchanged.
667      * <li>{@code MICRO_OF_SECOND} -
668      *  Returns an {@code Instant} with the nano-of-second replaced by the specified
669      *  micro-of-second multiplied by 1,000. The epoch-second will be unchanged.
670      * <li>{@code MILLI_OF_SECOND} -
671      *  Returns an {@code Instant} with the nano-of-second replaced by the specified
672      *  milli-of-second multiplied by 1,000,000. The epoch-second will be unchanged.
673      * <li>{@code INSTANT_SECONDS} -
674      *  Returns an {@code Instant} with the specified epoch-second.
675      *  The nano-of-second will be unchanged.
676      * </ul>
677      * <p>
678      * In all cases, if the new value is outside the valid range of values for the field
679      * then a {@code DateTimeException} will be thrown.
680      * <p>
681      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
682      * <p>
683      * If the field is not a {@code ChronoField}, then the result of this method
684      * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
685      * passing {@code this} as the argument. In this case, the field determines
686      * whether and how to adjust the instant.
687      * <p>
688      * This instance is immutable and unaffected by this method call.
689      *
690      * @param field  the field to set in the result, not null
691      * @param newValue  the new value of the field in the result
692      * @return an {@code Instant} based on {@code this} with the specified field set, not null
693      * @throws DateTimeException if the field cannot be set
694      * @throws UnsupportedTemporalTypeException if the field is not supported
695      * @throws ArithmeticException if numeric overflow occurs
696      */
697     @Override
with(TemporalField field, long newValue)698     public Instant with(TemporalField field, long newValue) {
699         if (field instanceof ChronoField chronoField) {
700             chronoField.checkValidValue(newValue);
701             switch (chronoField) {
702                 case MILLI_OF_SECOND: {
703                     int nval = (int) newValue * 1000_000;
704                     return (nval != nanos ? create(seconds, nval) : this);
705                 }
706                 case MICRO_OF_SECOND: {
707                     int nval = (int) newValue * 1000;
708                     return (nval != nanos ? create(seconds, nval) : this);
709                 }
710                 case NANO_OF_SECOND: return (newValue != nanos ? create(seconds, (int) newValue) : this);
711                 case INSTANT_SECONDS: return (newValue != seconds ? create(newValue, nanos) : this);
712             }
713             throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
714         }
715         return field.adjustInto(this, newValue);
716     }
717 
718     //-----------------------------------------------------------------------
719     /**
720      * Returns a copy of this {@code Instant} truncated to the specified unit.
721      * <p>
722      * Truncating the instant returns a copy of the original with fields
723      * smaller than the specified unit set to zero.
724      * The fields are calculated on the basis of using a UTC offset as seen
725      * in {@code toString}.
726      * For example, truncating with the {@link ChronoUnit#MINUTES MINUTES} unit will
727      * round down to the nearest minute, setting the seconds and nanoseconds to zero.
728      * <p>
729      * The unit must have a {@linkplain TemporalUnit#getDuration() duration}
730      * that divides into the length of a standard day without remainder.
731      * This includes all supplied time units on {@link ChronoUnit} and
732      * {@link ChronoUnit#DAYS DAYS}. Other units throw an exception.
733      * <p>
734      * This instance is immutable and unaffected by this method call.
735      *
736      * @param unit  the unit to truncate to, not null
737      * @return an {@code Instant} based on this instant with the time truncated, not null
738      * @throws DateTimeException if the unit is invalid for truncation
739      * @throws UnsupportedTemporalTypeException if the unit is not supported
740      */
truncatedTo(TemporalUnit unit)741     public Instant truncatedTo(TemporalUnit unit) {
742         if (unit == ChronoUnit.NANOS) {
743             return this;
744         }
745         Duration unitDur = unit.getDuration();
746         if (unitDur.getSeconds() > LocalTime.SECONDS_PER_DAY) {
747             throw new UnsupportedTemporalTypeException("Unit is too large to be used for truncation");
748         }
749         long dur = unitDur.toNanos();
750         if ((LocalTime.NANOS_PER_DAY % dur) != 0) {
751             throw new UnsupportedTemporalTypeException("Unit must divide into a standard day without remainder");
752         }
753         long nod = (seconds % LocalTime.SECONDS_PER_DAY) * LocalTime.NANOS_PER_SECOND + nanos;
754         long result = Math.floorDiv(nod, dur) * dur;
755         return plusNanos(result - nod);
756     }
757 
758     //-----------------------------------------------------------------------
759     /**
760      * Returns a copy of this instant with the specified amount added.
761      * <p>
762      * This returns an {@code Instant}, based on this one, with the specified amount added.
763      * The amount is typically {@link Duration} but may be any other type implementing
764      * the {@link TemporalAmount} interface.
765      * <p>
766      * The calculation is delegated to the amount object by calling
767      * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free
768      * to implement the addition in any way it wishes, however it typically
769      * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation
770      * of the amount implementation to determine if it can be successfully added.
771      * <p>
772      * This instance is immutable and unaffected by this method call.
773      *
774      * @param amountToAdd  the amount to add, not null
775      * @return an {@code Instant} based on this instant with the addition made, not null
776      * @throws DateTimeException if the addition cannot be made
777      * @throws ArithmeticException if numeric overflow occurs
778      */
779     @Override
plus(TemporalAmount amountToAdd)780     public Instant plus(TemporalAmount amountToAdd) {
781         return (Instant) amountToAdd.addTo(this);
782     }
783 
784     /**
785      * Returns a copy of this instant with the specified amount added.
786      * <p>
787      * This returns an {@code Instant}, based on this one, with the amount
788      * in terms of the unit added. If it is not possible to add the amount, because the
789      * unit is not supported or for some other reason, an exception is thrown.
790      * <p>
791      * If the field is a {@link ChronoUnit} then the addition is implemented here.
792      * The supported fields behave as follows:
793      * <ul>
794      * <li>{@code NANOS} -
795      *  Returns an {@code Instant} with the specified number of nanoseconds added.
796      *  This is equivalent to {@link #plusNanos(long)}.
797      * <li>{@code MICROS} -
798      *  Returns an {@code Instant} with the specified number of microseconds added.
799      *  This is equivalent to {@link #plusNanos(long)} with the amount
800      *  multiplied by 1,000.
801      * <li>{@code MILLIS} -
802      *  Returns an {@code Instant} with the specified number of milliseconds added.
803      *  This is equivalent to {@link #plusNanos(long)} with the amount
804      *  multiplied by 1,000,000.
805      * <li>{@code SECONDS} -
806      *  Returns an {@code Instant} with the specified number of seconds added.
807      *  This is equivalent to {@link #plusSeconds(long)}.
808      * <li>{@code MINUTES} -
809      *  Returns an {@code Instant} with the specified number of minutes added.
810      *  This is equivalent to {@link #plusSeconds(long)} with the amount
811      *  multiplied by 60.
812      * <li>{@code HOURS} -
813      *  Returns an {@code Instant} with the specified number of hours added.
814      *  This is equivalent to {@link #plusSeconds(long)} with the amount
815      *  multiplied by 3,600.
816      * <li>{@code HALF_DAYS} -
817      *  Returns an {@code Instant} with the specified number of half-days added.
818      *  This is equivalent to {@link #plusSeconds(long)} with the amount
819      *  multiplied by 43,200 (12 hours).
820      * <li>{@code DAYS} -
821      *  Returns an {@code Instant} with the specified number of days added.
822      *  This is equivalent to {@link #plusSeconds(long)} with the amount
823      *  multiplied by 86,400 (24 hours).
824      * </ul>
825      * <p>
826      * All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}.
827      * <p>
828      * If the field is not a {@code ChronoUnit}, then the result of this method
829      * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
830      * passing {@code this} as the argument. In this case, the unit determines
831      * whether and how to perform the addition.
832      * <p>
833      * This instance is immutable and unaffected by this method call.
834      *
835      * @param amountToAdd  the amount of the unit to add to the result, may be negative
836      * @param unit  the unit of the amount to add, not null
837      * @return an {@code Instant} based on this instant with the specified amount added, not null
838      * @throws DateTimeException if the addition cannot be made
839      * @throws UnsupportedTemporalTypeException if the unit is not supported
840      * @throws ArithmeticException if numeric overflow occurs
841      */
842     @Override
plus(long amountToAdd, TemporalUnit unit)843     public Instant plus(long amountToAdd, TemporalUnit unit) {
844         if (unit instanceof ChronoUnit) {
845             switch ((ChronoUnit) unit) {
846                 case NANOS: return plusNanos(amountToAdd);
847                 case MICROS: return plus(amountToAdd / 1000_000, (amountToAdd % 1000_000) * 1000);
848                 case MILLIS: return plusMillis(amountToAdd);
849                 case SECONDS: return plusSeconds(amountToAdd);
850                 case MINUTES: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_MINUTE));
851                 case HOURS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_HOUR));
852                 case HALF_DAYS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY / 2));
853                 case DAYS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY));
854             }
855             throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
856         }
857         return unit.addTo(this, amountToAdd);
858     }
859 
860     //-----------------------------------------------------------------------
861     /**
862      * Returns a copy of this instant with the specified duration in seconds added.
863      * <p>
864      * This instance is immutable and unaffected by this method call.
865      *
866      * @param secondsToAdd  the seconds to add, positive or negative
867      * @return an {@code Instant} based on this instant with the specified seconds added, not null
868      * @throws DateTimeException if the result exceeds the maximum or minimum instant
869      * @throws ArithmeticException if numeric overflow occurs
870      */
plusSeconds(long secondsToAdd)871     public Instant plusSeconds(long secondsToAdd) {
872         return plus(secondsToAdd, 0);
873     }
874 
875     /**
876      * Returns a copy of this instant with the specified duration in milliseconds added.
877      * <p>
878      * This instance is immutable and unaffected by this method call.
879      *
880      * @param millisToAdd  the milliseconds to add, positive or negative
881      * @return an {@code Instant} based on this instant with the specified milliseconds added, not null
882      * @throws DateTimeException if the result exceeds the maximum or minimum instant
883      * @throws ArithmeticException if numeric overflow occurs
884      */
plusMillis(long millisToAdd)885     public Instant plusMillis(long millisToAdd) {
886         return plus(millisToAdd / 1000, (millisToAdd % 1000) * 1000_000);
887     }
888 
889     /**
890      * Returns a copy of this instant with the specified duration in nanoseconds added.
891      * <p>
892      * This instance is immutable and unaffected by this method call.
893      *
894      * @param nanosToAdd  the nanoseconds to add, positive or negative
895      * @return an {@code Instant} based on this instant with the specified nanoseconds added, not null
896      * @throws DateTimeException if the result exceeds the maximum or minimum instant
897      * @throws ArithmeticException if numeric overflow occurs
898      */
plusNanos(long nanosToAdd)899     public Instant plusNanos(long nanosToAdd) {
900         return plus(0, nanosToAdd);
901     }
902 
903     /**
904      * Returns a copy of this instant with the specified duration added.
905      * <p>
906      * This instance is immutable and unaffected by this method call.
907      *
908      * @param secondsToAdd  the seconds to add, positive or negative
909      * @param nanosToAdd  the nanos to add, positive or negative
910      * @return an {@code Instant} based on this instant with the specified seconds added, not null
911      * @throws DateTimeException if the result exceeds the maximum or minimum instant
912      * @throws ArithmeticException if numeric overflow occurs
913      */
plus(long secondsToAdd, long nanosToAdd)914     private Instant plus(long secondsToAdd, long nanosToAdd) {
915         if ((secondsToAdd | nanosToAdd) == 0) {
916             return this;
917         }
918         long epochSec = Math.addExact(seconds, secondsToAdd);
919         epochSec = Math.addExact(epochSec, nanosToAdd / NANOS_PER_SECOND);
920         nanosToAdd = nanosToAdd % NANOS_PER_SECOND;
921         long nanoAdjustment = nanos + nanosToAdd;  // safe int+NANOS_PER_SECOND
922         return ofEpochSecond(epochSec, nanoAdjustment);
923     }
924 
925     //-----------------------------------------------------------------------
926     /**
927      * Returns a copy of this instant with the specified amount subtracted.
928      * <p>
929      * This returns an {@code Instant}, based on this one, with the specified amount subtracted.
930      * The amount is typically {@link Duration} but may be any other type implementing
931      * the {@link TemporalAmount} interface.
932      * <p>
933      * The calculation is delegated to the amount object by calling
934      * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free
935      * to implement the subtraction in any way it wishes, however it typically
936      * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation
937      * of the amount implementation to determine if it can be successfully subtracted.
938      * <p>
939      * This instance is immutable and unaffected by this method call.
940      *
941      * @param amountToSubtract  the amount to subtract, not null
942      * @return an {@code Instant} based on this instant with the subtraction made, not null
943      * @throws DateTimeException if the subtraction cannot be made
944      * @throws ArithmeticException if numeric overflow occurs
945      */
946     @Override
minus(TemporalAmount amountToSubtract)947     public Instant minus(TemporalAmount amountToSubtract) {
948         return (Instant) amountToSubtract.subtractFrom(this);
949     }
950 
951     /**
952      * Returns a copy of this instant with the specified amount subtracted.
953      * <p>
954      * This returns an {@code Instant}, based on this one, with the amount
955      * in terms of the unit subtracted. If it is not possible to subtract the amount,
956      * because the unit is not supported or for some other reason, an exception is thrown.
957      * <p>
958      * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.
959      * See that method for a full description of how addition, and thus subtraction, works.
960      * <p>
961      * This instance is immutable and unaffected by this method call.
962      *
963      * @param amountToSubtract  the amount of the unit to subtract from the result, may be negative
964      * @param unit  the unit of the amount to subtract, not null
965      * @return an {@code Instant} based on this instant with the specified amount subtracted, not null
966      * @throws DateTimeException if the subtraction cannot be made
967      * @throws UnsupportedTemporalTypeException if the unit is not supported
968      * @throws ArithmeticException if numeric overflow occurs
969      */
970     @Override
minus(long amountToSubtract, TemporalUnit unit)971     public Instant minus(long amountToSubtract, TemporalUnit unit) {
972         return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
973     }
974 
975     //-----------------------------------------------------------------------
976     /**
977      * Returns a copy of this instant with the specified duration in seconds subtracted.
978      * <p>
979      * This instance is immutable and unaffected by this method call.
980      *
981      * @param secondsToSubtract  the seconds to subtract, positive or negative
982      * @return an {@code Instant} based on this instant with the specified seconds subtracted, not null
983      * @throws DateTimeException if the result exceeds the maximum or minimum instant
984      * @throws ArithmeticException if numeric overflow occurs
985      */
minusSeconds(long secondsToSubtract)986     public Instant minusSeconds(long secondsToSubtract) {
987         if (secondsToSubtract == Long.MIN_VALUE) {
988             return plusSeconds(Long.MAX_VALUE).plusSeconds(1);
989         }
990         return plusSeconds(-secondsToSubtract);
991     }
992 
993     /**
994      * Returns a copy of this instant with the specified duration in milliseconds subtracted.
995      * <p>
996      * This instance is immutable and unaffected by this method call.
997      *
998      * @param millisToSubtract  the milliseconds to subtract, positive or negative
999      * @return an {@code Instant} based on this instant with the specified milliseconds subtracted, not null
1000      * @throws DateTimeException if the result exceeds the maximum or minimum instant
1001      * @throws ArithmeticException if numeric overflow occurs
1002      */
minusMillis(long millisToSubtract)1003     public Instant minusMillis(long millisToSubtract) {
1004         if (millisToSubtract == Long.MIN_VALUE) {
1005             return plusMillis(Long.MAX_VALUE).plusMillis(1);
1006         }
1007         return plusMillis(-millisToSubtract);
1008     }
1009 
1010     /**
1011      * Returns a copy of this instant with the specified duration in nanoseconds subtracted.
1012      * <p>
1013      * This instance is immutable and unaffected by this method call.
1014      *
1015      * @param nanosToSubtract  the nanoseconds to subtract, positive or negative
1016      * @return an {@code Instant} based on this instant with the specified nanoseconds subtracted, not null
1017      * @throws DateTimeException if the result exceeds the maximum or minimum instant
1018      * @throws ArithmeticException if numeric overflow occurs
1019      */
minusNanos(long nanosToSubtract)1020     public Instant minusNanos(long nanosToSubtract) {
1021         if (nanosToSubtract == Long.MIN_VALUE) {
1022             return plusNanos(Long.MAX_VALUE).plusNanos(1);
1023         }
1024         return plusNanos(-nanosToSubtract);
1025     }
1026 
1027     //-------------------------------------------------------------------------
1028     /**
1029      * Queries this instant using the specified query.
1030      * <p>
1031      * This queries this instant using the specified query strategy object.
1032      * The {@code TemporalQuery} object defines the logic to be used to
1033      * obtain the result. Read the documentation of the query to understand
1034      * what the result of this method will be.
1035      * <p>
1036      * The result of this method is obtained by invoking the
1037      * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
1038      * specified query passing {@code this} as the argument.
1039      *
1040      * @param <R> the type of the result
1041      * @param query  the query to invoke, not null
1042      * @return the query result, null may be returned (defined by the query)
1043      * @throws DateTimeException if unable to query (defined by the query)
1044      * @throws ArithmeticException if numeric overflow occurs (defined by the query)
1045      */
1046     @SuppressWarnings("unchecked")
1047     @Override
query(TemporalQuery<R> query)1048     public <R> R query(TemporalQuery<R> query) {
1049         if (query == TemporalQueries.precision()) {
1050             return (R) NANOS;
1051         }
1052         // inline TemporalAccessor.super.query(query) as an optimization
1053         if (query == TemporalQueries.chronology() || query == TemporalQueries.zoneId() ||
1054                 query == TemporalQueries.zone() || query == TemporalQueries.offset() ||
1055                 query == TemporalQueries.localDate() || query == TemporalQueries.localTime()) {
1056             return null;
1057         }
1058         return query.queryFrom(this);
1059     }
1060 
1061     /**
1062      * Adjusts the specified temporal object to have this instant.
1063      * <p>
1064      * This returns a temporal object of the same observable type as the input
1065      * with the instant changed to be the same as this.
1066      * <p>
1067      * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
1068      * twice, passing {@link ChronoField#INSTANT_SECONDS} and
1069      * {@link ChronoField#NANO_OF_SECOND} as the fields.
1070      * <p>
1071      * In most cases, it is clearer to reverse the calling pattern by using
1072      * {@link Temporal#with(TemporalAdjuster)}:
1073      * <pre>
1074      *   // these two lines are equivalent, but the second approach is recommended
1075      *   temporal = thisInstant.adjustInto(temporal);
1076      *   temporal = temporal.with(thisInstant);
1077      * </pre>
1078      * <p>
1079      * This instance is immutable and unaffected by this method call.
1080      *
1081      * @param temporal  the target object to be adjusted, not null
1082      * @return the adjusted object, not null
1083      * @throws DateTimeException if unable to make the adjustment
1084      * @throws ArithmeticException if numeric overflow occurs
1085      */
1086     @Override
adjustInto(Temporal temporal)1087     public Temporal adjustInto(Temporal temporal) {
1088         return temporal.with(INSTANT_SECONDS, seconds).with(NANO_OF_SECOND, nanos);
1089     }
1090 
1091     /**
1092      * Calculates the amount of time until another instant in terms of the specified unit.
1093      * <p>
1094      * This calculates the amount of time between two {@code Instant}
1095      * objects in terms of a single {@code TemporalUnit}.
1096      * The start and end points are {@code this} and the specified instant.
1097      * The result will be negative if the end is before the start.
1098      * The calculation returns a whole number, representing the number of
1099      * complete units between the two instants.
1100      * The {@code Temporal} passed to this method is converted to a
1101      * {@code Instant} using {@link #from(TemporalAccessor)}.
1102      * For example, the amount in seconds between two dates can be calculated
1103      * using {@code startInstant.until(endInstant, SECONDS)}.
1104      * <p>
1105      * There are two equivalent ways of using this method.
1106      * The first is to invoke this method.
1107      * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
1108      * <pre>
1109      *   // these two lines are equivalent
1110      *   amount = start.until(end, SECONDS);
1111      *   amount = SECONDS.between(start, end);
1112      * </pre>
1113      * The choice should be made based on which makes the code more readable.
1114      * <p>
1115      * The calculation is implemented in this method for {@link ChronoUnit}.
1116      * The units {@code NANOS}, {@code MICROS}, {@code MILLIS}, {@code SECONDS},
1117      * {@code MINUTES}, {@code HOURS}, {@code HALF_DAYS} and {@code DAYS}
1118      * are supported. Other {@code ChronoUnit} values will throw an exception.
1119      * <p>
1120      * If the unit is not a {@code ChronoUnit}, then the result of this method
1121      * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
1122      * passing {@code this} as the first argument and the converted input temporal
1123      * as the second argument.
1124      * <p>
1125      * This instance is immutable and unaffected by this method call.
1126      *
1127      * @param endExclusive  the end date, exclusive, which is converted to an {@code Instant}, not null
1128      * @param unit  the unit to measure the amount in, not null
1129      * @return the amount of time between this instant and the end instant
1130      * @throws DateTimeException if the amount cannot be calculated, or the end
1131      *  temporal cannot be converted to an {@code Instant}
1132      * @throws UnsupportedTemporalTypeException if the unit is not supported
1133      * @throws ArithmeticException if numeric overflow occurs
1134      */
1135     @Override
until(Temporal endExclusive, TemporalUnit unit)1136     public long until(Temporal endExclusive, TemporalUnit unit) {
1137         Instant end = Instant.from(endExclusive);
1138         if (unit instanceof ChronoUnit chronoUnit) {
1139             switch (chronoUnit) {
1140                 case NANOS: return nanosUntil(end);
1141                 case MICROS: return nanosUntil(end) / 1000;
1142                 case MILLIS: return Math.subtractExact(end.toEpochMilli(), toEpochMilli());
1143                 case SECONDS: return secondsUntil(end);
1144                 case MINUTES: return secondsUntil(end) / SECONDS_PER_MINUTE;
1145                 case HOURS: return secondsUntil(end) / SECONDS_PER_HOUR;
1146                 case HALF_DAYS: return secondsUntil(end) / (12 * SECONDS_PER_HOUR);
1147                 case DAYS: return secondsUntil(end) / (SECONDS_PER_DAY);
1148             }
1149             throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
1150         }
1151         return unit.between(this, end);
1152     }
1153 
nanosUntil(Instant end)1154     private long nanosUntil(Instant end) {
1155         long secsDiff = Math.subtractExact(end.seconds, seconds);
1156         long totalNanos = Math.multiplyExact(secsDiff, NANOS_PER_SECOND);
1157         return Math.addExact(totalNanos, end.nanos - nanos);
1158     }
1159 
secondsUntil(Instant end)1160     private long secondsUntil(Instant end) {
1161         long secsDiff = Math.subtractExact(end.seconds, seconds);
1162         long nanosDiff = end.nanos - nanos;
1163         if (secsDiff > 0 && nanosDiff < 0) {
1164             secsDiff--;
1165         } else if (secsDiff < 0 && nanosDiff > 0) {
1166             secsDiff++;
1167         }
1168         return secsDiff;
1169     }
1170 
1171     //-----------------------------------------------------------------------
1172     /**
1173      * Combines this instant with an offset to create an {@code OffsetDateTime}.
1174      * <p>
1175      * This returns an {@code OffsetDateTime} formed from this instant at the
1176      * specified offset from UTC/Greenwich. An exception will be thrown if the
1177      * instant is too large to fit into an offset date-time.
1178      * <p>
1179      * This method is equivalent to
1180      * {@link OffsetDateTime#ofInstant(Instant, ZoneId) OffsetDateTime.ofInstant(this, offset)}.
1181      *
1182      * @param offset  the offset to combine with, not null
1183      * @return the offset date-time formed from this instant and the specified offset, not null
1184      * @throws DateTimeException if the result exceeds the supported range
1185      */
atOffset(ZoneOffset offset)1186     public OffsetDateTime atOffset(ZoneOffset offset) {
1187         return OffsetDateTime.ofInstant(this, offset);
1188     }
1189 
1190     /**
1191      * Combines this instant with a time-zone to create a {@code ZonedDateTime}.
1192      * <p>
1193      * This returns an {@code ZonedDateTime} formed from this instant at the
1194      * specified time-zone. An exception will be thrown if the instant is too
1195      * large to fit into a zoned date-time.
1196      * <p>
1197      * This method is equivalent to
1198      * {@link ZonedDateTime#ofInstant(Instant, ZoneId) ZonedDateTime.ofInstant(this, zone)}.
1199      *
1200      * @param zone  the zone to combine with, not null
1201      * @return the zoned date-time formed from this instant and the specified zone, not null
1202      * @throws DateTimeException if the result exceeds the supported range
1203      */
atZone(ZoneId zone)1204     public ZonedDateTime atZone(ZoneId zone) {
1205         return ZonedDateTime.ofInstant(this, zone);
1206     }
1207 
1208     //-----------------------------------------------------------------------
1209     /**
1210      * Converts this instant to the number of milliseconds from the epoch
1211      * of 1970-01-01T00:00:00Z.
1212      * <p>
1213      * If this instant represents a point on the time-line too far in the future
1214      * or past to fit in a {@code long} milliseconds, then an exception is thrown.
1215      * <p>
1216      * If this instant has greater than millisecond precision, then the conversion
1217      * will drop any excess precision information as though the amount in nanoseconds
1218      * was subject to integer division by one million.
1219      *
1220      * @return the number of milliseconds since the epoch of 1970-01-01T00:00:00Z
1221      * @throws ArithmeticException if numeric overflow occurs
1222      */
toEpochMilli()1223     public long toEpochMilli() {
1224         if (seconds < 0 && nanos > 0) {
1225             long millis = Math.multiplyExact(seconds+1, 1000);
1226             long adjustment = nanos / 1000_000 - 1000;
1227             return Math.addExact(millis, adjustment);
1228         } else {
1229             long millis = Math.multiplyExact(seconds, 1000);
1230             return Math.addExact(millis, nanos / 1000_000);
1231         }
1232     }
1233 
1234     //-----------------------------------------------------------------------
1235     /**
1236      * Compares this instant to the specified instant.
1237      * <p>
1238      * The comparison is based on the time-line position of the instants.
1239      * It is "consistent with equals", as defined by {@link Comparable}.
1240      *
1241      * @param otherInstant  the other instant to compare to, not null
1242      * @return the comparator value, negative if less, positive if greater
1243      * @throws NullPointerException if otherInstant is null
1244      */
1245     @Override
compareTo(Instant otherInstant)1246     public int compareTo(Instant otherInstant) {
1247         int cmp = Long.compare(seconds, otherInstant.seconds);
1248         if (cmp != 0) {
1249             return cmp;
1250         }
1251         return nanos - otherInstant.nanos;
1252     }
1253 
1254     /**
1255      * Checks if this instant is after the specified instant.
1256      * <p>
1257      * The comparison is based on the time-line position of the instants.
1258      *
1259      * @param otherInstant  the other instant to compare to, not null
1260      * @return true if this instant is after the specified instant
1261      * @throws NullPointerException if otherInstant is null
1262      */
isAfter(Instant otherInstant)1263     public boolean isAfter(Instant otherInstant) {
1264         return compareTo(otherInstant) > 0;
1265     }
1266 
1267     /**
1268      * Checks if this instant is before the specified instant.
1269      * <p>
1270      * The comparison is based on the time-line position of the instants.
1271      *
1272      * @param otherInstant  the other instant to compare to, not null
1273      * @return true if this instant is before the specified instant
1274      * @throws NullPointerException if otherInstant is null
1275      */
isBefore(Instant otherInstant)1276     public boolean isBefore(Instant otherInstant) {
1277         return compareTo(otherInstant) < 0;
1278     }
1279 
1280     //-----------------------------------------------------------------------
1281     /**
1282      * Checks if this instant is equal to the specified instant.
1283      * <p>
1284      * The comparison is based on the time-line position of the instants.
1285      *
1286      * @param other  the other instant, null returns false
1287      * @return true if the other instant is equal to this one
1288      */
1289     @Override
equals(Object other)1290     public boolean equals(Object other) {
1291         if (this == other) {
1292             return true;
1293         }
1294         return (other instanceof Instant otherInstant)
1295                 && this.seconds == otherInstant.seconds
1296                 && this.nanos == otherInstant.nanos;
1297     }
1298 
1299     /**
1300      * Returns a hash code for this instant.
1301      *
1302      * @return a suitable hash code
1303      */
1304     @Override
hashCode()1305     public int hashCode() {
1306         return ((int) (seconds ^ (seconds >>> 32))) + 51 * nanos;
1307     }
1308 
1309     //-----------------------------------------------------------------------
1310     /**
1311      * A string representation of this instant using ISO-8601 representation.
1312      * <p>
1313      * The format used is the same as {@link DateTimeFormatter#ISO_INSTANT}.
1314      *
1315      * @return an ISO-8601 representation of this instant, not null
1316      */
1317     @Override
toString()1318     public String toString() {
1319         return DateTimeFormatter.ISO_INSTANT.format(this);
1320     }
1321 
1322     // -----------------------------------------------------------------------
1323     /**
1324      * Writes the object using a
1325      * <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>.
1326      * @serialData
1327      * <pre>
1328      *  out.writeByte(2);  // identifies an Instant
1329      *  out.writeLong(seconds);
1330      *  out.writeInt(nanos);
1331      * </pre>
1332      *
1333      * @return the instance of {@code Ser}, not null
1334      */
1335     @java.io.Serial
writeReplace()1336     private Object writeReplace() {
1337         return new Ser(Ser.INSTANT_TYPE, this);
1338     }
1339 
1340     /**
1341      * Defend against malicious streams.
1342      *
1343      * @param s the stream to read
1344      * @throws InvalidObjectException always
1345      */
1346     @java.io.Serial
readObject(ObjectInputStream s)1347     private void readObject(ObjectInputStream s) throws InvalidObjectException {
1348         throw new InvalidObjectException("Deserialization via serialization delegate");
1349     }
1350 
writeExternal(DataOutput out)1351     void writeExternal(DataOutput out) throws IOException {
1352         out.writeLong(seconds);
1353         out.writeInt(nanos);
1354     }
1355 
readExternal(DataInput in)1356     static Instant readExternal(DataInput in) throws IOException {
1357         long seconds = in.readLong();
1358         int nanos = in.readInt();
1359         return Instant.ofEpochSecond(seconds, nanos);
1360     }
1361 
1362 }
1363