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