• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2012, 2018, 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  * <h3>Time-scale</h3>
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     private static final long serialVersionUID = -665713676816604388L;
243 
244     /**
245      * The number of seconds from the epoch of 1970-01-01T00:00:00Z.
246      */
247     private final long seconds;
248     /**
249      * The number of nanoseconds, later along the time-line, from the seconds field.
250      * This is always positive, and never exceeds 999,999,999.
251      */
252     private final int nanos;
253 
254     //-----------------------------------------------------------------------
255     /**
256      * Obtains the current instant from the system clock.
257      * <p>
258      * This will query the {@link Clock#systemUTC() system UTC clock} to
259      * obtain the current instant.
260      * <p>
261      * Using this method will prevent the ability to use an alternate time-source for
262      * testing because the clock is effectively hard-coded.
263      *
264      * @return the current instant using the system clock, not null
265      */
now()266     public static Instant now() {
267         return Clock.systemUTC().instant();
268     }
269 
270     /**
271      * Obtains the current instant from the specified clock.
272      * <p>
273      * This will query the specified clock to obtain the current time.
274      * <p>
275      * Using this method allows the use of an alternate clock for testing.
276      * The alternate clock may be introduced using {@link Clock dependency injection}.
277      *
278      * @param clock  the clock to use, not null
279      * @return the current instant, not null
280      */
now(Clock clock)281     public static Instant now(Clock clock) {
282         Objects.requireNonNull(clock, "clock");
283         return clock.instant();
284     }
285 
286     //-----------------------------------------------------------------------
287     /**
288      * Obtains an instance of {@code Instant} using seconds from the
289      * epoch of 1970-01-01T00:00:00Z.
290      * <p>
291      * The nanosecond field is set to zero.
292      *
293      * @param epochSecond  the number of seconds from 1970-01-01T00:00:00Z
294      * @return an instant, not null
295      * @throws DateTimeException if the instant exceeds the maximum or minimum instant
296      */
ofEpochSecond(long epochSecond)297     public static Instant ofEpochSecond(long epochSecond) {
298         return create(epochSecond, 0);
299     }
300 
301     /**
302      * Obtains an instance of {@code Instant} using seconds from the
303      * epoch of 1970-01-01T00:00:00Z and nanosecond fraction of second.
304      * <p>
305      * This method allows an arbitrary number of nanoseconds to be passed in.
306      * The factory will alter the values of the second and nanosecond in order
307      * to ensure that the stored nanosecond is in the range 0 to 999,999,999.
308      * For example, the following will result in exactly the same instant:
309      * <pre>
310      *  Instant.ofEpochSecond(3, 1);
311      *  Instant.ofEpochSecond(4, -999_999_999);
312      *  Instant.ofEpochSecond(2, 1000_000_001);
313      * </pre>
314      *
315      * @param epochSecond  the number of seconds from 1970-01-01T00:00:00Z
316      * @param nanoAdjustment  the nanosecond adjustment to the number of seconds, positive or negative
317      * @return an instant, not null
318      * @throws DateTimeException if the instant exceeds the maximum or minimum instant
319      * @throws ArithmeticException if numeric overflow occurs
320      */
ofEpochSecond(long epochSecond, long nanoAdjustment)321     public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment) {
322         long secs = Math.addExact(epochSecond, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND));
323         int nos = (int)Math.floorMod(nanoAdjustment, NANOS_PER_SECOND);
324         return create(secs, nos);
325     }
326 
327     /**
328      * Obtains an instance of {@code Instant} using milliseconds from the
329      * epoch of 1970-01-01T00:00:00Z.
330      * <p>
331      * The seconds and nanoseconds are extracted from the specified milliseconds.
332      *
333      * @param epochMilli  the number of milliseconds from 1970-01-01T00:00:00Z
334      * @return an instant, not null
335      * @throws DateTimeException if the instant exceeds the maximum or minimum instant
336      */
ofEpochMilli(long epochMilli)337     public static Instant ofEpochMilli(long epochMilli) {
338         long secs = Math.floorDiv(epochMilli, 1000);
339         int mos = Math.floorMod(epochMilli, 1000);
340         return create(secs, mos * 1000_000);
341     }
342 
343     //-----------------------------------------------------------------------
344     /**
345      * Obtains an instance of {@code Instant} from a temporal object.
346      * <p>
347      * This obtains an instant based on the specified temporal.
348      * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
349      * which this factory converts to an instance of {@code Instant}.
350      * <p>
351      * The conversion extracts the {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS}
352      * and {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} fields.
353      * <p>
354      * This method matches the signature of the functional interface {@link TemporalQuery}
355      * allowing it to be used as a query via method reference, {@code Instant::from}.
356      *
357      * @param temporal  the temporal object to convert, not null
358      * @return the instant, not null
359      * @throws DateTimeException if unable to convert to an {@code Instant}
360      */
from(TemporalAccessor temporal)361     public static Instant from(TemporalAccessor temporal) {
362         if (temporal instanceof Instant) {
363             return (Instant) temporal;
364         }
365         Objects.requireNonNull(temporal, "temporal");
366         try {
367             long instantSecs = temporal.getLong(INSTANT_SECONDS);
368             int nanoOfSecond = temporal.get(NANO_OF_SECOND);
369             return Instant.ofEpochSecond(instantSecs, nanoOfSecond);
370         } catch (DateTimeException ex) {
371             throw new DateTimeException("Unable to obtain Instant from TemporalAccessor: " +
372                     temporal + " of type " + temporal.getClass().getName(), ex);
373         }
374     }
375 
376     //-----------------------------------------------------------------------
377     /**
378      * Obtains an instance of {@code Instant} from a text string such as
379      * {@code 2007-12-03T10:15:30.00Z}.
380      * <p>
381      * The string must represent a valid instant in UTC and is parsed using
382      * {@link DateTimeFormatter#ISO_INSTANT}.
383      *
384      * @param text  the text to parse, not null
385      * @return the parsed instant, not null
386      * @throws DateTimeParseException if the text cannot be parsed
387      */
parse(final CharSequence text)388     public static Instant parse(final CharSequence text) {
389         return DateTimeFormatter.ISO_INSTANT.parse(text, Instant::from);
390     }
391 
392     //-----------------------------------------------------------------------
393     /**
394      * Obtains an instance of {@code Instant} using seconds and nanoseconds.
395      *
396      * @param seconds  the length of the duration in seconds
397      * @param nanoOfSecond  the nano-of-second, from 0 to 999,999,999
398      * @throws DateTimeException if the instant exceeds the maximum or minimum instant
399      */
create(long seconds, int nanoOfSecond)400     private static Instant create(long seconds, int nanoOfSecond) {
401         if ((seconds | nanoOfSecond) == 0) {
402             return EPOCH;
403         }
404         if (seconds < MIN_SECOND || seconds > MAX_SECOND) {
405             throw new DateTimeException("Instant exceeds minimum or maximum instant");
406         }
407         return new Instant(seconds, nanoOfSecond);
408     }
409 
410     /**
411      * Constructs an instance of {@code Instant} using seconds from the epoch of
412      * 1970-01-01T00:00:00Z and nanosecond fraction of second.
413      *
414      * @param epochSecond  the number of seconds from 1970-01-01T00:00:00Z
415      * @param nanos  the nanoseconds within the second, must be positive
416      */
Instant(long epochSecond, int nanos)417     private Instant(long epochSecond, int nanos) {
418         super();
419         this.seconds = epochSecond;
420         this.nanos = nanos;
421     }
422 
423     //-----------------------------------------------------------------------
424     /**
425      * Checks if the specified field is supported.
426      * <p>
427      * This checks if this instant can be queried for the specified field.
428      * If false, then calling the {@link #range(TemporalField) range},
429      * {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}
430      * methods will throw an exception.
431      * <p>
432      * If the field is a {@link ChronoField} then the query is implemented here.
433      * The supported fields are:
434      * <ul>
435      * <li>{@code NANO_OF_SECOND}
436      * <li>{@code MICRO_OF_SECOND}
437      * <li>{@code MILLI_OF_SECOND}
438      * <li>{@code INSTANT_SECONDS}
439      * </ul>
440      * All other {@code ChronoField} instances will return false.
441      * <p>
442      * If the field is not a {@code ChronoField}, then the result of this method
443      * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
444      * passing {@code this} as the argument.
445      * Whether the field is supported is determined by the field.
446      *
447      * @param field  the field to check, null returns false
448      * @return true if the field is supported on this instant, false if not
449      */
450     @Override
isSupported(TemporalField field)451     public boolean isSupported(TemporalField field) {
452         if (field instanceof ChronoField) {
453             return field == INSTANT_SECONDS || field == NANO_OF_SECOND || field == MICRO_OF_SECOND || field == MILLI_OF_SECOND;
454         }
455         return field != null && field.isSupportedBy(this);
456     }
457 
458     /**
459      * Checks if the specified unit is supported.
460      * <p>
461      * This checks if the specified unit can be added to, or subtracted from, this date-time.
462      * If false, then calling the {@link #plus(long, TemporalUnit)} and
463      * {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
464      * <p>
465      * If the unit is a {@link ChronoUnit} then the query is implemented here.
466      * The supported units are:
467      * <ul>
468      * <li>{@code NANOS}
469      * <li>{@code MICROS}
470      * <li>{@code MILLIS}
471      * <li>{@code SECONDS}
472      * <li>{@code MINUTES}
473      * <li>{@code HOURS}
474      * <li>{@code HALF_DAYS}
475      * <li>{@code DAYS}
476      * </ul>
477      * All other {@code ChronoUnit} instances will return false.
478      * <p>
479      * If the unit is not a {@code ChronoUnit}, then the result of this method
480      * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}
481      * passing {@code this} as the argument.
482      * Whether the unit is supported is determined by the unit.
483      *
484      * @param unit  the unit to check, null returns false
485      * @return true if the unit can be added/subtracted, false if not
486      */
487     @Override
isSupported(TemporalUnit unit)488     public boolean isSupported(TemporalUnit unit) {
489         if (unit instanceof ChronoUnit) {
490             return unit.isTimeBased() || unit == DAYS;
491         }
492         return unit != null && unit.isSupportedBy(this);
493     }
494 
495     //-----------------------------------------------------------------------
496     /**
497      * Gets the range of valid values for the specified field.
498      * <p>
499      * The range object expresses the minimum and maximum valid values for a field.
500      * This instant is used to enhance the accuracy of the returned range.
501      * If it is not possible to return the range, because the field is not supported
502      * or for some other reason, an exception is thrown.
503      * <p>
504      * If the field is a {@link ChronoField} then the query is implemented here.
505      * The {@link #isSupported(TemporalField) supported fields} will return
506      * appropriate range instances.
507      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
508      * <p>
509      * If the field is not a {@code ChronoField}, then the result of this method
510      * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
511      * passing {@code this} as the argument.
512      * Whether the range can be obtained is determined by the field.
513      *
514      * @param field  the field to query the range for, not null
515      * @return the range of valid values for the field, not null
516      * @throws DateTimeException if the range for the field cannot be obtained
517      * @throws UnsupportedTemporalTypeException if the field is not supported
518      */
519     @Override  // override for Javadoc
range(TemporalField field)520     public ValueRange range(TemporalField field) {
521         return Temporal.super.range(field);
522     }
523 
524     /**
525      * Gets the value of the specified field from this instant as an {@code int}.
526      * <p>
527      * This queries this instant for the value of the specified field.
528      * The returned value will always be within the valid range of values for the field.
529      * If it is not possible to return the value, because the field is not supported
530      * or for some other reason, an exception is thrown.
531      * <p>
532      * If the field is a {@link ChronoField} then the query is implemented here.
533      * The {@link #isSupported(TemporalField) supported fields} will return valid
534      * values based on this date-time, except {@code INSTANT_SECONDS} which is too
535      * large to fit in an {@code int} and throws a {@code DateTimeException}.
536      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
537      * <p>
538      * If the field is not a {@code ChronoField}, then the result of this method
539      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
540      * passing {@code this} as the argument. Whether the value can be obtained,
541      * and what the value represents, is determined by the field.
542      *
543      * @param field  the field to get, not null
544      * @return the value for the field
545      * @throws DateTimeException if a value for the field cannot be obtained or
546      *         the value is outside the range of valid values for the field
547      * @throws UnsupportedTemporalTypeException if the field is not supported or
548      *         the range of values exceeds an {@code int}
549      * @throws ArithmeticException if numeric overflow occurs
550      */
551     @Override  // override for Javadoc and performance
get(TemporalField field)552     public int get(TemporalField field) {
553         if (field instanceof ChronoField) {
554             switch ((ChronoField) field) {
555                 case NANO_OF_SECOND: return nanos;
556                 case MICRO_OF_SECOND: return nanos / 1000;
557                 case MILLI_OF_SECOND: return nanos / 1000_000;
558             }
559             throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
560         }
561         return range(field).checkValidIntValue(field.getFrom(this), field);
562     }
563 
564     /**
565      * Gets the value of the specified field from this instant as a {@code long}.
566      * <p>
567      * This queries this instant for the value of the specified field.
568      * If it is not possible to return the value, because the field is not supported
569      * or for some other reason, an exception is thrown.
570      * <p>
571      * If the field is a {@link ChronoField} then the query is implemented here.
572      * The {@link #isSupported(TemporalField) supported fields} will return valid
573      * values based on this date-time.
574      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
575      * <p>
576      * If the field is not a {@code ChronoField}, then the result of this method
577      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
578      * passing {@code this} as the argument. Whether the value can be obtained,
579      * and what the value represents, is determined by the field.
580      *
581      * @param field  the field to get, not null
582      * @return the value for the field
583      * @throws DateTimeException if a value for the field cannot be obtained
584      * @throws UnsupportedTemporalTypeException if the field is not supported
585      * @throws ArithmeticException if numeric overflow occurs
586      */
587     @Override
getLong(TemporalField field)588     public long getLong(TemporalField field) {
589         if (field instanceof ChronoField) {
590             switch ((ChronoField) field) {
591                 case NANO_OF_SECOND: return nanos;
592                 case MICRO_OF_SECOND: return nanos / 1000;
593                 case MILLI_OF_SECOND: return nanos / 1000_000;
594                 case INSTANT_SECONDS: return seconds;
595             }
596             throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
597         }
598         return field.getFrom(this);
599     }
600 
601     //-----------------------------------------------------------------------
602     /**
603      * Gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z.
604      * <p>
605      * The epoch second count is a simple incrementing count of seconds where
606      * second 0 is 1970-01-01T00:00:00Z.
607      * The nanosecond part is returned by {@link #getNano}.
608      *
609      * @return the seconds from the epoch of 1970-01-01T00:00:00Z
610      */
getEpochSecond()611     public long getEpochSecond() {
612         return seconds;
613     }
614 
615     /**
616      * Gets the number of nanoseconds, later along the time-line, from the start
617      * of the second.
618      * <p>
619      * The nanosecond-of-second value measures the total number of nanoseconds from
620      * the second returned by {@link #getEpochSecond}.
621      *
622      * @return the nanoseconds within the second, always positive, never exceeds 999,999,999
623      */
getNano()624     public int getNano() {
625         return nanos;
626     }
627 
628     //-------------------------------------------------------------------------
629     /**
630      * Returns an adjusted copy of this instant.
631      * <p>
632      * This returns an {@code Instant}, based on this one, with the instant adjusted.
633      * The adjustment takes place using the specified adjuster strategy object.
634      * Read the documentation of the adjuster to understand what adjustment will be made.
635      * <p>
636      * The result of this method is obtained by invoking the
637      * {@link TemporalAdjuster#adjustInto(Temporal)} method on the
638      * specified adjuster passing {@code this} as the argument.
639      * <p>
640      * This instance is immutable and unaffected by this method call.
641      *
642      * @param adjuster the adjuster to use, not null
643      * @return an {@code Instant} based on {@code this} with the adjustment made, not null
644      * @throws DateTimeException if the adjustment cannot be made
645      * @throws ArithmeticException if numeric overflow occurs
646      */
647     @Override
with(TemporalAdjuster adjuster)648     public Instant with(TemporalAdjuster adjuster) {
649         return (Instant) adjuster.adjustInto(this);
650     }
651 
652     /**
653      * Returns a copy of this instant with the specified field set to a new value.
654      * <p>
655      * This returns an {@code Instant}, based on this one, with the value
656      * for the specified field changed.
657      * If it is not possible to set the value, because the field is not supported or for
658      * some other reason, an exception is thrown.
659      * <p>
660      * If the field is a {@link ChronoField} then the adjustment is implemented here.
661      * The supported fields behave as follows:
662      * <ul>
663      * <li>{@code NANO_OF_SECOND} -
664      *  Returns an {@code Instant} with the specified nano-of-second.
665      *  The epoch-second will be unchanged.
666      * <li>{@code MICRO_OF_SECOND} -
667      *  Returns an {@code Instant} with the nano-of-second replaced by the specified
668      *  micro-of-second multiplied by 1,000. The epoch-second will be unchanged.
669      * <li>{@code MILLI_OF_SECOND} -
670      *  Returns an {@code Instant} with the nano-of-second replaced by the specified
671      *  milli-of-second multiplied by 1,000,000. The epoch-second will be unchanged.
672      * <li>{@code INSTANT_SECONDS} -
673      *  Returns an {@code Instant} with the specified epoch-second.
674      *  The nano-of-second will be unchanged.
675      * </ul>
676      * <p>
677      * In all cases, if the new value is outside the valid range of values for the field
678      * then a {@code DateTimeException} will be thrown.
679      * <p>
680      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
681      * <p>
682      * If the field is not a {@code ChronoField}, then the result of this method
683      * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
684      * passing {@code this} as the argument. In this case, the field determines
685      * whether and how to adjust the instant.
686      * <p>
687      * This instance is immutable and unaffected by this method call.
688      *
689      * @param field  the field to set in the result, not null
690      * @param newValue  the new value of the field in the result
691      * @return an {@code Instant} based on {@code this} with the specified field set, not null
692      * @throws DateTimeException if the field cannot be set
693      * @throws UnsupportedTemporalTypeException if the field is not supported
694      * @throws ArithmeticException if numeric overflow occurs
695      */
696     @Override
with(TemporalField field, long newValue)697     public Instant with(TemporalField field, long newValue) {
698         if (field instanceof ChronoField) {
699             ChronoField f = (ChronoField) field;
700             f.checkValidValue(newValue);
701             switch (f) {
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) {
1139             ChronoUnit f = (ChronoUnit) unit;
1140             switch (f) {
1141                 case NANOS: return nanosUntil(end);
1142                 case MICROS: return nanosUntil(end) / 1000;
1143                 case MILLIS: return Math.subtractExact(end.toEpochMilli(), toEpochMilli());
1144                 case SECONDS: return secondsUntil(end);
1145                 case MINUTES: return secondsUntil(end) / SECONDS_PER_MINUTE;
1146                 case HOURS: return secondsUntil(end) / SECONDS_PER_HOUR;
1147                 case HALF_DAYS: return secondsUntil(end) / (12 * SECONDS_PER_HOUR);
1148                 case DAYS: return secondsUntil(end) / (SECONDS_PER_DAY);
1149             }
1150             throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
1151         }
1152         return unit.between(this, end);
1153     }
1154 
nanosUntil(Instant end)1155     private long nanosUntil(Instant end) {
1156         long secsDiff = Math.subtractExact(end.seconds, seconds);
1157         long totalNanos = Math.multiplyExact(secsDiff, NANOS_PER_SECOND);
1158         return Math.addExact(totalNanos, end.nanos - nanos);
1159     }
1160 
secondsUntil(Instant end)1161     private long secondsUntil(Instant end) {
1162         long secsDiff = Math.subtractExact(end.seconds, seconds);
1163         long nanosDiff = end.nanos - nanos;
1164         if (secsDiff > 0 && nanosDiff < 0) {
1165             secsDiff--;
1166         } else if (secsDiff < 0 && nanosDiff > 0) {
1167             secsDiff++;
1168         }
1169         return secsDiff;
1170     }
1171 
1172     //-----------------------------------------------------------------------
1173     /**
1174      * Combines this instant with an offset to create an {@code OffsetDateTime}.
1175      * <p>
1176      * This returns an {@code OffsetDateTime} formed from this instant at the
1177      * specified offset from UTC/Greenwich. An exception will be thrown if the
1178      * instant is too large to fit into an offset date-time.
1179      * <p>
1180      * This method is equivalent to
1181      * {@link OffsetDateTime#ofInstant(Instant, ZoneId) OffsetDateTime.ofInstant(this, offset)}.
1182      *
1183      * @param offset  the offset to combine with, not null
1184      * @return the offset date-time formed from this instant and the specified offset, not null
1185      * @throws DateTimeException if the result exceeds the supported range
1186      */
atOffset(ZoneOffset offset)1187     public OffsetDateTime atOffset(ZoneOffset offset) {
1188         return OffsetDateTime.ofInstant(this, offset);
1189     }
1190 
1191     /**
1192      * Combines this instant with a time-zone to create a {@code ZonedDateTime}.
1193      * <p>
1194      * This returns an {@code ZonedDateTime} formed from this instant at the
1195      * specified time-zone. An exception will be thrown if the instant is too
1196      * large to fit into a zoned date-time.
1197      * <p>
1198      * This method is equivalent to
1199      * {@link ZonedDateTime#ofInstant(Instant, ZoneId) ZonedDateTime.ofInstant(this, zone)}.
1200      *
1201      * @param zone  the zone to combine with, not null
1202      * @return the zoned date-time formed from this instant and the specified zone, not null
1203      * @throws DateTimeException if the result exceeds the supported range
1204      */
atZone(ZoneId zone)1205     public ZonedDateTime atZone(ZoneId zone) {
1206         return ZonedDateTime.ofInstant(this, zone);
1207     }
1208 
1209     //-----------------------------------------------------------------------
1210     /**
1211      * Converts this instant to the number of milliseconds from the epoch
1212      * of 1970-01-01T00:00:00Z.
1213      * <p>
1214      * If this instant represents a point on the time-line too far in the future
1215      * or past to fit in a {@code long} milliseconds, then an exception is thrown.
1216      * <p>
1217      * If this instant has greater than millisecond precision, then the conversion
1218      * will drop any excess precision information as though the amount in nanoseconds
1219      * was subject to integer division by one million.
1220      *
1221      * @return the number of milliseconds since the epoch of 1970-01-01T00:00:00Z
1222      * @throws ArithmeticException if numeric overflow occurs
1223      */
toEpochMilli()1224     public long toEpochMilli() {
1225         if (seconds < 0 && nanos > 0) {
1226             long millis = Math.multiplyExact(seconds+1, 1000);
1227             long adjustment = nanos / 1000_000 - 1000;
1228             return Math.addExact(millis, adjustment);
1229         } else {
1230             long millis = Math.multiplyExact(seconds, 1000);
1231             return Math.addExact(millis, nanos / 1000_000);
1232         }
1233     }
1234 
1235     //-----------------------------------------------------------------------
1236     /**
1237      * Compares this instant to the specified instant.
1238      * <p>
1239      * The comparison is based on the time-line position of the instants.
1240      * It is "consistent with equals", as defined by {@link Comparable}.
1241      *
1242      * @param otherInstant  the other instant to compare to, not null
1243      * @return the comparator value, negative if less, positive if greater
1244      * @throws NullPointerException if otherInstant is null
1245      */
1246     @Override
compareTo(Instant otherInstant)1247     public int compareTo(Instant otherInstant) {
1248         int cmp = Long.compare(seconds, otherInstant.seconds);
1249         if (cmp != 0) {
1250             return cmp;
1251         }
1252         return nanos - otherInstant.nanos;
1253     }
1254 
1255     /**
1256      * Checks if this instant is after the specified instant.
1257      * <p>
1258      * The comparison is based on the time-line position of the instants.
1259      *
1260      * @param otherInstant  the other instant to compare to, not null
1261      * @return true if this instant is after the specified instant
1262      * @throws NullPointerException if otherInstant is null
1263      */
isAfter(Instant otherInstant)1264     public boolean isAfter(Instant otherInstant) {
1265         return compareTo(otherInstant) > 0;
1266     }
1267 
1268     /**
1269      * Checks if this instant is before the specified instant.
1270      * <p>
1271      * The comparison is based on the time-line position of the instants.
1272      *
1273      * @param otherInstant  the other instant to compare to, not null
1274      * @return true if this instant is before the specified instant
1275      * @throws NullPointerException if otherInstant is null
1276      */
isBefore(Instant otherInstant)1277     public boolean isBefore(Instant otherInstant) {
1278         return compareTo(otherInstant) < 0;
1279     }
1280 
1281     //-----------------------------------------------------------------------
1282     /**
1283      * Checks if this instant is equal to the specified instant.
1284      * <p>
1285      * The comparison is based on the time-line position of the instants.
1286      *
1287      * @param otherInstant  the other instant, null returns false
1288      * @return true if the other instant is equal to this one
1289      */
1290     @Override
equals(Object otherInstant)1291     public boolean equals(Object otherInstant) {
1292         if (this == otherInstant) {
1293             return true;
1294         }
1295         if (otherInstant instanceof Instant) {
1296             Instant other = (Instant) otherInstant;
1297             return this.seconds == other.seconds &&
1298                    this.nanos == other.nanos;
1299         }
1300         return false;
1301     }
1302 
1303     /**
1304      * Returns a hash code for this instant.
1305      *
1306      * @return a suitable hash code
1307      */
1308     @Override
hashCode()1309     public int hashCode() {
1310         return ((int) (seconds ^ (seconds >>> 32))) + 51 * nanos;
1311     }
1312 
1313     //-----------------------------------------------------------------------
1314     /**
1315      * A string representation of this instant using ISO-8601 representation.
1316      * <p>
1317      * The format used is the same as {@link DateTimeFormatter#ISO_INSTANT}.
1318      *
1319      * @return an ISO-8601 representation of this instant, not null
1320      */
1321     @Override
toString()1322     public String toString() {
1323         return DateTimeFormatter.ISO_INSTANT.format(this);
1324     }
1325 
1326     // -----------------------------------------------------------------------
1327     /**
1328      * Writes the object using a
1329      * <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>.
1330      * @serialData
1331      * <pre>
1332      *  out.writeByte(2);  // identifies an Instant
1333      *  out.writeLong(seconds);
1334      *  out.writeInt(nanos);
1335      * </pre>
1336      *
1337      * @return the instance of {@code Ser}, not null
1338      */
writeReplace()1339     private Object writeReplace() {
1340         return new Ser(Ser.INSTANT_TYPE, this);
1341     }
1342 
1343     /**
1344      * Defend against malicious streams.
1345      *
1346      * @param s the stream to read
1347      * @throws InvalidObjectException always
1348      */
readObject(ObjectInputStream s)1349     private void readObject(ObjectInputStream s) throws InvalidObjectException {
1350         throw new InvalidObjectException("Deserialization via serialization delegate");
1351     }
1352 
writeExternal(DataOutput out)1353     void writeExternal(DataOutput out) throws IOException {
1354         out.writeLong(seconds);
1355         out.writeInt(nanos);
1356     }
1357 
readExternal(DataInput in)1358     static Instant readExternal(DataInput in) throws IOException {
1359         long seconds = in.readLong();
1360         int nanos = in.readInt();
1361         return Instant.ofEpochSecond(seconds, nanos);
1362     }
1363 
1364 }
1365