src/share/classes/java/time/Instant.java

Print this page




  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.SECONDS_PER_DAY;
  65 import static java.time.LocalTime.SECONDS_PER_HOUR;
  66 import static java.time.LocalTime.SECONDS_PER_MINUTE;
  67 import static java.time.temporal.ChronoField.INSTANT_SECONDS;
  68 import static java.time.temporal.ChronoField.MICRO_OF_SECOND;
  69 import static java.time.temporal.ChronoField.MILLI_OF_SECOND;
  70 import static java.time.temporal.ChronoField.NANO_OF_SECOND;
  71 import static java.time.temporal.ChronoUnit.NANOS;
  72 
  73 import java.io.DataInput;
  74 import java.io.DataOutput;
  75 import java.io.IOException;
  76 import java.io.InvalidObjectException;
  77 import java.io.ObjectStreamException;
  78 import java.io.Serializable;
  79 import java.time.format.DateTimeFormatters;
  80 import java.time.format.DateTimeParseException;
  81 import java.time.temporal.ChronoField;
  82 import java.time.temporal.ChronoUnit;
  83 import java.time.temporal.Queries;
  84 import java.time.temporal.Temporal;
  85 import java.time.temporal.TemporalAccessor;
  86 import java.time.temporal.TemporalAdder;
  87 import java.time.temporal.TemporalAdjuster;

  88 import java.time.temporal.TemporalField;
  89 import java.time.temporal.TemporalQuery;
  90 import java.time.temporal.TemporalSubtractor;
  91 import java.time.temporal.TemporalUnit;
  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.


 208      * The value is also chosen such that the value of the year fits in
 209      * an {@code int}.
 210      */
 211     public static final Instant MIN = Instant.ofEpochSecond(MIN_SECOND, 0);
 212     /**
 213      * The minimum supported {@code Instant}, '-1000000000-01-01T00:00Z'.
 214      * This could be used by an application as a "far future" instant.
 215      * <p>
 216      * This is one year later than the maximum {@code LocalDateTime}.
 217      * This provides sufficient values to handle the range of {@code ZoneOffset}
 218      * which affect the instant in addition to the local date-time.
 219      * The value is also chosen such that the value of the year fits in
 220      * an {@code int}.
 221      */
 222     public static final Instant MAX = Instant.ofEpochSecond(MAX_SECOND, 999_999_999);
 223 
 224     /**
 225      * Serialization version.
 226      */
 227     private static final long serialVersionUID = -665713676816604388L;
 228     /**
 229      * Constant for nanos per second.
 230      */
 231     private static final int NANOS_PER_SECOND = 1000_000_000;
 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.


 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      * A {@code TemporalAccessor} represents some form of date and time information.
 337      * This factory converts the arbitrary temporal object to an instance of {@code Instant}.

 338      * <p>
 339      * The conversion extracts the {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS}
 340      * and {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} fields.
 341      * <p>
 342      * This method matches the signature of the functional interface {@link TemporalQuery}
 343      * allowing it to be used as a query via method reference, {@code Instant::from}.
 344      *
 345      * @param temporal  the temporal object to convert, not null
 346      * @return the instant, not null
 347      * @throws DateTimeException if unable to convert to an {@code Instant}
 348      */
 349     public static Instant from(TemporalAccessor temporal) {
 350         long instantSecs = temporal.getLong(INSTANT_SECONDS);
 351         int nanoOfSecond = temporal.get(NANO_OF_SECOND);
 352         return Instant.ofEpochSecond(instantSecs, nanoOfSecond);
 353     }
 354 
 355     //-----------------------------------------------------------------------
 356     /**
 357      * Obtains an instance of {@code Instant} from a text string such as
 358      * {@code 2007-12-03T10:15:30:00}.
 359      * <p>
 360      * The string must represent a valid instant in UTC and is parsed using
 361      * {@link DateTimeFormatters#isoInstant()}.
 362      *
 363      * @param text  the text to parse, not null
 364      * @return the parsed instant, not null
 365      * @throws DateTimeParseException if the text cannot be parsed
 366      */
 367     public static Instant parse(final CharSequence text) {
 368         return DateTimeFormatters.isoInstant().parse(text, Instant::from);
 369     }
 370 
 371     //-----------------------------------------------------------------------
 372     /**
 373      * Obtains an instance of {@code Instant} using seconds and nanoseconds.
 374      *
 375      * @param seconds  the length of the duration in seconds
 376      * @param nanoOfSecond  the nano-of-second, from 0 to 999,999,999
 377      * @throws DateTimeException if the instant exceeds the maximum or minimum instant
 378      */
 379     private static Instant create(long seconds, int nanoOfSecond) {
 380         if ((seconds | nanoOfSecond) == 0) {
 381             return EPOCH;
 382         }
 383         if (seconds < MIN_SECOND || seconds > MAX_SECOND) {
 384             throw new DateTimeException("Instant exceeds minimum or maximum instant");
 385         }
 386         return new Instant(seconds, nanoOfSecond);
 387     }
 388 


 401 
 402     //-----------------------------------------------------------------------
 403     /**
 404      * Checks if the specified field is supported.
 405      * <p>
 406      * This checks if this instant can be queried for the specified field.
 407      * If false, then calling the {@link #range(TemporalField) range} and
 408      * {@link #get(TemporalField) get} methods will throw an exception.
 409      * <p>
 410      * If the field is a {@link ChronoField} then the query is implemented here.
 411      * The supported fields are:
 412      * <ul>
 413      * <li>{@code NANO_OF_SECOND}
 414      * <li>{@code MICRO_OF_SECOND}
 415      * <li>{@code MILLI_OF_SECOND}
 416      * <li>{@code INSTANT_SECONDS}
 417      * </ul>
 418      * All other {@code ChronoField} instances will return false.
 419      * <p>
 420      * If the field is not a {@code ChronoField}, then the result of this method
 421      * is obtained by invoking {@code TemporalField.doIsSupported(TemporalAccessor)}
 422      * passing {@code this} as the argument.
 423      * Whether the field is supported is determined by the field.
 424      *
 425      * @param field  the field to check, null returns false
 426      * @return true if the field is supported on this instant, false if not
 427      */
 428     @Override
 429     public boolean isSupported(TemporalField field) {
 430         if (field instanceof ChronoField) {
 431             return field == INSTANT_SECONDS || field == NANO_OF_SECOND || field == MICRO_OF_SECOND || field == MILLI_OF_SECOND;
 432         }
 433         return field != null && field.doIsSupported(this);
 434     }
 435 
 436     /**
 437      * Gets the range of valid values for the specified field.
 438      * <p>
 439      * The range object expresses the minimum and maximum valid values for a field.
 440      * This instant is used to enhance the accuracy of the returned range.
 441      * If it is not possible to return the range, because the field is not supported
 442      * or for some other reason, an exception is thrown.
 443      * <p>
 444      * If the field is a {@link ChronoField} then the query is implemented here.
 445      * The {@link #isSupported(TemporalField) supported fields} will return
 446      * appropriate range instances.
 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.doRange(TemporalAccessor)}
 451      * passing {@code this} as the argument.
 452      * Whether the range can be obtained is determined by the field.
 453      *
 454      * @param field  the field to query the range for, not null
 455      * @return the range of valid values for the field, not null
 456      * @throws DateTimeException if the range for the field cannot be obtained
 457      */
 458     @Override  // override for Javadoc
 459     public ValueRange range(TemporalField field) {
 460         return Temporal.super.range(field);
 461     }
 462 
 463     /**
 464      * Gets the value of the specified field from this instant as an {@code int}.
 465      * <p>
 466      * This queries this instant for the value for the specified field.
 467      * The returned value will always be within the valid range of values for the field.
 468      * If it is not possible to return the value, because the field is not supported
 469      * or for some other reason, an exception is thrown.
 470      * <p>
 471      * If the field is a {@link ChronoField} then the query is implemented here.
 472      * The {@link #isSupported(TemporalField) supported fields} will return valid
 473      * values based on this date-time, except {@code INSTANT_SECONDS} which is too
 474      * large to fit in an {@code int} and throws a {@code DateTimeException}.
 475      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 476      * <p>
 477      * If the field is not a {@code ChronoField}, then the result of this method
 478      * is obtained by invoking {@code TemporalField.doGet(TemporalAccessor)}
 479      * passing {@code this} as the argument. Whether the value can be obtained,
 480      * and what the value represents, is determined by the field.
 481      *
 482      * @param field  the field to get, not null
 483      * @return the value for the field
 484      * @throws DateTimeException if a value for the field cannot be obtained
 485      * @throws ArithmeticException if numeric overflow occurs
 486      */
 487     @Override  // override for Javadoc and performance
 488     public int get(TemporalField field) {
 489         if (field instanceof ChronoField) {
 490             switch ((ChronoField) field) {
 491                 case NANO_OF_SECOND: return nanos;
 492                 case MICRO_OF_SECOND: return nanos / 1000;
 493                 case MILLI_OF_SECOND: return nanos / 1000_000;
 494                 case INSTANT_SECONDS: INSTANT_SECONDS.checkValidIntValue(seconds);
 495             }
 496             throw new DateTimeException("Unsupported field: " + field.getName());
 497         }
 498         return range(field).checkValidIntValue(field.doGet(this), field);
 499     }
 500 
 501     /**
 502      * Gets the value of the specified field from this instant as a {@code long}.
 503      * <p>
 504      * This queries this instant for the value for the specified field.
 505      * If it is not possible to return the value, because the field is not supported
 506      * or for some other reason, an exception is thrown.
 507      * <p>
 508      * If the field is a {@link ChronoField} then the query is implemented here.
 509      * The {@link #isSupported(TemporalField) supported fields} will return valid
 510      * values based on this date-time.
 511      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 512      * <p>
 513      * If the field is not a {@code ChronoField}, then the result of this method
 514      * is obtained by invoking {@code TemporalField.doGet(TemporalAccessor)}
 515      * passing {@code this} as the argument. Whether the value can be obtained,
 516      * and what the value represents, is determined by the field.
 517      *
 518      * @param field  the field to get, not null
 519      * @return the value for the field
 520      * @throws DateTimeException if a value for the field cannot be obtained
 521      * @throws ArithmeticException if numeric overflow occurs
 522      */
 523     @Override
 524     public long getLong(TemporalField field) {
 525         if (field instanceof ChronoField) {
 526             switch ((ChronoField) field) {
 527                 case NANO_OF_SECOND: return nanos;
 528                 case MICRO_OF_SECOND: return nanos / 1000;
 529                 case MILLI_OF_SECOND: return nanos / 1000_000;
 530                 case INSTANT_SECONDS: return seconds;
 531             }
 532             throw new DateTimeException("Unsupported field: " + field.getName());
 533         }
 534         return field.doGet(this);
 535     }
 536 
 537     //-----------------------------------------------------------------------
 538     /**
 539      * Gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z.
 540      * <p>
 541      * The epoch second count is a simple incrementing count of seconds where
 542      * second 0 is 1970-01-01T00:00:00Z.
 543      * The nanosecond part of the day is returned by {@code getNanosOfSecond}.
 544      *
 545      * @return the seconds from the epoch of 1970-01-01T00:00:00Z
 546      */
 547     public long getEpochSecond() {
 548         return seconds;
 549     }
 550 
 551     /**
 552      * Gets the number of nanoseconds, later along the time-line, from the start
 553      * of the second.
 554      * <p>
 555      * The nanosecond-of-second value measures the total number of nanoseconds from
 556      * the second returned by {@code getEpochSecond}.
 557      *
 558      * @return the nanoseconds within the second, always positive, never exceeds 999,999,999
 559      */
 560     public int getNano() {
 561         return nanos;
 562     }
 563 
 564     //-------------------------------------------------------------------------
 565     /**
 566      * Returns an adjusted copy of this instant.
 567      * <p>
 568      * This returns a new {@code Instant}, based on this one, with the date adjusted.
 569      * The adjustment takes place using the specified adjuster strategy object.
 570      * Read the documentation of the adjuster to understand what adjustment will be made.
 571      * <p>
 572      * The result of this method is obtained by invoking the
 573      * {@link TemporalAdjuster#adjustInto(Temporal)} method on the
 574      * specified adjuster passing {@code this} as the argument.
 575      * <p>
 576      * This instance is immutable and unaffected by this method call.
 577      *
 578      * @param adjuster the adjuster to use, not null
 579      * @return an {@code Instant} based on {@code this} with the adjustment made, not null
 580      * @throws DateTimeException if the adjustment cannot be made
 581      * @throws ArithmeticException if numeric overflow occurs
 582      */
 583     @Override
 584     public Instant with(TemporalAdjuster adjuster) {
 585         return (Instant) adjuster.adjustInto(this);
 586     }
 587 
 588     /**
 589      * Returns a copy of this instant with the specified field set to a new value.
 590      * <p>
 591      * This returns a new {@code Instant}, based on this one, with the value
 592      * for the specified field changed.
 593      * If it is not possible to set the value, because the field is not supported or for
 594      * some other reason, an exception is thrown.
 595      * <p>
 596      * If the field is a {@link ChronoField} then the adjustment is implemented here.
 597      * The supported fields behave as follows:
 598      * <ul>
 599      * <li>{@code NANO_OF_SECOND} -
 600      *  Returns an {@code Instant} with the specified nano-of-second.
 601      *  The epoch-second will be unchanged.
 602      * <li>{@code MICRO_OF_SECOND} -
 603      *  Returns an {@code Instant} with the nano-of-second replaced by the specified
 604      *  micro-of-second multiplied by 1,000. The epoch-second will be unchanged.
 605      * <li>{@code MILLI_OF_SECOND} -
 606      *  Returns an {@code Instant} with the nano-of-second replaced by the specified
 607      *  milli-of-second multiplied by 1,000,000. The epoch-second will be unchanged.
 608      * <li>{@code INSTANT_SECONDS} -
 609      *  Returns an {@code Instant} with the specified epoch-second.
 610      *  The nano-of-second will be unchanged.
 611      * </ul>
 612      * <p>
 613      * In all cases, if the new value is outside the valid range of values for the field
 614      * then a {@code DateTimeException} will be thrown.
 615      * <p>
 616      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 617      * <p>
 618      * If the field is not a {@code ChronoField}, then the result of this method
 619      * is obtained by invoking {@code TemporalField.doWith(Temporal, long)}
 620      * passing {@code this} as the argument. In this case, the field determines
 621      * whether and how to adjust the instant.
 622      * <p>
 623      * This instance is immutable and unaffected by this method call.
 624      *
 625      * @param field  the field to set in the result, not null
 626      * @param newValue  the new value of the field in the result
 627      * @return an {@code Instant} based on {@code this} with the specified field set, not null
 628      * @throws DateTimeException if the field cannot be set
 629      * @throws ArithmeticException if numeric overflow occurs
 630      */
 631     @Override
 632     public Instant with(TemporalField field, long newValue) {
 633         if (field instanceof ChronoField) {
 634             ChronoField f = (ChronoField) field;
 635             f.checkValidValue(newValue);
 636             switch (f) {
 637                 case MILLI_OF_SECOND: {
 638                     int nval = (int) newValue * 1000_000;
 639                     return (nval != nanos ? create(seconds, nval) : this);
 640                 }
 641                 case MICRO_OF_SECOND: {
 642                     int nval = (int) newValue * 1000;
 643                     return (nval != nanos ? create(seconds, nval) : this);
 644                 }
 645                 case NANO_OF_SECOND: return (newValue != nanos ? create(seconds, (int) newValue) : this);
 646                 case INSTANT_SECONDS: return (newValue != seconds ? create(newValue, nanos) : this);
 647             }
 648             throw new DateTimeException("Unsupported field: " + field.getName());
 649         }
 650         return field.doWith(this, newValue);







































 651     }
 652 
 653     //-----------------------------------------------------------------------
 654     /**
 655      * {@inheritDoc}
 656      * @throws DateTimeException {@inheritDoc}
 657      * @throws ArithmeticException {@inheritDoc}















 658      */
 659     @Override
 660     public Instant plus(TemporalAdder adder) {
 661         return (Instant) adder.addTo(this);
 662     }
 663 
 664     /**
 665      * {@inheritDoc}
 666      * @throws DateTimeException {@inheritDoc}
 667      * @throws ArithmeticException {@inheritDoc}




















































 668      */
 669     @Override
 670     public Instant plus(long amountToAdd, TemporalUnit unit) {
 671         if (unit instanceof ChronoUnit) {
 672             switch ((ChronoUnit) unit) {
 673                 case NANOS: return plusNanos(amountToAdd);
 674                 case MICROS: return plus(amountToAdd / 1000_000, (amountToAdd % 1000_000) * 1000);
 675                 case MILLIS: return plusMillis(amountToAdd);
 676                 case SECONDS: return plusSeconds(amountToAdd);
 677                 case MINUTES: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_MINUTE));
 678                 case HOURS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_HOUR));
 679                 case HALF_DAYS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY / 2));
 680                 case DAYS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY));
 681             }
 682             throw new DateTimeException("Unsupported unit: " + unit.getName());
 683         }
 684         return unit.doPlus(this, amountToAdd);
 685     }
 686 
 687     //-----------------------------------------------------------------------
 688     /**
 689      * Returns a copy of this instant with the specified duration in seconds added.
 690      * <p>
 691      * This instance is immutable and unaffected by this method call.
 692      *
 693      * @param secondsToAdd  the seconds to add, positive or negative
 694      * @return an {@code Instant} based on this instant with the specified seconds 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 plusSeconds(long secondsToAdd) {
 699         return plus(secondsToAdd, 0);
 700     }
 701 
 702     /**
 703      * Returns a copy of this instant with the specified duration in milliseconds added.
 704      * <p>


 734      *
 735      * @param secondsToAdd  the seconds to add, positive or negative
 736      * @param nanosToAdd  the nanos to add, positive or negative
 737      * @return an {@code Instant} based on this instant with the specified seconds added, not null
 738      * @throws DateTimeException if the result exceeds the maximum or minimum instant
 739      * @throws ArithmeticException if numeric overflow occurs
 740      */
 741     private Instant plus(long secondsToAdd, long nanosToAdd) {
 742         if ((secondsToAdd | nanosToAdd) == 0) {
 743             return this;
 744         }
 745         long epochSec = Math.addExact(seconds, secondsToAdd);
 746         epochSec = Math.addExact(epochSec, nanosToAdd / NANOS_PER_SECOND);
 747         nanosToAdd = nanosToAdd % NANOS_PER_SECOND;
 748         long nanoAdjustment = nanos + nanosToAdd;  // safe int+NANOS_PER_SECOND
 749         return ofEpochSecond(epochSec, nanoAdjustment);
 750     }
 751 
 752     //-----------------------------------------------------------------------
 753     /**
 754      * {@inheritDoc}
 755      * @throws DateTimeException {@inheritDoc}
 756      * @throws ArithmeticException {@inheritDoc}















 757      */
 758     @Override
 759     public Instant minus(TemporalSubtractor subtractor) {
 760         return (Instant) subtractor.subtractFrom(this);
 761     }
 762 
 763     /**
 764      * {@inheritDoc}
 765      * @throws DateTimeException {@inheritDoc}
 766      * @throws ArithmeticException {@inheritDoc}













 767      */
 768     @Override
 769     public Instant minus(long amountToSubtract, TemporalUnit unit) {
 770         return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
 771     }
 772 
 773     //-----------------------------------------------------------------------
 774     /**
 775      * Returns a copy of this instant with the specified duration in seconds subtracted.
 776      * <p>
 777      * This instance is immutable and unaffected by this method call.
 778      *
 779      * @param secondsToSubtract  the seconds to subtract, positive or negative
 780      * @return an {@code Instant} based on this instant with the specified seconds subtracted, not null
 781      * @throws DateTimeException if the result exceeds the maximum or minimum instant
 782      * @throws ArithmeticException if numeric overflow occurs
 783      */
 784     public Instant minusSeconds(long secondsToSubtract) {
 785         if (secondsToSubtract == Long.MIN_VALUE) {
 786             return plusSeconds(Long.MAX_VALUE).plusSeconds(1);


 831      * obtain the result. Read the documentation of the query to understand
 832      * what the result of this method will be.
 833      * <p>
 834      * The result of this method is obtained by invoking the
 835      * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
 836      * specified query passing {@code this} as the argument.
 837      *
 838      * @param <R> the type of the result
 839      * @param query  the query to invoke, not null
 840      * @return the query result, null may be returned (defined by the query)
 841      * @throws DateTimeException if unable to query (defined by the query)
 842      * @throws ArithmeticException if numeric overflow occurs (defined by the query)
 843      */
 844     @SuppressWarnings("unchecked")
 845     @Override
 846     public <R> R query(TemporalQuery<R> query) {
 847         if (query == Queries.precision()) {
 848             return (R) NANOS;
 849         }
 850         // inline TemporalAccessor.super.query(query) as an optimization
 851         if (query == Queries.chrono() || query == Queries.zoneId() || query == Queries.zone() || query == Queries.offset()) {
 852             return null;
 853         }
 854         return query.queryFrom(this);
 855     }
 856 
 857     /**
 858      * Adjusts the specified temporal object to have this instant.
 859      * <p>
 860      * This returns a temporal object of the same observable type as the input
 861      * with the instant changed to be the same as this.
 862      * <p>
 863      * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
 864      * twice, passing {@link ChronoField#INSTANT_SECONDS} and
 865      * {@link ChronoField#NANO_OF_SECOND} as the fields.
 866      * <p>
 867      * In most cases, it is clearer to reverse the calling pattern by using
 868      * {@link Temporal#with(TemporalAdjuster)}:
 869      * <pre>
 870      *   // these two lines are equivalent, but the second approach is recommended
 871      *   temporal = thisInstant.adjustInto(temporal);


 928     public long periodUntil(Temporal endInstant, TemporalUnit unit) {
 929         if (endInstant instanceof Instant == false) {
 930             Objects.requireNonNull(endInstant, "endInstant");
 931             throw new DateTimeException("Unable to calculate period between objects of two different types");
 932         }
 933         Instant end = (Instant) endInstant;
 934         if (unit instanceof ChronoUnit) {
 935             ChronoUnit f = (ChronoUnit) unit;
 936             switch (f) {
 937                 case NANOS: return nanosUntil(end);
 938                 case MICROS: return nanosUntil(end) / 1000;
 939                 case MILLIS: return Math.subtractExact(end.toEpochMilli(), toEpochMilli());
 940                 case SECONDS: return secondsUntil(end);
 941                 case MINUTES: return secondsUntil(end) / SECONDS_PER_MINUTE;
 942                 case HOURS: return secondsUntil(end) / SECONDS_PER_HOUR;
 943                 case HALF_DAYS: return secondsUntil(end) / (12 * SECONDS_PER_HOUR);
 944                 case DAYS: return secondsUntil(end) / (SECONDS_PER_DAY);
 945             }
 946             throw new DateTimeException("Unsupported unit: " + unit.getName());
 947         }
 948         return unit.between(this, endInstant).getAmount();
 949     }
 950 
 951     private long nanosUntil(Instant end) {
 952         long secs = Math.multiplyExact(secondsUntil(end), NANOS_PER_SECOND);
 953         return Math.addExact(secs, end.nanos - nanos);
 954     }
 955 
 956     private long secondsUntil(Instant end) {
 957         return Math.subtractExact(end.seconds, seconds);
 958     }
 959 
 960     //-----------------------------------------------------------------------
 961     /**





































 962      * Converts this instant to the number of milliseconds from the epoch
 963      * of 1970-01-01T00:00:00Z.
 964      * <p>
 965      * If this instant represents a point on the time-line too far in the future
 966      * or past to fit in a {@code long} milliseconds, then an exception is thrown.
 967      * <p>
 968      * If this instant has greater than millisecond precision, then the conversion
 969      * will drop any excess precision information as though the amount in nanoseconds
 970      * was subject to integer division by one million.
 971      *
 972      * @return the number of milliseconds since the epoch of 1970-01-01T00:00:00Z
 973      * @throws ArithmeticException if numeric overflow occurs
 974      */
 975     public long toEpochMilli() {
 976         long millis = Math.multiplyExact(seconds, 1000);
 977         return millis + nanos / 1000_000;
 978     }
 979 
 980     //-----------------------------------------------------------------------
 981     /**


1042             return this.seconds == other.seconds &&
1043                    this.nanos == other.nanos;
1044         }
1045         return false;
1046     }
1047 
1048     /**
1049      * Returns a hash code for this instant.
1050      *
1051      * @return a suitable hash code
1052      */
1053     @Override
1054     public int hashCode() {
1055         return ((int) (seconds ^ (seconds >>> 32))) + 51 * nanos;
1056     }
1057 
1058     //-----------------------------------------------------------------------
1059     /**
1060      * A string representation of this instant using ISO-8601 representation.
1061      * <p>
1062      * The format used is the same as {@link DateTimeFormatters#isoInstant()}.
1063      *
1064      * @return an ISO-8601 representation of this instant, not null
1065      */
1066     @Override
1067     public String toString() {
1068         return DateTimeFormatters.isoInstant().print(this);
1069     }
1070 
1071     // -----------------------------------------------------------------------
1072     /**
1073      * Writes the object using a
1074      * <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>.
1075      * <pre>
1076      *  out.writeByte(2);  // identifies this as an Instant
1077      *  out.writeLong(seconds);
1078      *  out.writeInt(nanos);
1079      * </pre>
1080      *
1081      * @return the instance of {@code Ser}, not null
1082      */
1083     private Object writeReplace() {
1084         return new Ser(Ser.INSTANT_TYPE, this);
1085     }
1086 
1087     /**
1088      * Defend against malicious streams.


  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.Queries;
  85 import java.time.temporal.Temporal;
  86 import java.time.temporal.TemporalAccessor;

  87 import java.time.temporal.TemporalAdjuster;
  88 import java.time.temporal.TemporalAmount;
  89 import java.time.temporal.TemporalField;
  90 import java.time.temporal.TemporalQuery;

  91 import java.time.temporal.TemporalUnit;
  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.


 208      * The value is also chosen such that the value of the year fits in
 209      * an {@code int}.
 210      */
 211     public static final Instant MIN = Instant.ofEpochSecond(MIN_SECOND, 0);
 212     /**
 213      * The minimum supported {@code Instant}, '-1000000000-01-01T00:00Z'.
 214      * This could be used by an application as a "far future" instant.
 215      * <p>
 216      * This is one year later than the maximum {@code LocalDateTime}.
 217      * This provides sufficient values to handle the range of {@code ZoneOffset}
 218      * which affect the instant in addition to the local date-time.
 219      * The value is also chosen such that the value of the year fits in
 220      * an {@code int}.
 221      */
 222     public static final Instant MAX = Instant.ofEpochSecond(MAX_SECOND, 999_999_999);
 223 
 224     /**
 225      * Serialization version.
 226      */
 227     private static final long serialVersionUID = -665713676816604388L;




 228 
 229     /**
 230      * The number of seconds from the epoch of 1970-01-01T00:00:00Z.
 231      */
 232     private final long seconds;
 233     /**
 234      * The number of nanoseconds, later along the time-line, from the seconds field.
 235      * This is always positive, and never exceeds 999,999,999.
 236      */
 237     private final int nanos;
 238 
 239     //-----------------------------------------------------------------------
 240     /**
 241      * Obtains the current instant from the system clock.
 242      * <p>
 243      * This will query the {@link Clock#systemUTC() system UTC clock} to
 244      * obtain the current instant.
 245      * <p>
 246      * Using this method will prevent the ability to use an alternate time-source for
 247      * testing because the clock is effectively hard-coded.


 312     /**
 313      * Obtains an instance of {@code Instant} using milliseconds from the
 314      * epoch of 1970-01-01T00:00:00Z.
 315      * <p>
 316      * The seconds and nanoseconds are extracted from the specified milliseconds.
 317      *
 318      * @param epochMilli  the number of milliseconds from 1970-01-01T00:00:00Z
 319      * @return an instant, not null
 320      * @throws DateTimeException if the instant exceeds the maximum or minimum instant
 321      */
 322     public static Instant ofEpochMilli(long epochMilli) {
 323         long secs = Math.floorDiv(epochMilli, 1000);
 324         int mos = (int)Math.floorMod(epochMilli, 1000);
 325         return create(secs, mos * 1000_000);
 326     }
 327 
 328     //-----------------------------------------------------------------------
 329     /**
 330      * Obtains an instance of {@code Instant} from a temporal object.
 331      * <p>
 332      * This obtains an instant based on the specified temporal.
 333      * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
 334      * which this factory converts to an instance of {@code Instant}.
 335      * <p>
 336      * The conversion extracts the {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS}
 337      * and {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} fields.
 338      * <p>
 339      * This method matches the signature of the functional interface {@link TemporalQuery}
 340      * allowing it to be used as a query via method reference, {@code Instant::from}.
 341      *
 342      * @param temporal  the temporal object to convert, not null
 343      * @return the instant, not null
 344      * @throws DateTimeException if unable to convert to an {@code Instant}
 345      */
 346     public static Instant from(TemporalAccessor temporal) {
 347         long instantSecs = temporal.getLong(INSTANT_SECONDS);
 348         int nanoOfSecond = temporal.get(NANO_OF_SECOND);
 349         return Instant.ofEpochSecond(instantSecs, nanoOfSecond);
 350     }
 351 
 352     //-----------------------------------------------------------------------
 353     /**
 354      * Obtains an instance of {@code Instant} from a text string such as
 355      * {@code 2007-12-03T10:15:30:00}.
 356      * <p>
 357      * The string must represent a valid instant in UTC and is parsed using
 358      * {@link DateTimeFormatter#ISO_INSTANT}.
 359      *
 360      * @param text  the text to parse, not null
 361      * @return the parsed instant, not null
 362      * @throws DateTimeParseException if the text cannot be parsed
 363      */
 364     public static Instant parse(final CharSequence text) {
 365         return DateTimeFormatter.ISO_INSTANT.parse(text, Instant::from);
 366     }
 367 
 368     //-----------------------------------------------------------------------
 369     /**
 370      * Obtains an instance of {@code Instant} using seconds and nanoseconds.
 371      *
 372      * @param seconds  the length of the duration in seconds
 373      * @param nanoOfSecond  the nano-of-second, from 0 to 999,999,999
 374      * @throws DateTimeException if the instant exceeds the maximum or minimum instant
 375      */
 376     private static Instant create(long seconds, int nanoOfSecond) {
 377         if ((seconds | nanoOfSecond) == 0) {
 378             return EPOCH;
 379         }
 380         if (seconds < MIN_SECOND || seconds > MAX_SECOND) {
 381             throw new DateTimeException("Instant exceeds minimum or maximum instant");
 382         }
 383         return new Instant(seconds, nanoOfSecond);
 384     }
 385 


 398 
 399     //-----------------------------------------------------------------------
 400     /**
 401      * Checks if the specified field is supported.
 402      * <p>
 403      * This checks if this instant can be queried for the specified field.
 404      * If false, then calling the {@link #range(TemporalField) range} and
 405      * {@link #get(TemporalField) get} methods will throw an exception.
 406      * <p>
 407      * If the field is a {@link ChronoField} then the query is implemented here.
 408      * The supported fields are:
 409      * <ul>
 410      * <li>{@code NANO_OF_SECOND}
 411      * <li>{@code MICRO_OF_SECOND}
 412      * <li>{@code MILLI_OF_SECOND}
 413      * <li>{@code INSTANT_SECONDS}
 414      * </ul>
 415      * All other {@code ChronoField} instances will return false.
 416      * <p>
 417      * If the field is not a {@code ChronoField}, then the result of this method
 418      * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
 419      * passing {@code this} as the argument.
 420      * Whether the field is supported is determined by the field.
 421      *
 422      * @param field  the field to check, null returns false
 423      * @return true if the field is supported on this instant, false if not
 424      */
 425     @Override
 426     public boolean isSupported(TemporalField field) {
 427         if (field instanceof ChronoField) {
 428             return field == INSTANT_SECONDS || field == NANO_OF_SECOND || field == MICRO_OF_SECOND || field == MILLI_OF_SECOND;
 429         }
 430         return field != null && field.isSupportedBy(this);
 431     }
 432 
 433     /**
 434      * Gets the range of valid values for the specified field.
 435      * <p>
 436      * The range object expresses the minimum and maximum valid values for a field.
 437      * This instant is used to enhance the accuracy of the returned range.
 438      * If it is not possible to return the range, because the field is not supported
 439      * or for some other reason, an exception is thrown.
 440      * <p>
 441      * If the field is a {@link ChronoField} then the query is implemented here.
 442      * The {@link #isSupported(TemporalField) supported fields} will return
 443      * appropriate range instances.
 444      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 445      * <p>
 446      * If the field is not a {@code ChronoField}, then the result of this method
 447      * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
 448      * passing {@code this} as the argument.
 449      * Whether the range can be obtained is determined by the field.
 450      *
 451      * @param field  the field to query the range for, not null
 452      * @return the range of valid values for the field, not null
 453      * @throws DateTimeException if the range for the field cannot be obtained
 454      */
 455     @Override  // override for Javadoc
 456     public ValueRange range(TemporalField field) {
 457         return Temporal.super.range(field);
 458     }
 459 
 460     /**
 461      * Gets the value of the specified field from this instant as an {@code int}.
 462      * <p>
 463      * This queries this instant for the value for the specified field.
 464      * The returned value will always be within the valid range of values for the field.
 465      * If it is not possible to return the value, because the field is not supported
 466      * or for some other reason, an exception is thrown.
 467      * <p>
 468      * If the field is a {@link ChronoField} then the query is implemented here.
 469      * The {@link #isSupported(TemporalField) supported fields} will return valid
 470      * values based on this date-time, except {@code INSTANT_SECONDS} which is too
 471      * large to fit in an {@code int} and throws a {@code DateTimeException}.
 472      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 473      * <p>
 474      * If the field is not a {@code ChronoField}, then the result of this method
 475      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
 476      * passing {@code this} as the argument. Whether the value can be obtained,
 477      * and what the value represents, is determined by the field.
 478      *
 479      * @param field  the field to get, not null
 480      * @return the value for the field
 481      * @throws DateTimeException if a value for the field cannot be obtained
 482      * @throws ArithmeticException if numeric overflow occurs
 483      */
 484     @Override  // override for Javadoc and performance
 485     public int get(TemporalField field) {
 486         if (field instanceof ChronoField) {
 487             switch ((ChronoField) field) {
 488                 case NANO_OF_SECOND: return nanos;
 489                 case MICRO_OF_SECOND: return nanos / 1000;
 490                 case MILLI_OF_SECOND: return nanos / 1000_000;
 491                 case INSTANT_SECONDS: INSTANT_SECONDS.checkValidIntValue(seconds);
 492             }
 493             throw new DateTimeException("Unsupported field: " + field.getName());
 494         }
 495         return range(field).checkValidIntValue(field.getFrom(this), field);
 496     }
 497 
 498     /**
 499      * Gets the value of the specified field from this instant as a {@code long}.
 500      * <p>
 501      * This queries this instant for the value for the specified field.
 502      * If it is not possible to return the value, because the field is not supported
 503      * or for some other reason, an exception is thrown.
 504      * <p>
 505      * If the field is a {@link ChronoField} then the query is implemented here.
 506      * The {@link #isSupported(TemporalField) supported fields} will return valid
 507      * values based on this date-time.
 508      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 509      * <p>
 510      * If the field is not a {@code ChronoField}, then the result of this method
 511      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
 512      * passing {@code this} as the argument. Whether the value can be obtained,
 513      * and what the value represents, is determined by the field.
 514      *
 515      * @param field  the field to get, not null
 516      * @return the value for the field
 517      * @throws DateTimeException if a value for the field cannot be obtained
 518      * @throws ArithmeticException if numeric overflow occurs
 519      */
 520     @Override
 521     public long getLong(TemporalField field) {
 522         if (field instanceof ChronoField) {
 523             switch ((ChronoField) field) {
 524                 case NANO_OF_SECOND: return nanos;
 525                 case MICRO_OF_SECOND: return nanos / 1000;
 526                 case MILLI_OF_SECOND: return nanos / 1000_000;
 527                 case INSTANT_SECONDS: return seconds;
 528             }
 529             throw new DateTimeException("Unsupported field: " + field.getName());
 530         }
 531         return field.getFrom(this);
 532     }
 533 
 534     //-----------------------------------------------------------------------
 535     /**
 536      * Gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z.
 537      * <p>
 538      * The epoch second count is a simple incrementing count of seconds where
 539      * second 0 is 1970-01-01T00:00:00Z.
 540      * The nanosecond part of the day is returned by {@code getNanosOfSecond}.
 541      *
 542      * @return the seconds from the epoch of 1970-01-01T00:00:00Z
 543      */
 544     public long getEpochSecond() {
 545         return seconds;
 546     }
 547 
 548     /**
 549      * Gets the number of nanoseconds, later along the time-line, from the start
 550      * of the second.
 551      * <p>
 552      * The nanosecond-of-second value measures the total number of nanoseconds from
 553      * the second returned by {@code getEpochSecond}.
 554      *
 555      * @return the nanoseconds within the second, always positive, never exceeds 999,999,999
 556      */
 557     public int getNano() {
 558         return nanos;
 559     }
 560 
 561     //-------------------------------------------------------------------------
 562     /**
 563      * Returns an adjusted copy of this instant.
 564      * <p>
 565      * This returns an {@code Instant}, based on this one, with the instant adjusted.
 566      * The adjustment takes place using the specified adjuster strategy object.
 567      * Read the documentation of the adjuster to understand what adjustment will be made.
 568      * <p>
 569      * The result of this method is obtained by invoking the
 570      * {@link TemporalAdjuster#adjustInto(Temporal)} method on the
 571      * specified adjuster passing {@code this} as the argument.
 572      * <p>
 573      * This instance is immutable and unaffected by this method call.
 574      *
 575      * @param adjuster the adjuster to use, not null
 576      * @return an {@code Instant} based on {@code this} with the adjustment made, not null
 577      * @throws DateTimeException if the adjustment cannot be made
 578      * @throws ArithmeticException if numeric overflow occurs
 579      */
 580     @Override
 581     public Instant with(TemporalAdjuster adjuster) {
 582         return (Instant) adjuster.adjustInto(this);
 583     }
 584 
 585     /**
 586      * Returns a copy of this instant with the specified field set to a new value.
 587      * <p>
 588      * This returns an {@code Instant}, based on this one, with the value
 589      * for the specified field changed.
 590      * If it is not possible to set the value, because the field is not supported or for
 591      * some other reason, an exception is thrown.
 592      * <p>
 593      * If the field is a {@link ChronoField} then the adjustment is implemented here.
 594      * The supported fields behave as follows:
 595      * <ul>
 596      * <li>{@code NANO_OF_SECOND} -
 597      *  Returns an {@code Instant} with the specified nano-of-second.
 598      *  The epoch-second will be unchanged.
 599      * <li>{@code MICRO_OF_SECOND} -
 600      *  Returns an {@code Instant} with the nano-of-second replaced by the specified
 601      *  micro-of-second multiplied by 1,000. The epoch-second will be unchanged.
 602      * <li>{@code MILLI_OF_SECOND} -
 603      *  Returns an {@code Instant} with the nano-of-second replaced by the specified
 604      *  milli-of-second multiplied by 1,000,000. The epoch-second will be unchanged.
 605      * <li>{@code INSTANT_SECONDS} -
 606      *  Returns an {@code Instant} with the specified epoch-second.
 607      *  The nano-of-second will be unchanged.
 608      * </ul>
 609      * <p>
 610      * In all cases, if the new value is outside the valid range of values for the field
 611      * then a {@code DateTimeException} will be thrown.
 612      * <p>
 613      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 614      * <p>
 615      * If the field is not a {@code ChronoField}, then the result of this method
 616      * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
 617      * passing {@code this} as the argument. In this case, the field determines
 618      * whether and how to adjust the instant.
 619      * <p>
 620      * This instance is immutable and unaffected by this method call.
 621      *
 622      * @param field  the field to set in the result, not null
 623      * @param newValue  the new value of the field in the result
 624      * @return an {@code Instant} based on {@code this} with the specified field set, not null
 625      * @throws DateTimeException if the field cannot be set
 626      * @throws ArithmeticException if numeric overflow occurs
 627      */
 628     @Override
 629     public Instant with(TemporalField field, long newValue) {
 630         if (field instanceof ChronoField) {
 631             ChronoField f = (ChronoField) field;
 632             f.checkValidValue(newValue);
 633             switch (f) {
 634                 case MILLI_OF_SECOND: {
 635                     int nval = (int) newValue * 1000_000;
 636                     return (nval != nanos ? create(seconds, nval) : this);
 637                 }
 638                 case MICRO_OF_SECOND: {
 639                     int nval = (int) newValue * 1000;
 640                     return (nval != nanos ? create(seconds, nval) : this);
 641                 }
 642                 case NANO_OF_SECOND: return (newValue != nanos ? create(seconds, (int) newValue) : this);
 643                 case INSTANT_SECONDS: return (newValue != seconds ? create(newValue, nanos) : this);
 644             }
 645             throw new DateTimeException("Unsupported field: " + field.getName());
 646         }
 647         return field.adjustInto(this, newValue);
 648     }
 649 
 650     //-----------------------------------------------------------------------
 651     /**
 652      * Returns a copy of this {@code Instant} truncated to the specified unit.
 653      * <p>
 654      * Truncating the instant returns a copy of the original with fields
 655      * smaller than the specified unit set to zero.
 656      * The fields are calculated on the basis of using a UTC offset as seen
 657      * in {@code toString}.
 658      * For example, truncating with the {@link ChronoUnit#MINUTES MINUTES} unit will
 659      * round down to the nearest minute, setting the seconds and nanoseconds to zero.
 660      * <p>
 661      * The unit must have a {@linkplain TemporalUnit#getDuration() duration}
 662      * that divides into the length of a standard day without remainder.
 663      * This includes all supplied time units on {@link ChronoUnit} and
 664      * {@link ChronoUnit#DAYS DAYS}. Other units throw an exception.
 665      * <p>
 666      * This instance is immutable and unaffected by this method call.
 667      *
 668      * @param unit  the unit to truncate to, not null
 669      * @return an {@code Instant} based on this instant with the time truncated, not null
 670      * @throws DateTimeException if the unit is invalid for truncation
 671      */
 672     public Instant truncatedTo(TemporalUnit unit) {
 673         if (unit == ChronoUnit.NANOS) {
 674             return this;
 675         }
 676         Duration unitDur = unit.getDuration();
 677         if (unitDur.getSeconds() > LocalTime.SECONDS_PER_DAY) {
 678             throw new DateTimeException("Unit is too large to be used for truncation");
 679         }
 680         long dur = unitDur.toNanos();
 681         if ((LocalTime.NANOS_PER_DAY % dur) != 0) {
 682             throw new DateTimeException("Unit must divide into a standard day without remainder");
 683         }
 684         long nod = (seconds % LocalTime.SECONDS_PER_DAY) * LocalTime.NANOS_PER_SECOND + nanos;
 685         long result = (nod / dur) * dur;
 686         return plusNanos(result - nod);
 687     }
 688 
 689     //-----------------------------------------------------------------------
 690     /**
 691      * Returns a copy of this instant with the specified amount added.
 692      * <p>
 693      * This returns an {@code Instant}, based on this one, with the specified amount added.
 694      * The amount is typically {@link Duration} but may be any other type implementing
 695      * the {@link TemporalAmount} interface.
 696      * <p>
 697      * The calculation is delegated to the amount object by calling
 698      * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free
 699      * to implement the addition in any way it wishes, however it typically
 700      * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation
 701      * of the amount implementation to determine if it can be successfully added.
 702      * <p>
 703      * This instance is immutable and unaffected by this method call.
 704      *
 705      * @param amountToAdd  the amount to add, not null
 706      * @return an {@code Instant} based on this instant with the addition made, not null
 707      * @throws DateTimeException if the addition cannot be made
 708      * @throws ArithmeticException if numeric overflow occurs
 709      */
 710     @Override
 711     public Instant plus(TemporalAmount amountToAdd) {
 712         return (Instant) amountToAdd.addTo(this);
 713     }
 714 
 715     /**
 716      * Returns a copy of this instant with the specified amount added.
 717      * <p>
 718      * This returns an {@code Instant}, based on this one, with the amount
 719      * in terms of the unit added. If it is not possible to add the amount, because the
 720      * unit is not supported or for some other reason, an exception is thrown.
 721      * <p>
 722      * If the field is a {@link ChronoUnit} then the addition is implemented here.
 723      * The supported fields behave as follows:
 724      * <ul>
 725      * <li>{@code NANOS} -
 726      *  Returns a {@code Instant} with the specified number of nanoseconds added.
 727      *  This is equivalent to {@link #plusNanos(long)}.
 728      * <li>{@code MICROS} -
 729      *  Returns a {@code Instant} with the specified number of microseconds added.
 730      *  This is equivalent to {@link #plusNanos(long)} with the amount
 731      *  multiplied by 1,000.
 732      * <li>{@code MILLIS} -
 733      *  Returns a {@code Instant} with the specified number of milliseconds added.
 734      *  This is equivalent to {@link #plusNanos(long)} with the amount
 735      *  multiplied by 1,000,000.
 736      * <li>{@code SECONDS} -
 737      *  Returns a {@code Instant} with the specified number of seconds added.
 738      *  This is equivalent to {@link #plusSeconds(long)}.
 739      * <li>{@code MINUTES} -
 740      *  Returns a {@code Instant} with the specified number of minutes added.
 741      *  This is equivalent to {@link #plusSeconds(long)} with the amount
 742      *  multiplied by 60.
 743      * <li>{@code HOURS} -
 744      *  Returns a {@code Instant} with the specified number of hours added.
 745      *  This is equivalent to {@link #plusSeconds(long)} with the amount
 746      *  multiplied by 3,600.
 747      * <li>{@code HALF_DAYS} -
 748      *  Returns a {@code Instant} with the specified number of half-days added.
 749      *  This is equivalent to {@link #plusSeconds(long)} with the amount
 750      *  multiplied by 43,200 (12 hours).
 751      * <li>{@code DAYS} -
 752      *  Returns a {@code Instant} with the specified number of days added.
 753      *  This is equivalent to {@link #plusSeconds(long)} with the amount
 754      *  multiplied by 86,400 (24 hours).
 755      * </ul>
 756      * <p>
 757      * All other {@code ChronoUnit} instances will throw a {@code DateTimeException}.
 758      * <p>
 759      * If the field is not a {@code ChronoUnit}, then the result of this method
 760      * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
 761      * passing {@code this} as the argument. In this case, the unit determines
 762      * whether and how to perform the addition.
 763      * <p>
 764      * This instance is immutable and unaffected by this method call.
 765      *
 766      * @param amountToAdd  the amount of the unit to add to the result, may be negative
 767      * @param unit  the unit of the amount to add, not null
 768      * @return an {@code Instant} based on this instant with the specified amount added, not null
 769      * @throws DateTimeException if the addition cannot be made
 770      * @throws ArithmeticException if numeric overflow occurs
 771      */
 772     @Override
 773     public Instant plus(long amountToAdd, TemporalUnit unit) {
 774         if (unit instanceof ChronoUnit) {
 775             switch ((ChronoUnit) unit) {
 776                 case NANOS: return plusNanos(amountToAdd);
 777                 case MICROS: return plus(amountToAdd / 1000_000, (amountToAdd % 1000_000) * 1000);
 778                 case MILLIS: return plusMillis(amountToAdd);
 779                 case SECONDS: return plusSeconds(amountToAdd);
 780                 case MINUTES: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_MINUTE));
 781                 case HOURS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_HOUR));
 782                 case HALF_DAYS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY / 2));
 783                 case DAYS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY));
 784             }
 785             throw new DateTimeException("Unsupported unit: " + unit.getName());
 786         }
 787         return unit.addTo(this, amountToAdd);
 788     }
 789 
 790     //-----------------------------------------------------------------------
 791     /**
 792      * Returns a copy of this instant with the specified duration in seconds added.
 793      * <p>
 794      * This instance is immutable and unaffected by this method call.
 795      *
 796      * @param secondsToAdd  the seconds to add, positive or negative
 797      * @return an {@code Instant} based on this instant with the specified seconds added, not null
 798      * @throws DateTimeException if the result exceeds the maximum or minimum instant
 799      * @throws ArithmeticException if numeric overflow occurs
 800      */
 801     public Instant plusSeconds(long secondsToAdd) {
 802         return plus(secondsToAdd, 0);
 803     }
 804 
 805     /**
 806      * Returns a copy of this instant with the specified duration in milliseconds added.
 807      * <p>


 837      *
 838      * @param secondsToAdd  the seconds to add, positive or negative
 839      * @param nanosToAdd  the nanos to add, positive or negative
 840      * @return an {@code Instant} based on this instant with the specified seconds added, not null
 841      * @throws DateTimeException if the result exceeds the maximum or minimum instant
 842      * @throws ArithmeticException if numeric overflow occurs
 843      */
 844     private Instant plus(long secondsToAdd, long nanosToAdd) {
 845         if ((secondsToAdd | nanosToAdd) == 0) {
 846             return this;
 847         }
 848         long epochSec = Math.addExact(seconds, secondsToAdd);
 849         epochSec = Math.addExact(epochSec, nanosToAdd / NANOS_PER_SECOND);
 850         nanosToAdd = nanosToAdd % NANOS_PER_SECOND;
 851         long nanoAdjustment = nanos + nanosToAdd;  // safe int+NANOS_PER_SECOND
 852         return ofEpochSecond(epochSec, nanoAdjustment);
 853     }
 854 
 855     //-----------------------------------------------------------------------
 856     /**
 857      * Returns a copy of this instant with the specified amount subtracted.
 858      * <p>
 859      * This returns an {@code Instant}, based on this one, with the specified amount subtracted.
 860      * The amount is typically {@link Duration} but may be any other type implementing
 861      * the {@link TemporalAmount} interface.
 862      * <p>
 863      * The calculation is delegated to the amount object by calling
 864      * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free
 865      * to implement the subtraction in any way it wishes, however it typically
 866      * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation
 867      * of the amount implementation to determine if it can be successfully subtracted.
 868      * <p>
 869      * This instance is immutable and unaffected by this method call.
 870      *
 871      * @param amountToSubtract  the amount to subtract, not null
 872      * @return an {@code Instant} based on this instant with the subtraction made, not null
 873      * @throws DateTimeException if the subtraction cannot be made
 874      * @throws ArithmeticException if numeric overflow occurs
 875      */
 876     @Override
 877     public Instant minus(TemporalAmount amountToSubtract) {
 878         return (Instant) amountToSubtract.subtractFrom(this);
 879     }
 880 
 881     /**
 882      * Returns a copy of this instant with the specified amount subtracted.
 883      * <p>
 884      * This returns a {@code Instant}, based on this one, with the amount
 885      * in terms of the unit subtracted. If it is not possible to subtract the amount,
 886      * because the unit is not supported or for some other reason, an exception is thrown.
 887      * <p>
 888      * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.
 889      * See that method for a full description of how addition, and thus subtraction, works.
 890      * <p>
 891      * This instance is immutable and unaffected by this method call.
 892      *
 893      * @param amountToSubtract  the amount of the unit to subtract from the result, may be negative
 894      * @param unit  the unit of the amount to subtract, not null
 895      * @return an {@code Instant} based on this instant with the specified amount subtracted, not null
 896      * @throws DateTimeException if the subtraction cannot be made
 897      * @throws ArithmeticException if numeric overflow occurs
 898      */
 899     @Override
 900     public Instant minus(long amountToSubtract, TemporalUnit unit) {
 901         return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
 902     }
 903 
 904     //-----------------------------------------------------------------------
 905     /**
 906      * Returns a copy of this instant with the specified duration in seconds subtracted.
 907      * <p>
 908      * This instance is immutable and unaffected by this method call.
 909      *
 910      * @param secondsToSubtract  the seconds to subtract, positive or negative
 911      * @return an {@code Instant} based on this instant with the specified seconds subtracted, not null
 912      * @throws DateTimeException if the result exceeds the maximum or minimum instant
 913      * @throws ArithmeticException if numeric overflow occurs
 914      */
 915     public Instant minusSeconds(long secondsToSubtract) {
 916         if (secondsToSubtract == Long.MIN_VALUE) {
 917             return plusSeconds(Long.MAX_VALUE).plusSeconds(1);


 962      * obtain the result. Read the documentation of the query to understand
 963      * what the result of this method will be.
 964      * <p>
 965      * The result of this method is obtained by invoking the
 966      * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
 967      * specified query passing {@code this} as the argument.
 968      *
 969      * @param <R> the type of the result
 970      * @param query  the query to invoke, not null
 971      * @return the query result, null may be returned (defined by the query)
 972      * @throws DateTimeException if unable to query (defined by the query)
 973      * @throws ArithmeticException if numeric overflow occurs (defined by the query)
 974      */
 975     @SuppressWarnings("unchecked")
 976     @Override
 977     public <R> R query(TemporalQuery<R> query) {
 978         if (query == Queries.precision()) {
 979             return (R) NANOS;
 980         }
 981         // inline TemporalAccessor.super.query(query) as an optimization
 982         if (query == Queries.chronology() || query == Queries.zoneId() || query == Queries.zone() || query == Queries.offset()) {
 983             return null;
 984         }
 985         return query.queryFrom(this);
 986     }
 987 
 988     /**
 989      * Adjusts the specified temporal object to have this instant.
 990      * <p>
 991      * This returns a temporal object of the same observable type as the input
 992      * with the instant changed to be the same as this.
 993      * <p>
 994      * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
 995      * twice, passing {@link ChronoField#INSTANT_SECONDS} and
 996      * {@link ChronoField#NANO_OF_SECOND} as the fields.
 997      * <p>
 998      * In most cases, it is clearer to reverse the calling pattern by using
 999      * {@link Temporal#with(TemporalAdjuster)}:
1000      * <pre>
1001      *   // these two lines are equivalent, but the second approach is recommended
1002      *   temporal = thisInstant.adjustInto(temporal);


1059     public long periodUntil(Temporal endInstant, TemporalUnit unit) {
1060         if (endInstant instanceof Instant == false) {
1061             Objects.requireNonNull(endInstant, "endInstant");
1062             throw new DateTimeException("Unable to calculate period between objects of two different types");
1063         }
1064         Instant end = (Instant) endInstant;
1065         if (unit instanceof ChronoUnit) {
1066             ChronoUnit f = (ChronoUnit) unit;
1067             switch (f) {
1068                 case NANOS: return nanosUntil(end);
1069                 case MICROS: return nanosUntil(end) / 1000;
1070                 case MILLIS: return Math.subtractExact(end.toEpochMilli(), toEpochMilli());
1071                 case SECONDS: return secondsUntil(end);
1072                 case MINUTES: return secondsUntil(end) / SECONDS_PER_MINUTE;
1073                 case HOURS: return secondsUntil(end) / SECONDS_PER_HOUR;
1074                 case HALF_DAYS: return secondsUntil(end) / (12 * SECONDS_PER_HOUR);
1075                 case DAYS: return secondsUntil(end) / (SECONDS_PER_DAY);
1076             }
1077             throw new DateTimeException("Unsupported unit: " + unit.getName());
1078         }
1079         return unit.between(this, endInstant);
1080     }
1081 
1082     private long nanosUntil(Instant end) {
1083         long secs = Math.multiplyExact(secondsUntil(end), NANOS_PER_SECOND);
1084         return Math.addExact(secs, end.nanos - nanos);
1085     }
1086 
1087     private long secondsUntil(Instant end) {
1088         return Math.subtractExact(end.seconds, seconds);
1089     }
1090 
1091     //-----------------------------------------------------------------------
1092     /**
1093      * Combines this instant with an offset to create an {@code OffsetDateTime}.
1094      * <p>
1095      * This returns an {@code OffsetDateTime} formed from this instant at the
1096      * specified offset from UTC/Greenwich. An exception will be thrown if the
1097      * instant is too large to fit into an offset date-time.
1098      * <p>
1099      * This method is equivalent to
1100      * {@link OffsetDateTime#ofInstant(Instant, ZoneId) OffsetDateTime.ofInstant(this, offset)}.
1101      *
1102      * @param offset  the offset to combine with, not null
1103      * @return the offset date-time formed from this instant and the specified offset, not null
1104      * @throws DateTimeException if the result exceeds the supported range
1105      */
1106     public OffsetDateTime atOffset(ZoneOffset offset) {
1107         return OffsetDateTime.ofInstant(this, offset);
1108     }
1109 
1110     /**
1111      * Combines this instant with a time-zone to create a {@code ZonedDateTime}.
1112      * <p>
1113      * This returns an {@code ZonedDateTime} formed from this instant at the
1114      * specified time-zone. An exception will be thrown if the instant is too
1115      * large to fit into a zoned date-time.
1116      * <p>
1117      * This method is equivalent to
1118      * {@link ZonedDateTime#ofInstant(Instant, ZoneId) ZonedDateTime.ofInstant(this, zone)}.
1119      *
1120      * @param zone  the zone to combine with, not null
1121      * @return the zoned date-time formed from this instant and the specified zone, not null
1122      * @throws DateTimeException if the result exceeds the supported range
1123      */
1124     public ZonedDateTime atZone(ZoneId zone) {
1125         return ZonedDateTime.ofInstant(this, zone);
1126     }
1127 
1128     //-----------------------------------------------------------------------
1129     /**
1130      * Converts this instant to the number of milliseconds from the epoch
1131      * of 1970-01-01T00:00:00Z.
1132      * <p>
1133      * If this instant represents a point on the time-line too far in the future
1134      * or past to fit in a {@code long} milliseconds, then an exception is thrown.
1135      * <p>
1136      * If this instant has greater than millisecond precision, then the conversion
1137      * will drop any excess precision information as though the amount in nanoseconds
1138      * was subject to integer division by one million.
1139      *
1140      * @return the number of milliseconds since the epoch of 1970-01-01T00:00:00Z
1141      * @throws ArithmeticException if numeric overflow occurs
1142      */
1143     public long toEpochMilli() {
1144         long millis = Math.multiplyExact(seconds, 1000);
1145         return millis + nanos / 1000_000;
1146     }
1147 
1148     //-----------------------------------------------------------------------
1149     /**


1210             return this.seconds == other.seconds &&
1211                    this.nanos == other.nanos;
1212         }
1213         return false;
1214     }
1215 
1216     /**
1217      * Returns a hash code for this instant.
1218      *
1219      * @return a suitable hash code
1220      */
1221     @Override
1222     public int hashCode() {
1223         return ((int) (seconds ^ (seconds >>> 32))) + 51 * nanos;
1224     }
1225 
1226     //-----------------------------------------------------------------------
1227     /**
1228      * A string representation of this instant using ISO-8601 representation.
1229      * <p>
1230      * The format used is the same as {@link DateTimeFormatter#ISO_INSTANT}.
1231      *
1232      * @return an ISO-8601 representation of this instant, not null
1233      */
1234     @Override
1235     public String toString() {
1236         return DateTimeFormatter.ISO_INSTANT.format(this);
1237     }
1238 
1239     // -----------------------------------------------------------------------
1240     /**
1241      * Writes the object using a
1242      * <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>.
1243      * <pre>
1244      *  out.writeByte(2);  // identifies this as an Instant
1245      *  out.writeLong(seconds);
1246      *  out.writeInt(nanos);
1247      * </pre>
1248      *
1249      * @return the instance of {@code Ser}, not null
1250      */
1251     private Object writeReplace() {
1252         return new Ser(Ser.INSTANT_TYPE, this);
1253     }
1254 
1255     /**
1256      * Defend against malicious streams.