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