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