001/*
002 * Copyright (c) 2007-2013, Stephen Colebourne & Michael Nascimento Santos
003 *
004 * All rights reserved.
005 *
006 * Redistribution and use in source and binary forms, with or without
007 * modification, are permitted provided that the following conditions are met:
008 *
009 *  * Redistributions of source code must retain the above copyright notice,
010 *    this list of conditions and the following disclaimer.
011 *
012 *  * Redistributions in binary form must reproduce the above copyright notice,
013 *    this list of conditions and the following disclaimer in the documentation
014 *    and/or other materials provided with the distribution.
015 *
016 *  * Neither the name of JSR-310 nor the names of its contributors
017 *    may be used to endorse or promote products derived from this software
018 *    without specific prior written permission.
019 *
020 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
021 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
022 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
023 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
024 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
025 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
026 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
027 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
028 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
029 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
030 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
031 */
032package org.threeten.bp;
033
034import static org.threeten.bp.LocalTime.SECONDS_PER_DAY;
035import static org.threeten.bp.LocalTime.SECONDS_PER_HOUR;
036import static org.threeten.bp.LocalTime.SECONDS_PER_MINUTE;
037import static org.threeten.bp.temporal.ChronoField.INSTANT_SECONDS;
038import static org.threeten.bp.temporal.ChronoField.MICRO_OF_SECOND;
039import static org.threeten.bp.temporal.ChronoField.MILLI_OF_SECOND;
040import static org.threeten.bp.temporal.ChronoField.NANO_OF_SECOND;
041import static org.threeten.bp.temporal.ChronoUnit.NANOS;
042
043import java.io.DataInput;
044import java.io.DataOutput;
045import java.io.IOException;
046import java.io.InvalidObjectException;
047import java.io.ObjectStreamException;
048import java.io.Serializable;
049import java.util.Objects;
050
051import org.threeten.bp.format.DateTimeFormatters;
052import org.threeten.bp.format.DateTimeParseException;
053import org.threeten.bp.jdk8.DefaultInterfaceTemporalAccessor;
054import org.threeten.bp.jdk8.Jdk8Methods;
055import org.threeten.bp.temporal.ChronoField;
056import org.threeten.bp.temporal.ChronoUnit;
057import org.threeten.bp.temporal.Temporal;
058import org.threeten.bp.temporal.TemporalAccessor;
059import org.threeten.bp.temporal.TemporalAdder;
060import org.threeten.bp.temporal.TemporalAdjuster;
061import org.threeten.bp.temporal.TemporalField;
062import org.threeten.bp.temporal.TemporalQueries;
063import org.threeten.bp.temporal.TemporalQuery;
064import org.threeten.bp.temporal.TemporalSubtractor;
065import org.threeten.bp.temporal.TemporalUnit;
066import org.threeten.bp.temporal.ValueRange;
067
068/**
069 * An instantaneous point on the time-line.
070 * <p>
071 * This class models a single instantaneous point on the time-line.
072 * This might be used to record event time-stamps in the application.
073 * <p>
074 * For practicality, the instant is stored with some constraints.
075 * The measurable time-line is restricted to the number of seconds that can be held
076 * in a {@code long}. This is greater than the current estimated age of the universe.
077 * The instant is stored to nanosecond resolution.
078 * <p>
079 * The range of an instant requires the storage of a number larger than a {@code long}.
080 * To achieve this, the class stores a {@code long} representing epoch-seconds and an
081 * {@code int} representing nanosecond-of-second, which will always be between 0 and 999,999,999.
082 * The epoch-seconds are measured from the standard Java epoch of {@code 1970-01-01T00:00:00Z}
083 * where instants after the epoch have positive values, and earlier instants have negative values.
084 * For both the epoch-second and nanosecond parts, a larger value is always later on the time-line
085 * than a smaller value.
086 *
087 * <h3>Time-scale</h3>
088 * <p>
089 * The length of the solar day is the standard way that humans measure time.
090 * This has traditionally been subdivided into 24 hours of 60 minutes of 60 seconds,
091 * forming a 86400 second day.
092 * <p>
093 * Modern timekeeping is based on atomic clocks which precisely define an SI second
094 * relative to the transitions of a Caesium atom. The length of an SI second was defined
095 * to be very close to the 86400th fraction of a day.
096 * <p>
097 * Unfortunately, as the Earth rotates the length of the day varies.
098 * In addition, over time the average length of the day is getting longer as the Earth slows.
099 * 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="http://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 for all date-time classes supplied by JSR-310.
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 */
157public 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 minimum supported {@code Instant}, '-1000000000-01-01T00:00Z'.
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, 999_999_999);
195
196    /**
197     * Serialization version.
198     */
199    private static final long serialVersionUID = -665713676816604388L;
200    /**
201     * Constant for nanos per second.
202     */
203    private static final int NANOS_PER_SECOND = 1000_000_000;
204
205    /**
206     * The number of seconds from the epoch of 1970-01-01T00:00:00Z.
207     */
208    private final long seconds;
209    /**
210     * The number of nanoseconds, later along the time-line, from the seconds field.
211     * This is always positive, and never exceeds 999,999,999.
212     */
213    private final int nanos;
214
215    //-----------------------------------------------------------------------
216    /**
217     * Obtains the current instant from the system clock.
218     * <p>
219     * This will query the {@link Clock#systemUTC() system UTC clock} to
220     * obtain the current instant.
221     * <p>
222     * Using this method will prevent the ability to use an alternate time-source for
223     * testing because the clock is effectively hard-coded.
224     *
225     * @return the current instant using the system clock, not null
226     */
227    public static Instant now() {
228        return Clock.systemUTC().instant();
229    }
230
231    /**
232     * Obtains the current instant from the specified clock.
233     * <p>
234     * This will query the specified clock to obtain the current time.
235     * <p>
236     * Using this method allows the use of an alternate clock for testing.
237     * The alternate clock may be introduced using {@link Clock dependency injection}.
238     *
239     * @param clock  the clock to use, not null
240     * @return the current instant, not null
241     */
242    public static Instant now(Clock clock) {
243        Objects.requireNonNull(clock, "clock");
244        return clock.instant();
245    }
246
247    //-----------------------------------------------------------------------
248    /**
249     * Obtains an instance of {@code Instant} using seconds from the
250     * epoch of 1970-01-01T00:00:00Z.
251     * <p>
252     * The nanosecond field is set to zero.
253     *
254     * @param epochSecond  the number of seconds from 1970-01-01T00:00:00Z
255     * @return an instant, not null
256     * @throws DateTimeException if the instant exceeds the maximum or minimum instant
257     */
258    public static Instant ofEpochSecond(long epochSecond) {
259        return create(epochSecond, 0);
260    }
261
262    /**
263     * Obtains an instance of {@code Instant} using seconds from the
264     * epoch of 1970-01-01T00:00:00Z and nanosecond fraction of second.
265     * <p>
266     * This method allows an arbitrary number of nanoseconds to be passed in.
267     * The factory will alter the values of the second and nanosecond in order
268     * to ensure that the stored nanosecond is in the range 0 to 999,999,999.
269     * For example, the following will result in the exactly the same instant:
270     * <pre>
271     *  Instant.ofSeconds(3, 1);
272     *  Instant.ofSeconds(4, -999_999_999);
273     *  Instant.ofSeconds(2, 1000_000_001);
274     * </pre>
275     *
276     * @param epochSecond  the number of seconds from 1970-01-01T00:00:00Z
277     * @param nanoAdjustment  the nanosecond adjustment to the number of seconds, positive or negative
278     * @return an instant, not null
279     * @throws DateTimeException if the instant exceeds the maximum or minimum instant
280     * @throws ArithmeticException if numeric overflow occurs
281     */
282    public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment) {
283        long secs = Jdk8Methods.safeAdd(epochSecond, Jdk8Methods.floorDiv(nanoAdjustment, NANOS_PER_SECOND));
284        int nos = Jdk8Methods.floorMod(nanoAdjustment, NANOS_PER_SECOND);
285        return create(secs, nos);
286    }
287
288    /**
289     * Obtains an instance of {@code Instant} using milliseconds from the
290     * epoch of 1970-01-01T00:00:00Z.
291     * <p>
292     * The seconds and nanoseconds are extracted from the specified milliseconds.
293     *
294     * @param epochMilli  the number of milliseconds from 1970-01-01T00:00:00Z
295     * @return an instant, not null
296     * @throws DateTimeException if the instant exceeds the maximum or minimum instant
297     */
298    public static Instant ofEpochMilli(long epochMilli) {
299        long secs = Jdk8Methods.floorDiv(epochMilli, 1000);
300        int mos = Jdk8Methods.floorMod(epochMilli, 1000);
301        return create(secs, mos * 1000_000);
302    }
303
304    //-----------------------------------------------------------------------
305    /**
306     * Obtains an instance of {@code Instant} from a temporal object.
307     * <p>
308     * A {@code TemporalAccessor} represents some form of date and time information.
309     * This factory converts the arbitrary temporal object to an instance of {@code Instant}.
310     * <p>
311     * The conversion extracts the {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS}
312     * and {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} fields.
313     * <p>
314     * This method matches the signature of the functional interface {@link TemporalQuery}
315     * allowing it to be used as a query via method reference, {@code Instant::from}.
316     *
317     * @param temporal  the temporal object to convert, not null
318     * @return the instant, not null
319     * @throws DateTimeException if unable to convert to an {@code Instant}
320     */
321    public static Instant from(TemporalAccessor temporal) {
322        long instantSecs = temporal.getLong(INSTANT_SECONDS);
323        int nanoOfSecond = temporal.get(NANO_OF_SECOND);
324        return Instant.ofEpochSecond(instantSecs, nanoOfSecond);
325    }
326
327    //-----------------------------------------------------------------------
328    /**
329     * Obtains an instance of {@code Instant} from a text string such as
330     * {@code 2007-12-03T10:15:30:00}.
331     * <p>
332     * The string must represent a valid instant in UTC and is parsed using
333     * {@link DateTimeFormatters#isoInstant()}.
334     *
335     * @param text  the text to parse, not null
336     * @return the parsed instant, not null
337     * @throws DateTimeParseException if the text cannot be parsed
338     */
339    public static Instant parse(final CharSequence text) {
340        return DateTimeFormatters.isoInstant().parse(text, Instant.class);
341    }
342
343    //-----------------------------------------------------------------------
344    /**
345     * Obtains an instance of {@code Instant} using seconds and nanoseconds.
346     *
347     * @param seconds  the length of the duration in seconds
348     * @param nanoOfSecond  the nano-of-second, from 0 to 999,999,999
349     * @throws DateTimeException if the instant exceeds the maximum or minimum instant
350     */
351    private static Instant create(long seconds, int nanoOfSecond) {
352        if ((seconds | nanoOfSecond) == 0) {
353            return EPOCH;
354        }
355        if (seconds < MIN_SECOND || seconds > MAX_SECOND) {
356            throw new DateTimeException("Instant exceeds minimum or maximum instant");
357        }
358        return new Instant(seconds, nanoOfSecond);
359    }
360
361    /**
362     * Constructs an instance of {@code Instant} using seconds from the epoch of
363     * 1970-01-01T00:00:00Z and nanosecond fraction of second.
364     *
365     * @param epochSecond  the number of seconds from 1970-01-01T00:00:00Z
366     * @param nanos  the nanoseconds within the second, must be positive
367     */
368    private Instant(long epochSecond, int nanos) {
369        super();
370        this.seconds = epochSecond;
371        this.nanos = nanos;
372    }
373
374    //-----------------------------------------------------------------------
375    /**
376     * Checks if the specified field is supported.
377     * <p>
378     * This checks if this instant can be queried for the specified field.
379     * If false, then calling the {@link #range(TemporalField) range} and
380     * {@link #get(TemporalField) get} methods will throw an exception.
381     * <p>
382     * If the field is a {@link ChronoField} then the query is implemented here.
383     * The supported fields are:
384     * <ul>
385     * <li>{@code NANO_OF_SECOND}
386     * <li>{@code MICRO_OF_SECOND}
387     * <li>{@code MILLI_OF_SECOND}
388     * <li>{@code INSTANT_SECONDS}
389     * </ul>
390     * All other {@code ChronoField} instances will return false.
391     * <p>
392     * If the field is not a {@code ChronoField}, then the result of this method
393     * is obtained by invoking {@code TemporalField.doIsSupported(TemporalAccessor)}
394     * passing {@code this} as the argument.
395     * Whether the field is supported is determined by the field.
396     *
397     * @param field  the field to check, null returns false
398     * @return true if the field is supported on this instant, false if not
399     */
400    @Override
401    public boolean isSupported(TemporalField field) {
402        if (field instanceof ChronoField) {
403            return field == INSTANT_SECONDS || field == NANO_OF_SECOND || field == MICRO_OF_SECOND || field == MILLI_OF_SECOND;
404        }
405        return field != null && field.doIsSupported(this);
406    }
407
408    /**
409     * Gets the range of valid values for the specified field.
410     * <p>
411     * The range object expresses the minimum and maximum valid values for a field.
412     * This instant is used to enhance the accuracy of the returned range.
413     * If it is not possible to return the range, because the field is not supported
414     * or for some other reason, an exception is thrown.
415     * <p>
416     * If the field is a {@link ChronoField} then the query is implemented here.
417     * The {@link #isSupported(TemporalField) supported fields} will return
418     * appropriate range instances.
419     * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
420     * <p>
421     * If the field is not a {@code ChronoField}, then the result of this method
422     * is obtained by invoking {@code TemporalField.doRange(TemporalAccessor)}
423     * passing {@code this} as the argument.
424     * Whether the range can be obtained is determined by the field.
425     *
426     * @param field  the field to query the range for, not null
427     * @return the range of valid values for the field, not null
428     * @throws DateTimeException if the range for the field cannot be obtained
429     */
430    @Override  // override for Javadoc
431    public ValueRange range(TemporalField field) {
432        return super.range(field);
433    }
434
435    /**
436     * Gets the value of the specified field from this instant as an {@code int}.
437     * <p>
438     * This queries this instant for the value for the specified field.
439     * The returned value will always be within the valid range of values for the field.
440     * If it is not possible to return the value, because the field is not supported
441     * or for some other reason, an exception is thrown.
442     * <p>
443     * If the field is a {@link ChronoField} then the query is implemented here.
444     * The {@link #isSupported(TemporalField) supported fields} will return valid
445     * values based on this date-time, except {@code INSTANT_SECONDS} which is too
446     * large to fit in an {@code int} and throws a {@code DateTimeException}.
447     * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
448     * <p>
449     * If the field is not a {@code ChronoField}, then the result of this method
450     * is obtained by invoking {@code TemporalField.doGet(TemporalAccessor)}
451     * passing {@code this} as the argument. Whether the value can be obtained,
452     * and what the value represents, is determined by the field.
453     *
454     * @param field  the field to get, not null
455     * @return the value for the field
456     * @throws DateTimeException if a value for the field cannot be obtained
457     * @throws ArithmeticException if numeric overflow occurs
458     */
459    @Override  // override for Javadoc and performance
460    public int get(TemporalField field) {
461        if (field instanceof ChronoField) {
462            switch ((ChronoField) field) {
463                case NANO_OF_SECOND: return nanos;
464                case MICRO_OF_SECOND: return nanos / 1000;
465                case MILLI_OF_SECOND: return nanos / 1000_000;
466                case INSTANT_SECONDS: INSTANT_SECONDS.checkValidIntValue(seconds);
467            }
468            throw new DateTimeException("Unsupported field: " + field.getName());
469        }
470        return range(field).checkValidIntValue(field.doGet(this), field);
471    }
472
473    /**
474     * Gets the value of the specified field from this instant as a {@code long}.
475     * <p>
476     * This queries this instant for the value for the specified field.
477     * If it is not possible to return the value, because the field is not supported
478     * or for some other reason, an exception is thrown.
479     * <p>
480     * If the field is a {@link ChronoField} then the query is implemented here.
481     * The {@link #isSupported(TemporalField) supported fields} will return valid
482     * values based on this date-time.
483     * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
484     * <p>
485     * If the field is not a {@code ChronoField}, then the result of this method
486     * is obtained by invoking {@code TemporalField.doGet(TemporalAccessor)}
487     * passing {@code this} as the argument. Whether the value can be obtained,
488     * and what the value represents, is determined by the field.
489     *
490     * @param field  the field to get, not null
491     * @return the value for the field
492     * @throws DateTimeException if a value for the field cannot be obtained
493     * @throws ArithmeticException if numeric overflow occurs
494     */
495    @Override
496    public long getLong(TemporalField field) {
497        if (field instanceof ChronoField) {
498            switch ((ChronoField) field) {
499                case NANO_OF_SECOND: return nanos;
500                case MICRO_OF_SECOND: return nanos / 1000;
501                case MILLI_OF_SECOND: return nanos / 1000_000;
502                case INSTANT_SECONDS: return seconds;
503            }
504            throw new DateTimeException("Unsupported field: " + field.getName());
505        }
506        return field.doGet(this);
507    }
508
509    //-----------------------------------------------------------------------
510    /**
511     * Gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z.
512     * <p>
513     * The epoch second count is a simple incrementing count of seconds where
514     * second 0 is 1970-01-01T00:00:00Z.
515     * The nanosecond part of the day is returned by {@code getNanosOfSecond}.
516     *
517     * @return the seconds from the epoch of 1970-01-01T00:00:00Z
518     */
519    public long getEpochSecond() {
520        return seconds;
521    }
522
523    /**
524     * Gets the number of nanoseconds, later along the time-line, from the start
525     * of the second.
526     * <p>
527     * The nanosecond-of-second value measures the total number of nanoseconds from
528     * the second returned by {@code getEpochSecond}.
529     *
530     * @return the nanoseconds within the second, always positive, never exceeds 999,999,999
531     */
532    public int getNano() {
533        return nanos;
534    }
535
536    //-------------------------------------------------------------------------
537    /**
538     * Returns an adjusted copy of this instant.
539     * <p>
540     * This returns a new {@code Instant}, based on this one, with the date adjusted.
541     * The adjustment takes place using the specified adjuster strategy object.
542     * Read the documentation of the adjuster to understand what adjustment will be made.
543     * <p>
544     * The result of this method is obtained by invoking the
545     * {@link TemporalAdjuster#adjustInto(Temporal)} method on the
546     * specified adjuster passing {@code this} as the argument.
547     * <p>
548     * This instance is immutable and unaffected by this method call.
549     *
550     * @param adjuster the adjuster to use, not null
551     * @return an {@code Instant} based on {@code this} with the adjustment made, not null
552     * @throws DateTimeException if the adjustment cannot be made
553     * @throws ArithmeticException if numeric overflow occurs
554     */
555    @Override
556    public Instant with(TemporalAdjuster adjuster) {
557        return (Instant) adjuster.adjustInto(this);
558    }
559
560    /**
561     * Returns a copy of this instant with the specified field set to a new value.
562     * <p>
563     * This returns a new {@code Instant}, based on this one, with the value
564     * for the specified field changed.
565     * If it is not possible to set the value, because the field is not supported or for
566     * some other reason, an exception is thrown.
567     * <p>
568     * If the field is a {@link ChronoField} then the adjustment is implemented here.
569     * The supported fields behave as follows:
570     * <ul>
571     * <li>{@code NANO_OF_SECOND} -
572     *  Returns an {@code Instant} with the specified nano-of-second.
573     *  The epoch-second will be unchanged.
574     * <li>{@code MICRO_OF_SECOND} -
575     *  Returns an {@code Instant} with the nano-of-second replaced by the specified
576     *  micro-of-second multiplied by 1,000. The epoch-second will be unchanged.
577     * <li>{@code MILLI_OF_SECOND} -
578     *  Returns an {@code Instant} with the nano-of-second replaced by the specified
579     *  milli-of-second multiplied by 1,000,000. The epoch-second will be unchanged.
580     * <li>{@code INSTANT_SECONDS} -
581     *  Returns an {@code Instant} with the specified epoch-second.
582     *  The nano-of-second will be unchanged.
583     * </ul>
584     * <p>
585     * In all cases, if the new value is outside the valid range of values for the field
586     * then a {@code DateTimeException} will be thrown.
587     * <p>
588     * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
589     * <p>
590     * If the field is not a {@code ChronoField}, then the result of this method
591     * is obtained by invoking {@code TemporalField.doWith(Temporal, long)}
592     * passing {@code this} as the argument. In this case, the field determines
593     * whether and how to adjust the instant.
594     * <p>
595     * This instance is immutable and unaffected by this method call.
596     *
597     * @param field  the field to set in the result, not null
598     * @param newValue  the new value of the field in the result
599     * @return an {@code Instant} based on {@code this} with the specified field set, not null
600     * @throws DateTimeException if the field cannot be set
601     * @throws ArithmeticException if numeric overflow occurs
602     */
603    @Override
604    public Instant with(TemporalField field, long newValue) {
605        if (field instanceof ChronoField) {
606            ChronoField f = (ChronoField) field;
607            f.checkValidValue(newValue);
608            switch (f) {
609                case MILLI_OF_SECOND: {
610                    int nval = (int) newValue * 1000_000;
611                    return (nval != nanos ? create(seconds, nval) : this);
612                }
613                case MICRO_OF_SECOND: {
614                    int nval = (int) newValue * 1000;
615                    return (nval != nanos ? create(seconds, nval) : this);
616                }
617                case NANO_OF_SECOND: return (newValue != nanos ? create(seconds, (int) newValue) : this);
618                case INSTANT_SECONDS: return (newValue != seconds ? create(newValue, nanos) : this);
619            }
620            throw new DateTimeException("Unsupported field: " + field.getName());
621        }
622        return field.doWith(this, newValue);
623    }
624
625    //-----------------------------------------------------------------------
626    /**
627     * {@inheritDoc}
628     * @throws DateTimeException {@inheritDoc}
629     * @throws ArithmeticException {@inheritDoc}
630     */
631    @Override
632    public Instant plus(TemporalAdder adder) {
633        return (Instant) adder.addTo(this);
634    }
635
636    /**
637     * {@inheritDoc}
638     * @throws DateTimeException {@inheritDoc}
639     * @throws ArithmeticException {@inheritDoc}
640     */
641    @Override
642    public Instant plus(long amountToAdd, TemporalUnit unit) {
643        if (unit instanceof ChronoUnit) {
644            switch ((ChronoUnit) unit) {
645                case NANOS: return plusNanos(amountToAdd);
646                case MICROS: return plus(amountToAdd / 1000_000, (amountToAdd % 1000_000) * 1000);
647                case MILLIS: return plusMillis(amountToAdd);
648                case SECONDS: return plusSeconds(amountToAdd);
649                case MINUTES: return plusSeconds(Jdk8Methods.safeMultiply(amountToAdd, SECONDS_PER_MINUTE));
650                case HOURS: return plusSeconds(Jdk8Methods.safeMultiply(amountToAdd, SECONDS_PER_HOUR));
651                case HALF_DAYS: return plusSeconds(Jdk8Methods.safeMultiply(amountToAdd, SECONDS_PER_DAY / 2));
652                case DAYS: return plusSeconds(Jdk8Methods.safeMultiply(amountToAdd, SECONDS_PER_DAY));
653            }
654            throw new DateTimeException("Unsupported unit: " + unit.getName());
655        }
656        return unit.doPlus(this, amountToAdd);
657    }
658
659    //-----------------------------------------------------------------------
660    /**
661     * Returns a copy of this instant with the specified duration in seconds added.
662     * <p>
663     * This instance is immutable and unaffected by this method call.
664     *
665     * @param secondsToAdd  the seconds to add, positive or negative
666     * @return an {@code Instant} based on this instant with the specified seconds added, not null
667     * @throws DateTimeException if the result exceeds the maximum or minimum instant
668     * @throws ArithmeticException if numeric overflow occurs
669     */
670    public Instant plusSeconds(long secondsToAdd) {
671        return plus(secondsToAdd, 0);
672    }
673
674    /**
675     * Returns a copy of this instant with the specified duration in milliseconds added.
676     * <p>
677     * This instance is immutable and unaffected by this method call.
678     *
679     * @param millisToAdd  the milliseconds to add, positive or negative
680     * @return an {@code Instant} based on this instant with the specified milliseconds added, not null
681     * @throws DateTimeException if the result exceeds the maximum or minimum instant
682     * @throws ArithmeticException if numeric overflow occurs
683     */
684    public Instant plusMillis(long millisToAdd) {
685        return plus(millisToAdd / 1000, (millisToAdd % 1000) * 1000_000);
686    }
687
688    /**
689     * Returns a copy of this instant with the specified duration in nanoseconds added.
690     * <p>
691     * This instance is immutable and unaffected by this method call.
692     *
693     * @param nanosToAdd  the nanoseconds to add, positive or negative
694     * @return an {@code Instant} based on this instant with the specified nanoseconds added, not null
695     * @throws DateTimeException if the result exceeds the maximum or minimum instant
696     * @throws ArithmeticException if numeric overflow occurs
697     */
698    public Instant plusNanos(long nanosToAdd) {
699        return plus(0, nanosToAdd);
700    }
701
702    /**
703     * Returns a copy of this instant with the specified duration added.
704     * <p>
705     * This instance is immutable and unaffected by this method call.
706     *
707     * @param secondsToAdd  the seconds to add, positive or negative
708     * @param nanosToAdd  the nanos to add, positive or negative
709     * @return an {@code Instant} based on this instant with the specified seconds added, not null
710     * @throws DateTimeException if the result exceeds the maximum or minimum instant
711     * @throws ArithmeticException if numeric overflow occurs
712     */
713    private Instant plus(long secondsToAdd, long nanosToAdd) {
714        if ((secondsToAdd | nanosToAdd) == 0) {
715            return this;
716        }
717        long epochSec = Jdk8Methods.safeAdd(seconds, secondsToAdd);
718        epochSec = Jdk8Methods.safeAdd(epochSec, nanosToAdd / NANOS_PER_SECOND);
719        nanosToAdd = nanosToAdd % NANOS_PER_SECOND;
720        long nanoAdjustment = nanos + nanosToAdd;  // safe int+NANOS_PER_SECOND
721        return ofEpochSecond(epochSec, nanoAdjustment);
722    }
723
724    //-----------------------------------------------------------------------
725    /**
726     * {@inheritDoc}
727     * @throws DateTimeException {@inheritDoc}
728     * @throws ArithmeticException {@inheritDoc}
729     */
730    @Override
731    public Instant minus(TemporalSubtractor subtractor) {
732        return (Instant) subtractor.subtractFrom(this);
733    }
734
735    /**
736     * {@inheritDoc}
737     * @throws DateTimeException {@inheritDoc}
738     * @throws ArithmeticException {@inheritDoc}
739     */
740    @Override
741    public Instant minus(long amountToSubtract, TemporalUnit unit) {
742        return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
743    }
744
745    //-----------------------------------------------------------------------
746    /**
747     * Returns a copy of this instant with the specified duration in seconds subtracted.
748     * <p>
749     * This instance is immutable and unaffected by this method call.
750     *
751     * @param secondsToSubtract  the seconds to subtract, positive or negative
752     * @return an {@code Instant} based on this instant with the specified seconds subtracted, not null
753     * @throws DateTimeException if the result exceeds the maximum or minimum instant
754     * @throws ArithmeticException if numeric overflow occurs
755     */
756    public Instant minusSeconds(long secondsToSubtract) {
757        if (secondsToSubtract == Long.MIN_VALUE) {
758            return plusSeconds(Long.MAX_VALUE).plusSeconds(1);
759        }
760        return plusSeconds(-secondsToSubtract);
761    }
762
763    /**
764     * Returns a copy of this instant with the specified duration in milliseconds subtracted.
765     * <p>
766     * This instance is immutable and unaffected by this method call.
767     *
768     * @param millisToSubtract  the milliseconds to subtract, positive or negative
769     * @return an {@code Instant} based on this instant with the specified milliseconds subtracted, not null
770     * @throws DateTimeException if the result exceeds the maximum or minimum instant
771     * @throws ArithmeticException if numeric overflow occurs
772     */
773    public Instant minusMillis(long millisToSubtract) {
774        if (millisToSubtract == Long.MIN_VALUE) {
775            return plusMillis(Long.MAX_VALUE).plusMillis(1);
776        }
777        return plusMillis(-millisToSubtract);
778    }
779
780    /**
781     * Returns a copy of this instant with the specified duration in nanoseconds subtracted.
782     * <p>
783     * This instance is immutable and unaffected by this method call.
784     *
785     * @param nanosToSubtract  the nanoseconds to subtract, positive or negative
786     * @return an {@code Instant} based on this instant with the specified nanoseconds subtracted, not null
787     * @throws DateTimeException if the result exceeds the maximum or minimum instant
788     * @throws ArithmeticException if numeric overflow occurs
789     */
790    public Instant minusNanos(long nanosToSubtract) {
791        if (nanosToSubtract == Long.MIN_VALUE) {
792            return plusNanos(Long.MAX_VALUE).plusNanos(1);
793        }
794        return plusNanos(-nanosToSubtract);
795    }
796
797    //-------------------------------------------------------------------------
798    /**
799     * Queries this instant using the specified query.
800     * <p>
801     * This queries this instant using the specified query strategy object.
802     * The {@code TemporalQuery} object defines the logic to be used to
803     * obtain the result. Read the documentation of the query to understand
804     * what the result of this method will be.
805     * <p>
806     * The result of this method is obtained by invoking the
807     * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
808     * specified query passing {@code this} as the argument.
809     *
810     * @param <R> the type of the result
811     * @param query  the query to invoke, not null
812     * @return the query result, null may be returned (defined by the query)
813     * @throws DateTimeException if unable to query (defined by the query)
814     * @throws ArithmeticException if numeric overflow occurs (defined by the query)
815     */
816    @SuppressWarnings("unchecked")
817    @Override
818    public <R> R query(TemporalQuery<R> query) {
819        if (query == TemporalQueries.precision()) {
820            return (R) NANOS;
821        }
822        // inline TemporalAccessor.super.query(query) as an optimization
823        if (query == TemporalQueries.chrono() || query == TemporalQueries.zoneId() ||
824                query == TemporalQueries.zone() || query == TemporalQueries.offset()) {
825            return null;
826        }
827        return query.queryFrom(this);
828    }
829
830    /**
831     * Adjusts the specified temporal object to have this instant.
832     * <p>
833     * This returns a temporal object of the same observable type as the input
834     * with the instant changed to be the same as this.
835     * <p>
836     * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
837     * twice, passing {@link ChronoField#INSTANT_SECONDS} and
838     * {@link ChronoField#NANO_OF_SECOND} as the fields.
839     * <p>
840     * In most cases, it is clearer to reverse the calling pattern by using
841     * {@link Temporal#with(TemporalAdjuster)}:
842     * <pre>
843     *   // these two lines are equivalent, but the second approach is recommended
844     *   temporal = thisInstant.adjustInto(temporal);
845     *   temporal = temporal.with(thisInstant);
846     * </pre>
847     * <p>
848     * This instance is immutable and unaffected by this method call.
849     *
850     * @param temporal  the target object to be adjusted, not null
851     * @return the adjusted object, not null
852     * @throws DateTimeException if unable to make the adjustment
853     * @throws ArithmeticException if numeric overflow occurs
854     */
855    @Override
856    public Temporal adjustInto(Temporal temporal) {
857        return temporal.with(INSTANT_SECONDS, seconds).with(NANO_OF_SECOND, nanos);
858    }
859
860    /**
861     * Calculates the period between this instant and another instant in
862     * terms of the specified unit.
863     * <p>
864     * This calculates the period between two instants in terms of a single unit.
865     * The start and end points are {@code this} and the specified instant.
866     * The result will be negative if the end is before the start.
867     * The calculation returns a whole number, representing the number of
868     * complete units between the two instants.
869     * The {@code Temporal} passed to this method must be an {@code Instant}.
870     * For example, the period in days between two dates can be calculated
871     * using {@code startInstant.periodUntil(endInstant, SECONDS)}.
872     * <p>
873     * This method operates in association with {@link TemporalUnit#between}.
874     * The result of this method is a {@code long} representing the amount of
875     * the specified unit. By contrast, the result of {@code between} is an
876     * object that can be used directly in addition/subtraction:
877     * <pre>
878     *   long period = start.periodUntil(end, SECONDS);   // this method
879     *   dateTime.plus(SECONDS.between(start, end));      // use in plus/minus
880     * </pre>
881     * <p>
882     * The calculation is implemented in this method for {@link ChronoUnit}.
883     * The units {@code NANOS}, {@code MICROS}, {@code MILLIS}, {@code SECONDS},
884     * {@code MINUTES}, {@code HOURS}, {@code HALF_DAYS} and {@code DAYS}
885     * are supported. Other {@code ChronoUnit} values will throw an exception.
886     * <p>
887     * If the unit is not a {@code ChronoUnit}, then the result of this method
888     * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
889     * passing {@code this} as the first argument and the input temporal as
890     * the second argument.
891     * <p>
892     * This instance is immutable and unaffected by this method call.
893     *
894     * @param endInstant  the end date, which must be a {@code LocalDate}, not null
895     * @param unit  the unit to measure the period in, not null
896     * @return the amount of the period between this date and the end date
897     * @throws DateTimeException if the period cannot be calculated
898     * @throws ArithmeticException if numeric overflow occurs
899     */
900    @Override
901    public long periodUntil(Temporal endInstant, TemporalUnit unit) {
902        if (endInstant instanceof Instant == false) {
903            Objects.requireNonNull(endInstant, "endInstant");
904            throw new DateTimeException("Unable to calculate period between objects of two different types");
905        }
906        Instant end = (Instant) endInstant;
907        if (unit instanceof ChronoUnit) {
908            ChronoUnit f = (ChronoUnit) unit;
909            switch (f) {
910                case NANOS: return nanosUntil(end);
911                case MICROS: return nanosUntil(end) / 1000;
912                case MILLIS: return Jdk8Methods.safeSubtract(end.toEpochMilli(), toEpochMilli());
913                case SECONDS: return secondsUntil(end);
914                case MINUTES: return secondsUntil(end) / SECONDS_PER_MINUTE;
915                case HOURS: return secondsUntil(end) / SECONDS_PER_HOUR;
916                case HALF_DAYS: return secondsUntil(end) / (12 * SECONDS_PER_HOUR);
917                case DAYS: return secondsUntil(end) / (SECONDS_PER_DAY);
918            }
919            throw new DateTimeException("Unsupported unit: " + unit.getName());
920        }
921        return unit.between(this, endInstant).getAmount();
922    }
923
924    private long nanosUntil(Instant end) {
925        long secs = Jdk8Methods.safeMultiply(secondsUntil(end), NANOS_PER_SECOND);
926        return Jdk8Methods.safeAdd(secs, end.nanos - nanos);
927    }
928
929    private long secondsUntil(Instant end) {
930        return Jdk8Methods.safeSubtract(end.seconds, seconds);
931    }
932
933    //-----------------------------------------------------------------------
934    /**
935     * Converts this instant to the number of milliseconds from the epoch
936     * of 1970-01-01T00:00:00Z.
937     * <p>
938     * If this instant represents a point on the time-line too far in the future
939     * or past to fit in a {@code long} milliseconds, then an exception is thrown.
940     * <p>
941     * If this instant has greater than millisecond precision, then the conversion
942     * will drop any excess precision information as though the amount in nanoseconds
943     * was subject to integer division by one million.
944     *
945     * @return the number of milliseconds since the epoch of 1970-01-01T00:00:00Z
946     * @throws ArithmeticException if numeric overflow occurs
947     */
948    public long toEpochMilli() {
949        long millis = Jdk8Methods.safeMultiply(seconds, 1000);
950        return millis + nanos / 1000_000;
951    }
952
953    //-----------------------------------------------------------------------
954    /**
955     * Compares this instant to the specified instant.
956     * <p>
957     * The comparison is based on the time-line position of the instants.
958     * It is "consistent with equals", as defined by {@link Comparable}.
959     *
960     * @param otherInstant  the other instant to compare to, not null
961     * @return the comparator value, negative if less, positive if greater
962     * @throws NullPointerException if otherInstant is null
963     */
964    @Override
965    public int compareTo(Instant otherInstant) {
966        int cmp = Long.compare(seconds, otherInstant.seconds);
967        if (cmp != 0) {
968            return cmp;
969        }
970        return nanos - otherInstant.nanos;
971    }
972
973    /**
974     * Checks if this instant is after the specified instant.
975     * <p>
976     * The comparison is based on the time-line position of the instants.
977     *
978     * @param otherInstant  the other instant to compare to, not null
979     * @return true if this instant is after the specified instant
980     * @throws NullPointerException if otherInstant is null
981     */
982    public boolean isAfter(Instant otherInstant) {
983        return compareTo(otherInstant) > 0;
984    }
985
986    /**
987     * Checks if this instant is before the specified instant.
988     * <p>
989     * The comparison is based on the time-line position of the instants.
990     *
991     * @param otherInstant  the other instant to compare to, not null
992     * @return true if this instant is before the specified instant
993     * @throws NullPointerException if otherInstant is null
994     */
995    public boolean isBefore(Instant otherInstant) {
996        return compareTo(otherInstant) < 0;
997    }
998
999    //-----------------------------------------------------------------------
1000    /**
1001     * Checks if this instant is equal to the specified instant.
1002     * <p>
1003     * The comparison is based on the time-line position of the instants.
1004     *
1005     * @param otherInstant  the other instant, null returns false
1006     * @return true if the other instant is equal to this one
1007     */
1008    @Override
1009    public boolean equals(Object otherInstant) {
1010        if (this == otherInstant) {
1011            return true;
1012        }
1013        if (otherInstant instanceof Instant) {
1014            Instant other = (Instant) otherInstant;
1015            return this.seconds == other.seconds &&
1016                   this.nanos == other.nanos;
1017        }
1018        return false;
1019    }
1020
1021    /**
1022     * Returns a hash code for this instant.
1023     *
1024     * @return a suitable hash code
1025     */
1026    @Override
1027    public int hashCode() {
1028        return ((int) (seconds ^ (seconds >>> 32))) + 51 * nanos;
1029    }
1030
1031    //-----------------------------------------------------------------------
1032    /**
1033     * A string representation of this instant using ISO-8601 representation.
1034     * <p>
1035     * The format used is the same as {@link DateTimeFormatters#isoInstant()}.
1036     *
1037     * @return an ISO-8601 representation of this instant, not null
1038     */
1039    @Override
1040    public String toString() {
1041        return DateTimeFormatters.isoInstant().print(this);
1042    }
1043
1044    //-----------------------------------------------------------------------
1045    private Object writeReplace() {
1046        return new Ser(Ser.INSTANT_TYPE, this);
1047    }
1048
1049    /**
1050     * Defend against malicious streams.
1051     * @return never
1052     * @throws InvalidObjectException always
1053     */
1054    private Object readResolve() throws ObjectStreamException {
1055        throw new InvalidObjectException("Deserialization via serialization delegate");
1056    }
1057
1058    void writeExternal(DataOutput out) throws IOException {
1059        out.writeLong(seconds);
1060        out.writeInt(nanos);
1061    }
1062
1063    static Instant readExternal(DataInput in) throws IOException {
1064        long seconds = in.readLong();
1065        int nanos = in.readInt();
1066        return Instant.ofEpochSecond(seconds, nanos);
1067    }
1068
1069}