1 /* 2 * Copyright (c) 2012, 2021, 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.MICROS_PER_SECOND; 65 import static java.time.LocalTime.MILLIS_PER_SECOND; 66 import static java.time.LocalTime.NANOS_PER_SECOND; 67 import static java.time.LocalTime.SECONDS_PER_DAY; 68 import static java.time.LocalTime.SECONDS_PER_HOUR; 69 import static java.time.LocalTime.SECONDS_PER_MINUTE; 70 import static java.time.temporal.ChronoField.INSTANT_SECONDS; 71 import static java.time.temporal.ChronoField.MICRO_OF_SECOND; 72 import static java.time.temporal.ChronoField.MILLI_OF_SECOND; 73 import static java.time.temporal.ChronoField.NANO_OF_SECOND; 74 import static java.time.temporal.ChronoUnit.DAYS; 75 import static java.time.temporal.ChronoUnit.NANOS; 76 77 import java.io.DataInput; 78 import java.io.DataOutput; 79 import java.io.IOException; 80 import java.io.InvalidObjectException; 81 import java.io.ObjectInputStream; 82 import java.io.Serializable; 83 import java.time.format.DateTimeFormatter; 84 import java.time.format.DateTimeParseException; 85 import java.time.temporal.ChronoField; 86 import java.time.temporal.ChronoUnit; 87 import java.time.temporal.Temporal; 88 import java.time.temporal.TemporalAccessor; 89 import java.time.temporal.TemporalAdjuster; 90 import java.time.temporal.TemporalAmount; 91 import java.time.temporal.TemporalField; 92 import java.time.temporal.TemporalQueries; 93 import java.time.temporal.TemporalQuery; 94 import java.time.temporal.TemporalUnit; 95 import java.time.temporal.UnsupportedTemporalTypeException; 96 import java.time.temporal.ValueRange; 97 import java.util.Objects; 98 99 /** 100 * An instantaneous point on the time-line. 101 * <p> 102 * This class models a single instantaneous point on the time-line. 103 * This might be used to record event time-stamps in the application. 104 * <p> 105 * The range of an instant requires the storage of a number larger than a {@code long}. 106 * To achieve this, the class stores a {@code long} representing epoch-seconds and an 107 * {@code int} representing nanosecond-of-second, which will always be between 0 and 999,999,999. 108 * The epoch-seconds are measured from the standard Java epoch of {@code 1970-01-01T00:00:00Z} 109 * where instants after the epoch have positive values, and earlier instants have negative values. 110 * For both the epoch-second and nanosecond parts, a larger value is always later on the time-line 111 * than a smaller value. 112 * 113 * <h2>Time-scale</h2> 114 * <p> 115 * The length of the solar day is the standard way that humans measure time. 116 * This has traditionally been subdivided into 24 hours of 60 minutes of 60 seconds, 117 * forming a 86400 second day. 118 * <p> 119 * Modern timekeeping is based on atomic clocks which precisely define an SI second 120 * relative to the transitions of a Caesium atom. The length of an SI second was defined 121 * to be very close to the 86400th fraction of a day. 122 * <p> 123 * Unfortunately, as the Earth rotates the length of the day varies. 124 * In addition, over time the average length of the day is getting longer as the Earth slows. 125 * As a result, the length of a solar day in 2012 is slightly longer than 86400 SI seconds. 126 * The actual length of any given day and the amount by which the Earth is slowing 127 * are not predictable and can only be determined by measurement. 128 * The UT1 time-scale captures the accurate length of day, but is only available some 129 * time after the day has completed. 130 * <p> 131 * The UTC time-scale is a standard approach to bundle up all the additional fractions 132 * of a second from UT1 into whole seconds, known as <i>leap-seconds</i>. 133 * A leap-second may be added or removed depending on the Earth's rotational changes. 134 * As such, UTC permits a day to have 86399 SI seconds or 86401 SI seconds where 135 * necessary in order to keep the day aligned with the Sun. 136 * <p> 137 * The modern UTC time-scale was introduced in 1972, introducing the concept of whole leap-seconds. 138 * Between 1958 and 1972, the definition of UTC was complex, with minor sub-second leaps and 139 * alterations to the length of the notional second. As of 2012, discussions are underway 140 * to change the definition of UTC again, with the potential to remove leap seconds or 141 * introduce other changes. 142 * <p> 143 * Given the complexity of accurate timekeeping described above, this Java API defines 144 * its own time-scale, the <i>Java Time-Scale</i>. 145 * <p> 146 * The Java Time-Scale divides each calendar day into exactly 86400 147 * subdivisions, known as seconds. These seconds may differ from the 148 * SI second. It closely matches the de facto international civil time 149 * scale, the definition of which changes from time to time. 150 * <p> 151 * The Java Time-Scale has slightly different definitions for different 152 * segments of the time-line, each based on the consensus international 153 * time scale that is used as the basis for civil time. Whenever the 154 * internationally-agreed time scale is modified or replaced, a new 155 * segment of the Java Time-Scale must be defined for it. Each segment 156 * must meet these requirements: 157 * <ul> 158 * <li>the Java Time-Scale shall closely match the underlying international 159 * civil time scale;</li> 160 * <li>the Java Time-Scale shall exactly match the international civil 161 * time scale at noon each day;</li> 162 * <li>the Java Time-Scale shall have a precisely-defined relationship to 163 * the international civil time scale.</li> 164 * </ul> 165 * There are currently, as of 2013, two segments in the Java time-scale. 166 * <p> 167 * For the segment from 1972-11-03 (exact boundary discussed below) until 168 * further notice, the consensus international time scale is UTC (with 169 * leap seconds). In this segment, the Java Time-Scale is identical to 170 * <a href="http://www.cl.cam.ac.uk/~mgk25/time/utc-sls/">UTC-SLS</a>. 171 * This is identical to UTC on days that do not have a leap second. 172 * On days that do have a leap second, the leap second is spread equally 173 * over the last 1000 seconds of the day, maintaining the appearance of 174 * exactly 86400 seconds per day. 175 * <p> 176 * For the segment prior to 1972-11-03, extending back arbitrarily far, 177 * the consensus international time scale is defined to be UT1, applied 178 * proleptically, which is equivalent to the (mean) solar time on the 179 * prime meridian (Greenwich). In this segment, the Java Time-Scale is 180 * identical to the consensus international time scale. The exact 181 * boundary between the two segments is the instant where UT1 = UTC 182 * between 1972-11-03T00:00 and 1972-11-04T12:00. 183 * <p> 184 * Implementations of the Java time-scale using the JSR-310 API are not 185 * required to provide any clock that is sub-second accurate, or that 186 * progresses monotonically or smoothly. Implementations are therefore 187 * not required to actually perform the UTC-SLS slew or to otherwise be 188 * aware of leap seconds. JSR-310 does, however, require that 189 * implementations must document the approach they use when defining a 190 * clock representing the current instant. 191 * See {@link Clock} for details on the available clocks. 192 * <p> 193 * The Java time-scale is used for all date-time classes. 194 * This includes {@code Instant}, {@code LocalDate}, {@code LocalTime}, {@code OffsetDateTime}, 195 * {@code ZonedDateTime} and {@code Duration}. 196 * <p> 197 * This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a> 198 * class; programmers should treat instances that are 199 * {@linkplain #equals(Object) equal} as interchangeable and should not 200 * use instances for synchronization, or unpredictable behavior may 201 * occur. For example, in a future release, synchronization may fail. 202 * The {@code equals} method should be used for comparisons. 203 * 204 * @implSpec 205 * This class is immutable and thread-safe. 206 * 207 * @since 1.8 208 */ 209 @jdk.internal.ValueBased 210 public final class Instant 211 implements Temporal, TemporalAdjuster, Comparable<Instant>, Serializable { 212 213 /** 214 * Constant for the 1970-01-01T00:00:00Z epoch instant. 215 */ 216 public static final Instant EPOCH = new Instant(0, 0); 217 /** 218 * The minimum supported epoch second. 219 */ 220 private static final long MIN_SECOND = -31557014167219200L; 221 /** 222 * The maximum supported epoch second. 223 */ 224 private static final long MAX_SECOND = 31556889864403199L; 225 /** 226 * The minimum supported {@code Instant}, '-1000000000-01-01T00:00Z'. 227 * This could be used by an application as a "far past" instant. 228 * <p> 229 * This is one year earlier than the minimum {@code LocalDateTime}. 230 * This provides sufficient values to handle the range of {@code ZoneOffset} 231 * which affect the instant in addition to the local date-time. 232 * The value is also chosen such that the value of the year fits in 233 * an {@code int}. 234 */ 235 public static final Instant MIN = Instant.ofEpochSecond(MIN_SECOND, 0); 236 /** 237 * The maximum supported {@code Instant}, '1000000000-12-31T23:59:59.999999999Z'. 238 * This could be used by an application as a "far future" instant. 239 * <p> 240 * This is one year later than the maximum {@code LocalDateTime}. 241 * This provides sufficient values to handle the range of {@code ZoneOffset} 242 * which affect the instant in addition to the local date-time. 243 * The value is also chosen such that the value of the year fits in 244 * an {@code int}. 245 */ 246 public static final Instant MAX = Instant.ofEpochSecond(MAX_SECOND, 999_999_999); 247 248 /** 249 * Serialization version. 250 */ 251 @java.io.Serial 252 private static final long serialVersionUID = -665713676816604388L; 253 254 /** 255 * The number of seconds from the epoch of 1970-01-01T00:00:00Z. 256 */ 257 private final long seconds; 258 /** 259 * The number of nanoseconds, later along the time-line, from the seconds field. 260 * This is always positive, and never exceeds 999,999,999. 261 */ 262 private final int nanos; 263 264 //----------------------------------------------------------------------- 265 /** 266 * Obtains the current instant from the system clock. 267 * <p> 268 * This will query the {@link Clock#systemUTC() system UTC clock} to 269 * obtain the current instant. 270 * <p> 271 * Using this method will prevent the ability to use an alternate time-source for 272 * testing because the clock is effectively hard-coded. 273 * 274 * @return the current instant using the system clock, not null 275 */ 276 public static Instant now() { 277 return Clock.currentInstant(); 278 } 279 280 /** 281 * Obtains the current instant from the specified clock. 282 * <p> 283 * This will query the specified clock to obtain the current time. 284 * <p> 285 * Using this method allows the use of an alternate clock for testing. 286 * The alternate clock may be introduced using {@link Clock dependency injection}. 287 * 288 * @param clock the clock to use, not null 289 * @return the current instant, not null 290 */ 291 public static Instant now(Clock clock) { 292 Objects.requireNonNull(clock, "clock"); 293 return clock.instant(); 294 } 295 296 //----------------------------------------------------------------------- 297 /** 298 * Obtains an instance of {@code Instant} using seconds from the 299 * epoch of 1970-01-01T00:00:00Z. 300 * <p> 301 * The nanosecond field is set to zero. 302 * 303 * @param epochSecond the number of seconds from 1970-01-01T00:00:00Z 304 * @return an instant, not null 305 * @throws DateTimeException if the instant exceeds the maximum or minimum instant 306 */ 307 public static Instant ofEpochSecond(long epochSecond) { 308 return create(epochSecond, 0); 309 } 310 311 /** 312 * Obtains an instance of {@code Instant} using seconds from the 313 * epoch of 1970-01-01T00:00:00Z and nanosecond fraction of second. 314 * <p> 315 * This method allows an arbitrary number of nanoseconds to be passed in. 316 * The factory will alter the values of the second and nanosecond in order 317 * to ensure that the stored nanosecond is in the range 0 to 999,999,999. 318 * For example, the following will result in exactly the same instant: 319 * <pre> 320 * Instant.ofEpochSecond(3, 1); 321 * Instant.ofEpochSecond(4, -999_999_999); 322 * Instant.ofEpochSecond(2, 1000_000_001); 323 * </pre> 324 * 325 * @param epochSecond the number of seconds from 1970-01-01T00:00:00Z 326 * @param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative 327 * @return an instant, not null 328 * @throws DateTimeException if the instant exceeds the maximum or minimum instant 329 * @throws ArithmeticException if numeric overflow occurs 330 */ 331 public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment) { 332 long secs = Math.addExact(epochSecond, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND)); 333 int nos = (int)Math.floorMod(nanoAdjustment, NANOS_PER_SECOND); 334 return create(secs, nos); 335 } 336 337 /** 338 * Obtains an instance of {@code Instant} using milliseconds from the 339 * epoch of 1970-01-01T00:00:00Z. 340 * <p> 341 * The seconds and nanoseconds are extracted from the specified milliseconds. 342 * 343 * @param epochMilli the number of milliseconds from 1970-01-01T00:00:00Z 344 * @return an instant, not null 345 * @throws DateTimeException if the instant exceeds the maximum or minimum instant 346 */ 347 public static Instant ofEpochMilli(long epochMilli) { 348 long secs = Math.floorDiv(epochMilli, 1000); 349 int mos = Math.floorMod(epochMilli, 1000); 350 return create(secs, mos * 1000_000); 351 } 352 353 //----------------------------------------------------------------------- 354 /** 355 * Obtains an instance of {@code Instant} from a temporal object. 356 * <p> 357 * This obtains an instant based on the specified temporal. 358 * A {@code TemporalAccessor} represents an arbitrary set of date and time information, 359 * which this factory converts to an instance of {@code Instant}. 360 * <p> 361 * The conversion extracts the {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS} 362 * and {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} fields. 363 * <p> 364 * This method matches the signature of the functional interface {@link TemporalQuery} 365 * allowing it to be used as a query via method reference, {@code Instant::from}. 366 * 367 * @param temporal the temporal object to convert, not null 368 * @return the instant, not null 369 * @throws DateTimeException if unable to convert to an {@code Instant} 370 */ 371 public static Instant from(TemporalAccessor temporal) { 372 if (temporal instanceof Instant) { 373 return (Instant) temporal; 374 } 375 Objects.requireNonNull(temporal, "temporal"); 376 try { 377 long instantSecs = temporal.getLong(INSTANT_SECONDS); 378 int nanoOfSecond = temporal.get(NANO_OF_SECOND); 379 return Instant.ofEpochSecond(instantSecs, nanoOfSecond); 380 } catch (DateTimeException ex) { 381 throw new DateTimeException("Unable to obtain Instant from TemporalAccessor: " + 382 temporal + " of type " + temporal.getClass().getName(), ex); 383 } 384 } 385 386 //----------------------------------------------------------------------- 387 /** 388 * Obtains an instance of {@code Instant} from a text string such as 389 * {@code 2007-12-03T10:15:30.00Z}. 390 * <p> 391 * The string must represent a valid instant in UTC and is parsed using 392 * {@link DateTimeFormatter#ISO_INSTANT}. 393 * 394 * @param text the text to parse, not null 395 * @return the parsed instant, not null 396 * @throws DateTimeParseException if the text cannot be parsed 397 */ 398 public static Instant parse(final CharSequence text) { 399 return DateTimeFormatter.ISO_INSTANT.parse(text, Instant::from); 400 } 401 402 //----------------------------------------------------------------------- 403 /** 404 * Obtains an instance of {@code Instant} using seconds and nanoseconds. 405 * 406 * @param seconds the length of the duration in seconds 407 * @param nanoOfSecond the nano-of-second, from 0 to 999,999,999 408 * @throws DateTimeException if the instant exceeds the maximum or minimum instant 409 */ 410 private static Instant create(long seconds, int nanoOfSecond) { 411 if ((seconds | nanoOfSecond) == 0) { 412 return EPOCH; 413 } 414 if (seconds < MIN_SECOND || seconds > MAX_SECOND) { 415 throw new DateTimeException("Instant exceeds minimum or maximum instant"); 416 } 417 return new Instant(seconds, nanoOfSecond); 418 } 419 420 /** 421 * Constructs an instance of {@code Instant} using seconds from the epoch of 422 * 1970-01-01T00:00:00Z and nanosecond fraction of second. 423 * 424 * @param epochSecond the number of seconds from 1970-01-01T00:00:00Z 425 * @param nanos the nanoseconds within the second, must be positive 426 */ 427 private Instant(long epochSecond, int nanos) { 428 super(); 429 this.seconds = epochSecond; 430 this.nanos = nanos; 431 } 432 433 //----------------------------------------------------------------------- 434 /** 435 * Checks if the specified field is supported. 436 * <p> 437 * This checks if this instant can be queried for the specified field. 438 * If false, then calling the {@link #range(TemporalField) range}, 439 * {@link #get(TemporalField) get} and {@link #with(TemporalField, long)} 440 * methods will throw an exception. 441 * <p> 442 * If the field is a {@link ChronoField} then the query is implemented here. 443 * The supported fields are: 444 * <ul> 445 * <li>{@code NANO_OF_SECOND} 446 * <li>{@code MICRO_OF_SECOND} 447 * <li>{@code MILLI_OF_SECOND} 448 * <li>{@code INSTANT_SECONDS} 449 * </ul> 450 * All other {@code ChronoField} instances will return false. 451 * <p> 452 * If the field is not a {@code ChronoField}, then the result of this method 453 * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)} 454 * passing {@code this} as the argument. 455 * Whether the field is supported is determined by the field. 456 * 457 * @param field the field to check, null returns false 458 * @return true if the field is supported on this instant, false if not 459 */ 460 @Override 461 public boolean isSupported(TemporalField field) { 462 if (field instanceof ChronoField) { 463 return field == INSTANT_SECONDS || field == NANO_OF_SECOND || field == MICRO_OF_SECOND || field == MILLI_OF_SECOND; 464 } 465 return field != null && field.isSupportedBy(this); 466 } 467 468 /** 469 * Checks if the specified unit is supported. 470 * <p> 471 * This checks if the specified unit can be added to, or subtracted from, this date-time. 472 * If false, then calling the {@link #plus(long, TemporalUnit)} and 473 * {@link #minus(long, TemporalUnit) minus} methods will throw an exception. 474 * <p> 475 * If the unit is a {@link ChronoUnit} then the query is implemented here. 476 * The supported units are: 477 * <ul> 478 * <li>{@code NANOS} 479 * <li>{@code MICROS} 480 * <li>{@code MILLIS} 481 * <li>{@code SECONDS} 482 * <li>{@code MINUTES} 483 * <li>{@code HOURS} 484 * <li>{@code HALF_DAYS} 485 * <li>{@code DAYS} 486 * </ul> 487 * All other {@code ChronoUnit} instances will return false. 488 * <p> 489 * If the unit is not a {@code ChronoUnit}, then the result of this method 490 * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)} 491 * passing {@code this} as the argument. 492 * Whether the unit is supported is determined by the unit. 493 * 494 * @param unit the unit to check, null returns false 495 * @return true if the unit can be added/subtracted, false if not 496 */ 497 @Override 498 public boolean isSupported(TemporalUnit unit) { 499 if (unit instanceof ChronoUnit) { 500 return unit.isTimeBased() || unit == DAYS; 501 } 502 return unit != null && unit.isSupportedBy(this); 503 } 504 505 //----------------------------------------------------------------------- 506 /** 507 * Gets the range of valid values for the specified field. 508 * <p> 509 * The range object expresses the minimum and maximum valid values for a field. 510 * This instant is used to enhance the accuracy of the returned range. 511 * If it is not possible to return the range, because the field is not supported 512 * or for some other reason, an exception is thrown. 513 * <p> 514 * If the field is a {@link ChronoField} then the query is implemented here. 515 * The {@link #isSupported(TemporalField) supported fields} will return 516 * appropriate range instances. 517 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. 518 * <p> 519 * If the field is not a {@code ChronoField}, then the result of this method 520 * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)} 521 * passing {@code this} as the argument. 522 * Whether the range can be obtained is determined by the field. 523 * 524 * @param field the field to query the range for, not null 525 * @return the range of valid values for the field, not null 526 * @throws DateTimeException if the range for the field cannot be obtained 527 * @throws UnsupportedTemporalTypeException if the field is not supported 528 */ 529 @Override // override for Javadoc 530 public ValueRange range(TemporalField field) { 531 return Temporal.super.range(field); 532 } 533 534 /** 535 * Gets the value of the specified field from this instant as an {@code int}. 536 * <p> 537 * This queries this instant for the value of the specified field. 538 * The returned value will always be within the valid range of values for the field. 539 * If it is not possible to return the value, because the field is not supported 540 * or for some other reason, an exception is thrown. 541 * <p> 542 * If the field is a {@link ChronoField} then the query is implemented here. 543 * The {@link #isSupported(TemporalField) supported fields} will return valid 544 * values based on this date-time, except {@code INSTANT_SECONDS} which is too 545 * large to fit in an {@code int} and throws a {@code DateTimeException}. 546 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. 547 * <p> 548 * If the field is not a {@code ChronoField}, then the result of this method 549 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} 550 * passing {@code this} as the argument. Whether the value can be obtained, 551 * and what the value represents, is determined by the field. 552 * 553 * @param field the field to get, not null 554 * @return the value for the field 555 * @throws DateTimeException if a value for the field cannot be obtained or 556 * the value is outside the range of valid values for the field 557 * @throws UnsupportedTemporalTypeException if the field is not supported or 558 * the range of values exceeds an {@code int} 559 * @throws ArithmeticException if numeric overflow occurs 560 */ 561 @Override // override for Javadoc and performance 562 public int get(TemporalField field) { 563 if (field instanceof ChronoField chronoField) { 564 return switch (chronoField) { 565 case NANO_OF_SECOND -> nanos; 566 case MICRO_OF_SECOND -> nanos / 1000; 567 case MILLI_OF_SECOND -> nanos / 1000_000; 568 default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field); 569 }; 570 } 571 return range(field).checkValidIntValue(field.getFrom(this), field); 572 } 573 574 /** 575 * Gets the value of the specified field from this instant as a {@code long}. 576 * <p> 577 * This queries this instant for the value of the specified field. 578 * If it is not possible to return the value, because the field is not supported 579 * or for some other reason, an exception is thrown. 580 * <p> 581 * If the field is a {@link ChronoField} then the query is implemented here. 582 * The {@link #isSupported(TemporalField) supported fields} will return valid 583 * values based on this date-time. 584 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. 585 * <p> 586 * If the field is not a {@code ChronoField}, then the result of this method 587 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} 588 * passing {@code this} as the argument. Whether the value can be obtained, 589 * and what the value represents, is determined by the field. 590 * 591 * @param field the field to get, not null 592 * @return the value for the field 593 * @throws DateTimeException if a value for the field cannot be obtained 594 * @throws UnsupportedTemporalTypeException if the field is not supported 595 * @throws ArithmeticException if numeric overflow occurs 596 */ 597 @Override 598 public long getLong(TemporalField field) { 599 if (field instanceof ChronoField chronoField) { 600 return switch (chronoField) { 601 case NANO_OF_SECOND -> nanos; 602 case MICRO_OF_SECOND -> nanos / 1000; 603 case MILLI_OF_SECOND -> nanos / 1000_000; 604 case INSTANT_SECONDS -> seconds; 605 default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field); 606 }; 607 } 608 return field.getFrom(this); 609 } 610 611 //----------------------------------------------------------------------- 612 /** 613 * Gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z. 614 * <p> 615 * The epoch second count is a simple incrementing count of seconds where 616 * second 0 is 1970-01-01T00:00:00Z. 617 * The nanosecond part is returned by {@link #getNano}. 618 * 619 * @return the seconds from the epoch of 1970-01-01T00:00:00Z 620 */ 621 public long getEpochSecond() { 622 return seconds; 623 } 624 625 /** 626 * Gets the number of nanoseconds, later along the time-line, from the start 627 * of the second. 628 * <p> 629 * The nanosecond-of-second value measures the total number of nanoseconds from 630 * the second returned by {@link #getEpochSecond}. 631 * 632 * @return the nanoseconds within the second, always positive, never exceeds 999,999,999 633 */ 634 public int getNano() { 635 return nanos; 636 } 637 638 //------------------------------------------------------------------------- 639 /** 640 * Returns an adjusted copy of this instant. 641 * <p> 642 * This returns an {@code Instant}, based on this one, with the instant adjusted. 643 * The adjustment takes place using the specified adjuster strategy object. 644 * Read the documentation of the adjuster to understand what adjustment will be made. 645 * <p> 646 * The result of this method is obtained by invoking the 647 * {@link TemporalAdjuster#adjustInto(Temporal)} method on the 648 * specified adjuster passing {@code this} as the argument. 649 * <p> 650 * This instance is immutable and unaffected by this method call. 651 * 652 * @param adjuster the adjuster to use, not null 653 * @return an {@code Instant} based on {@code this} with the adjustment made, not null 654 * @throws DateTimeException if the adjustment cannot be made 655 * @throws ArithmeticException if numeric overflow occurs 656 */ 657 @Override 658 public Instant with(TemporalAdjuster adjuster) { 659 return (Instant) adjuster.adjustInto(this); 660 } 661 662 /** 663 * Returns a copy of this instant with the specified field set to a new value. 664 * <p> 665 * This returns an {@code Instant}, based on this one, with the value 666 * for the specified field changed. 667 * If it is not possible to set the value, because the field is not supported or for 668 * some other reason, an exception is thrown. 669 * <p> 670 * If the field is a {@link ChronoField} then the adjustment is implemented here. 671 * The supported fields behave as follows: 672 * <ul> 673 * <li>{@code NANO_OF_SECOND} - 674 * Returns an {@code Instant} with the specified nano-of-second. 675 * The epoch-second will be unchanged. 676 * <li>{@code MICRO_OF_SECOND} - 677 * Returns an {@code Instant} with the nano-of-second replaced by the specified 678 * micro-of-second multiplied by 1,000. The epoch-second will be unchanged. 679 * <li>{@code MILLI_OF_SECOND} - 680 * Returns an {@code Instant} with the nano-of-second replaced by the specified 681 * milli-of-second multiplied by 1,000,000. The epoch-second will be unchanged. 682 * <li>{@code INSTANT_SECONDS} - 683 * Returns an {@code Instant} with the specified epoch-second. 684 * The nano-of-second will be unchanged. 685 * </ul> 686 * <p> 687 * In all cases, if the new value is outside the valid range of values for the field 688 * then a {@code DateTimeException} will be thrown. 689 * <p> 690 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. 691 * <p> 692 * If the field is not a {@code ChronoField}, then the result of this method 693 * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)} 694 * passing {@code this} as the argument. In this case, the field determines 695 * whether and how to adjust the instant. 696 * <p> 697 * This instance is immutable and unaffected by this method call. 698 * 699 * @param field the field to set in the result, not null 700 * @param newValue the new value of the field in the result 701 * @return an {@code Instant} based on {@code this} with the specified field set, not null 702 * @throws DateTimeException if the field cannot be set 703 * @throws UnsupportedTemporalTypeException if the field is not supported 704 * @throws ArithmeticException if numeric overflow occurs 705 */ 706 @Override 707 public Instant with(TemporalField field, long newValue) { 708 if (field instanceof ChronoField chronoField) { 709 chronoField.checkValidValue(newValue); 710 return switch (chronoField) { 711 case MILLI_OF_SECOND -> { 712 int nval = (int) newValue * 1000_000; 713 yield nval != nanos ? create(seconds, nval) : this; 714 } 715 case MICRO_OF_SECOND -> { 716 int nval = (int) newValue * 1000; 717 yield nval != nanos ? create(seconds, nval) : this; 718 } 719 case NANO_OF_SECOND -> newValue != nanos ? create(seconds, (int) newValue) : this; 720 case INSTANT_SECONDS -> newValue != seconds ? create(newValue, nanos) : this; 721 default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field); 722 }; 723 } 724 return field.adjustInto(this, newValue); 725 } 726 727 //----------------------------------------------------------------------- 728 /** 729 * Returns a copy of this {@code Instant} truncated to the specified unit. 730 * <p> 731 * Truncating the instant returns a copy of the original with fields 732 * smaller than the specified unit set to zero. 733 * The fields are calculated on the basis of using a UTC offset as seen 734 * in {@code toString}. 735 * For example, truncating with the {@link ChronoUnit#MINUTES MINUTES} unit will 736 * round down to the nearest minute, setting the seconds and nanoseconds to zero. 737 * <p> 738 * The unit must have a {@linkplain TemporalUnit#getDuration() duration} 739 * that divides into the length of a standard day without remainder. 740 * This includes all supplied time units on {@link ChronoUnit} and 741 * {@link ChronoUnit#DAYS DAYS}. Other units throw an exception. 742 * <p> 743 * This instance is immutable and unaffected by this method call. 744 * 745 * @param unit the unit to truncate to, not null 746 * @return an {@code Instant} based on this instant with the time truncated, not null 747 * @throws DateTimeException if the unit is invalid for truncation 748 * @throws UnsupportedTemporalTypeException if the unit is not supported 749 */ 750 public Instant truncatedTo(TemporalUnit unit) { 751 if (unit == ChronoUnit.NANOS) { 752 return this; 753 } 754 Duration unitDur = unit.getDuration(); 755 if (unitDur.getSeconds() > LocalTime.SECONDS_PER_DAY) { 756 throw new UnsupportedTemporalTypeException("Unit is too large to be used for truncation"); 757 } 758 long dur = unitDur.toNanos(); 759 if ((LocalTime.NANOS_PER_DAY % dur) != 0) { 760 throw new UnsupportedTemporalTypeException("Unit must divide into a standard day without remainder"); 761 } 762 long nod = (seconds % LocalTime.SECONDS_PER_DAY) * LocalTime.NANOS_PER_SECOND + nanos; 763 long result = Math.floorDiv(nod, dur) * dur; 764 return plusNanos(result - nod); 765 } 766 767 //----------------------------------------------------------------------- 768 /** 769 * Returns a copy of this instant with the specified amount added. 770 * <p> 771 * This returns an {@code Instant}, based on this one, with the specified amount added. 772 * The amount is typically {@link Duration} but may be any other type implementing 773 * the {@link TemporalAmount} interface. 774 * <p> 775 * The calculation is delegated to the amount object by calling 776 * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free 777 * to implement the addition in any way it wishes, however it typically 778 * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation 779 * of the amount implementation to determine if it can be successfully added. 780 * <p> 781 * This instance is immutable and unaffected by this method call. 782 * 783 * @param amountToAdd the amount to add, not null 784 * @return an {@code Instant} based on this instant with the addition made, not null 785 * @throws DateTimeException if the addition cannot be made 786 * @throws ArithmeticException if numeric overflow occurs 787 */ 788 @Override 789 public Instant plus(TemporalAmount amountToAdd) { 790 return (Instant) amountToAdd.addTo(this); 791 } 792 793 /** 794 * Returns a copy of this instant with the specified amount added. 795 * <p> 796 * This returns an {@code Instant}, based on this one, with the amount 797 * in terms of the unit added. If it is not possible to add the amount, because the 798 * unit is not supported or for some other reason, an exception is thrown. 799 * <p> 800 * If the field is a {@link ChronoUnit} then the addition is implemented here. 801 * The supported fields behave as follows: 802 * <ul> 803 * <li>{@code NANOS} - 804 * Returns an {@code Instant} with the specified number of nanoseconds added. 805 * This is equivalent to {@link #plusNanos(long)}. 806 * <li>{@code MICROS} - 807 * Returns an {@code Instant} with the specified number of microseconds added. 808 * This is equivalent to {@link #plusNanos(long)} with the amount 809 * multiplied by 1,000. 810 * <li>{@code MILLIS} - 811 * Returns an {@code Instant} with the specified number of milliseconds added. 812 * This is equivalent to {@link #plusNanos(long)} with the amount 813 * multiplied by 1,000,000. 814 * <li>{@code SECONDS} - 815 * Returns an {@code Instant} with the specified number of seconds added. 816 * This is equivalent to {@link #plusSeconds(long)}. 817 * <li>{@code MINUTES} - 818 * Returns an {@code Instant} with the specified number of minutes added. 819 * This is equivalent to {@link #plusSeconds(long)} with the amount 820 * multiplied by 60. 821 * <li>{@code HOURS} - 822 * Returns an {@code Instant} with the specified number of hours added. 823 * This is equivalent to {@link #plusSeconds(long)} with the amount 824 * multiplied by 3,600. 825 * <li>{@code HALF_DAYS} - 826 * Returns an {@code Instant} with the specified number of half-days added. 827 * This is equivalent to {@link #plusSeconds(long)} with the amount 828 * multiplied by 43,200 (12 hours). 829 * <li>{@code DAYS} - 830 * Returns an {@code Instant} with the specified number of days added. 831 * This is equivalent to {@link #plusSeconds(long)} with the amount 832 * multiplied by 86,400 (24 hours). 833 * </ul> 834 * <p> 835 * All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}. 836 * <p> 837 * If the field is not a {@code ChronoUnit}, then the result of this method 838 * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)} 839 * passing {@code this} as the argument. In this case, the unit determines 840 * whether and how to perform the addition. 841 * <p> 842 * This instance is immutable and unaffected by this method call. 843 * 844 * @param amountToAdd the amount of the unit to add to the result, may be negative 845 * @param unit the unit of the amount to add, not null 846 * @return an {@code Instant} based on this instant with the specified amount added, not null 847 * @throws DateTimeException if the addition cannot be made 848 * @throws UnsupportedTemporalTypeException if the unit is not supported 849 * @throws ArithmeticException if numeric overflow occurs 850 */ 851 @Override 852 public Instant plus(long amountToAdd, TemporalUnit unit) { 853 if (unit instanceof ChronoUnit chronoUnit) { 854 return switch (chronoUnit) { 855 case NANOS -> plusNanos(amountToAdd); 856 case MICROS -> plus(amountToAdd / 1000_000, (amountToAdd % 1000_000) * 1000); 857 case MILLIS -> plusMillis(amountToAdd); 858 case SECONDS -> plusSeconds(amountToAdd); 859 case MINUTES -> plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_MINUTE)); 860 case HOURS -> plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_HOUR)); 861 case HALF_DAYS -> plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY / 2)); 862 case DAYS -> plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY)); 863 default -> throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); 864 }; 865 } 866 return unit.addTo(this, amountToAdd); 867 } 868 869 //----------------------------------------------------------------------- 870 /** 871 * Returns a copy of this instant with the specified duration in seconds added. 872 * <p> 873 * This instance is immutable and unaffected by this method call. 874 * 875 * @param secondsToAdd the seconds to add, positive or negative 876 * @return an {@code Instant} based on this instant with the specified seconds added, not null 877 * @throws DateTimeException if the result exceeds the maximum or minimum instant 878 * @throws ArithmeticException if numeric overflow occurs 879 */ 880 public Instant plusSeconds(long secondsToAdd) { 881 if (secondsToAdd == 0) { 882 return this; 883 } 884 long epochSec = Math.addExact(seconds, secondsToAdd); 885 return create(epochSec, nanos); 886 } 887 888 /** 889 * Returns a copy of this instant with the specified duration in milliseconds added. 890 * <p> 891 * This instance is immutable and unaffected by this method call. 892 * 893 * @param millisToAdd the milliseconds to add, positive or negative 894 * @return an {@code Instant} based on this instant with the specified milliseconds added, not null 895 * @throws DateTimeException if the result exceeds the maximum or minimum instant 896 * @throws ArithmeticException if numeric overflow occurs 897 */ 898 public Instant plusMillis(long millisToAdd) { 899 return plus(millisToAdd / 1000, (millisToAdd % 1000) * 1000_000); 900 } 901 902 /** 903 * Returns a copy of this instant with the specified duration in nanoseconds added. 904 * <p> 905 * This instance is immutable and unaffected by this method call. 906 * 907 * @param nanosToAdd the nanoseconds to add, positive or negative 908 * @return an {@code Instant} based on this instant with the specified nanoseconds added, not null 909 * @throws DateTimeException if the result exceeds the maximum or minimum instant 910 * @throws ArithmeticException if numeric overflow occurs 911 */ 912 public Instant plusNanos(long nanosToAdd) { 913 return plus(0, nanosToAdd); 914 } 915 916 /** 917 * Returns a copy of this instant with the specified duration added. 918 * <p> 919 * This instance is immutable and unaffected by this method call. 920 * 921 * @param secondsToAdd the seconds to add, positive or negative 922 * @param nanosToAdd the nanos to add, positive or negative 923 * @return an {@code Instant} based on this instant with the specified seconds added, not null 924 * @throws DateTimeException if the result exceeds the maximum or minimum instant 925 * @throws ArithmeticException if numeric overflow occurs 926 */ 927 private Instant plus(long secondsToAdd, long nanosToAdd) { 928 if ((secondsToAdd | nanosToAdd) == 0) { 929 return this; 930 } 931 long epochSec = Math.addExact(seconds, secondsToAdd); 932 epochSec = Math.addExact(epochSec, nanosToAdd / NANOS_PER_SECOND); 933 nanosToAdd = nanosToAdd % NANOS_PER_SECOND; 934 long nanoAdjustment = nanos + nanosToAdd; // safe int+NANOS_PER_SECOND 935 return ofEpochSecond(epochSec, nanoAdjustment); 936 } 937 938 //----------------------------------------------------------------------- 939 /** 940 * Returns a copy of this instant with the specified amount subtracted. 941 * <p> 942 * This returns an {@code Instant}, based on this one, with the specified amount subtracted. 943 * The amount is typically {@link Duration} but may be any other type implementing 944 * the {@link TemporalAmount} interface. 945 * <p> 946 * The calculation is delegated to the amount object by calling 947 * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free 948 * to implement the subtraction in any way it wishes, however it typically 949 * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation 950 * of the amount implementation to determine if it can be successfully subtracted. 951 * <p> 952 * This instance is immutable and unaffected by this method call. 953 * 954 * @param amountToSubtract the amount to subtract, not null 955 * @return an {@code Instant} based on this instant with the subtraction made, not null 956 * @throws DateTimeException if the subtraction cannot be made 957 * @throws ArithmeticException if numeric overflow occurs 958 */ 959 @Override 960 public Instant minus(TemporalAmount amountToSubtract) { 961 return (Instant) amountToSubtract.subtractFrom(this); 962 } 963 964 /** 965 * Returns a copy of this instant with the specified amount subtracted. 966 * <p> 967 * This returns an {@code Instant}, based on this one, with the amount 968 * in terms of the unit subtracted. If it is not possible to subtract the amount, 969 * because the unit is not supported or for some other reason, an exception is thrown. 970 * <p> 971 * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated. 972 * See that method for a full description of how addition, and thus subtraction, works. 973 * <p> 974 * This instance is immutable and unaffected by this method call. 975 * 976 * @param amountToSubtract the amount of the unit to subtract from the result, may be negative 977 * @param unit the unit of the amount to subtract, not null 978 * @return an {@code Instant} based on this instant with the specified amount subtracted, not null 979 * @throws DateTimeException if the subtraction cannot be made 980 * @throws UnsupportedTemporalTypeException if the unit is not supported 981 * @throws ArithmeticException if numeric overflow occurs 982 */ 983 @Override 984 public Instant minus(long amountToSubtract, TemporalUnit unit) { 985 return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit)); 986 } 987 988 //----------------------------------------------------------------------- 989 /** 990 * Returns a copy of this instant with the specified duration in seconds subtracted. 991 * <p> 992 * This instance is immutable and unaffected by this method call. 993 * 994 * @param secondsToSubtract the seconds to subtract, positive or negative 995 * @return an {@code Instant} based on this instant with the specified seconds subtracted, not null 996 * @throws DateTimeException if the result exceeds the maximum or minimum instant 997 * @throws ArithmeticException if numeric overflow occurs 998 */ 999 public Instant minusSeconds(long secondsToSubtract) { 1000 if (secondsToSubtract == Long.MIN_VALUE) { 1001 return plusSeconds(Long.MAX_VALUE).plusSeconds(1); 1002 } 1003 return plusSeconds(-secondsToSubtract); 1004 } 1005 1006 /** 1007 * Returns a copy of this instant with the specified duration in milliseconds subtracted. 1008 * <p> 1009 * This instance is immutable and unaffected by this method call. 1010 * 1011 * @param millisToSubtract the milliseconds to subtract, positive or negative 1012 * @return an {@code Instant} based on this instant with the specified milliseconds subtracted, not null 1013 * @throws DateTimeException if the result exceeds the maximum or minimum instant 1014 * @throws ArithmeticException if numeric overflow occurs 1015 */ 1016 public Instant minusMillis(long millisToSubtract) { 1017 if (millisToSubtract == Long.MIN_VALUE) { 1018 return plusMillis(Long.MAX_VALUE).plusMillis(1); 1019 } 1020 return plusMillis(-millisToSubtract); 1021 } 1022 1023 /** 1024 * Returns a copy of this instant with the specified duration in nanoseconds subtracted. 1025 * <p> 1026 * This instance is immutable and unaffected by this method call. 1027 * 1028 * @param nanosToSubtract the nanoseconds to subtract, positive or negative 1029 * @return an {@code Instant} based on this instant with the specified nanoseconds subtracted, not null 1030 * @throws DateTimeException if the result exceeds the maximum or minimum instant 1031 * @throws ArithmeticException if numeric overflow occurs 1032 */ 1033 public Instant minusNanos(long nanosToSubtract) { 1034 if (nanosToSubtract == Long.MIN_VALUE) { 1035 return plusNanos(Long.MAX_VALUE).plusNanos(1); 1036 } 1037 return plusNanos(-nanosToSubtract); 1038 } 1039 1040 //------------------------------------------------------------------------- 1041 /** 1042 * Queries this instant using the specified query. 1043 * <p> 1044 * This queries this instant using the specified query strategy object. 1045 * The {@code TemporalQuery} object defines the logic to be used to 1046 * obtain the result. Read the documentation of the query to understand 1047 * what the result of this method will be. 1048 * <p> 1049 * The result of this method is obtained by invoking the 1050 * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the 1051 * specified query passing {@code this} as the argument. 1052 * 1053 * @param <R> the type of the result 1054 * @param query the query to invoke, not null 1055 * @return the query result, null may be returned (defined by the query) 1056 * @throws DateTimeException if unable to query (defined by the query) 1057 * @throws ArithmeticException if numeric overflow occurs (defined by the query) 1058 */ 1059 @SuppressWarnings("unchecked") 1060 @Override 1061 public <R> R query(TemporalQuery<R> query) { 1062 if (query == TemporalQueries.precision()) { 1063 return (R) NANOS; 1064 } 1065 // inline TemporalAccessor.super.query(query) as an optimization 1066 if (query == TemporalQueries.chronology() || query == TemporalQueries.zoneId() || 1067 query == TemporalQueries.zone() || query == TemporalQueries.offset() || 1068 query == TemporalQueries.localDate() || query == TemporalQueries.localTime()) { 1069 return null; 1070 } 1071 return query.queryFrom(this); 1072 } 1073 1074 /** 1075 * Adjusts the specified temporal object to have this instant. 1076 * <p> 1077 * This returns a temporal object of the same observable type as the input 1078 * with the instant changed to be the same as this. 1079 * <p> 1080 * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)} 1081 * twice, passing {@link ChronoField#INSTANT_SECONDS} and 1082 * {@link ChronoField#NANO_OF_SECOND} as the fields. 1083 * <p> 1084 * In most cases, it is clearer to reverse the calling pattern by using 1085 * {@link Temporal#with(TemporalAdjuster)}: 1086 * <pre> 1087 * // these two lines are equivalent, but the second approach is recommended 1088 * temporal = thisInstant.adjustInto(temporal); 1089 * temporal = temporal.with(thisInstant); 1090 * </pre> 1091 * <p> 1092 * This instance is immutable and unaffected by this method call. 1093 * 1094 * @param temporal the target object to be adjusted, not null 1095 * @return the adjusted object, not null 1096 * @throws DateTimeException if unable to make the adjustment 1097 * @throws ArithmeticException if numeric overflow occurs 1098 */ 1099 @Override 1100 public Temporal adjustInto(Temporal temporal) { 1101 return temporal.with(INSTANT_SECONDS, seconds).with(NANO_OF_SECOND, nanos); 1102 } 1103 1104 /** 1105 * Calculates the amount of time until another instant in terms of the specified unit. 1106 * <p> 1107 * This calculates the amount of time between two {@code Instant} 1108 * objects in terms of a single {@code TemporalUnit}. 1109 * The start and end points are {@code this} and the specified instant. 1110 * The result will be negative if the end is before the start. 1111 * The calculation returns a whole number, representing the number of 1112 * complete units between the two instants. 1113 * The {@code Temporal} passed to this method is converted to a 1114 * {@code Instant} using {@link #from(TemporalAccessor)}. 1115 * For example, the amount in seconds between two dates can be calculated 1116 * using {@code startInstant.until(endInstant, SECONDS)}. 1117 * <p> 1118 * There are two equivalent ways of using this method. 1119 * The first is to invoke this method. 1120 * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}: 1121 * <pre> 1122 * // these two lines are equivalent 1123 * amount = start.until(end, SECONDS); 1124 * amount = SECONDS.between(start, end); 1125 * </pre> 1126 * The choice should be made based on which makes the code more readable. 1127 * <p> 1128 * The calculation is implemented in this method for {@link ChronoUnit}. 1129 * The units {@code NANOS}, {@code MICROS}, {@code MILLIS}, {@code SECONDS}, 1130 * {@code MINUTES}, {@code HOURS}, {@code HALF_DAYS} and {@code DAYS} 1131 * are supported. Other {@code ChronoUnit} values will throw an exception. 1132 * <p> 1133 * If the unit is not a {@code ChronoUnit}, then the result of this method 1134 * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)} 1135 * passing {@code this} as the first argument and the converted input temporal 1136 * as the second argument. 1137 * <p> 1138 * This instance is immutable and unaffected by this method call. 1139 * 1140 * @param endExclusive the end date, exclusive, which is converted to an {@code Instant}, not null 1141 * @param unit the unit to measure the amount in, not null 1142 * @return the amount of time between this instant and the end instant 1143 * @throws DateTimeException if the amount cannot be calculated, or the end 1144 * temporal cannot be converted to an {@code Instant} 1145 * @throws UnsupportedTemporalTypeException if the unit is not supported 1146 * @throws ArithmeticException if numeric overflow occurs 1147 */ 1148 @Override 1149 public long until(Temporal endExclusive, TemporalUnit unit) { 1150 Instant end = Instant.from(endExclusive); 1151 if (unit instanceof ChronoUnit chronoUnit) { 1152 return switch (chronoUnit) { 1153 case NANOS -> nanosUntil(end); 1154 case MICROS -> microsUntil(end); 1155 case MILLIS -> millisUntil(end); 1156 case SECONDS -> secondsUntil(end); 1157 case MINUTES -> secondsUntil(end) / SECONDS_PER_MINUTE; 1158 case HOURS -> secondsUntil(end) / SECONDS_PER_HOUR; 1159 case HALF_DAYS -> secondsUntil(end) / (12 * SECONDS_PER_HOUR); 1160 case DAYS -> secondsUntil(end) / (SECONDS_PER_DAY); 1161 default -> throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); 1162 }; 1163 } 1164 return unit.between(this, end); 1165 } 1166 1167 private long nanosUntil(Instant end) { 1168 long secsDiff = Math.subtractExact(end.seconds, seconds); 1169 long totalNanos = Math.multiplyExact(secsDiff, NANOS_PER_SECOND); 1170 return Math.addExact(totalNanos, end.nanos - nanos); 1171 } 1172 1173 private long microsUntil(Instant end) { 1174 long secsDiff = Math.subtractExact(end.seconds, seconds); 1175 long totalMicros = Math.multiplyExact(secsDiff, MICROS_PER_SECOND); 1176 return Math.addExact(totalMicros, (end.nanos - nanos) / 1000); 1177 } 1178 1179 private long millisUntil(Instant end) { 1180 long secsDiff = Math.subtractExact(end.seconds, seconds); 1181 long totalMillis = Math.multiplyExact(secsDiff, MILLIS_PER_SECOND); 1182 return Math.addExact(totalMillis, (end.nanos - nanos) / 1000_000); 1183 } 1184 1185 private long secondsUntil(Instant end) { 1186 long secsDiff = Math.subtractExact(end.seconds, seconds); 1187 long nanosDiff = end.nanos - nanos; 1188 if (secsDiff > 0 && nanosDiff < 0) { 1189 secsDiff--; 1190 } else if (secsDiff < 0 && nanosDiff > 0) { 1191 secsDiff++; 1192 } 1193 return secsDiff; 1194 } 1195 1196 //----------------------------------------------------------------------- 1197 /** 1198 * Combines this instant with an offset to create an {@code OffsetDateTime}. 1199 * <p> 1200 * This returns an {@code OffsetDateTime} formed from this instant at the 1201 * specified offset from UTC/Greenwich. An exception will be thrown if the 1202 * instant is too large to fit into an offset date-time. 1203 * <p> 1204 * This method is equivalent to 1205 * {@link OffsetDateTime#ofInstant(Instant, ZoneId) OffsetDateTime.ofInstant(this, offset)}. 1206 * 1207 * @param offset the offset to combine with, not null 1208 * @return the offset date-time formed from this instant and the specified offset, not null 1209 * @throws DateTimeException if the result exceeds the supported range 1210 */ 1211 public OffsetDateTime atOffset(ZoneOffset offset) { 1212 return OffsetDateTime.ofInstant(this, offset); 1213 } 1214 1215 /** 1216 * Combines this instant with a time-zone to create a {@code ZonedDateTime}. 1217 * <p> 1218 * This returns an {@code ZonedDateTime} formed from this instant at the 1219 * specified time-zone. An exception will be thrown if the instant is too 1220 * large to fit into a zoned date-time. 1221 * <p> 1222 * This method is equivalent to 1223 * {@link ZonedDateTime#ofInstant(Instant, ZoneId) ZonedDateTime.ofInstant(this, zone)}. 1224 * 1225 * @param zone the zone to combine with, not null 1226 * @return the zoned date-time formed from this instant and the specified zone, not null 1227 * @throws DateTimeException if the result exceeds the supported range 1228 */ 1229 public ZonedDateTime atZone(ZoneId zone) { 1230 return ZonedDateTime.ofInstant(this, zone); 1231 } 1232 1233 //----------------------------------------------------------------------- 1234 /** 1235 * Converts this instant to the number of milliseconds from the epoch 1236 * of 1970-01-01T00:00:00Z. 1237 * <p> 1238 * If this instant represents a point on the time-line too far in the future 1239 * or past to fit in a {@code long} milliseconds, then an exception is thrown. 1240 * <p> 1241 * If this instant has greater than millisecond precision, then the conversion 1242 * will drop any excess precision information as though the amount in nanoseconds 1243 * was subject to integer division by one million. 1244 * 1245 * @return the number of milliseconds since the epoch of 1970-01-01T00:00:00Z 1246 * @throws ArithmeticException if numeric overflow occurs 1247 */ 1248 public long toEpochMilli() { 1249 if (seconds < 0 && nanos > 0) { 1250 long millis = Math.multiplyExact(seconds+1, 1000); 1251 long adjustment = nanos / 1000_000 - 1000; 1252 return Math.addExact(millis, adjustment); 1253 } else { 1254 long millis = Math.multiplyExact(seconds, 1000); 1255 return Math.addExact(millis, nanos / 1000_000); 1256 } 1257 } 1258 1259 //----------------------------------------------------------------------- 1260 /** 1261 * Compares this instant to the specified instant. 1262 * <p> 1263 * The comparison is based on the time-line position of the instants. 1264 * It is "consistent with equals", as defined by {@link Comparable}. 1265 * 1266 * @param otherInstant the other instant to compare to, not null 1267 * @return the comparator value, negative if less, positive if greater 1268 * @throws NullPointerException if otherInstant is null 1269 */ 1270 @Override 1271 public int compareTo(Instant otherInstant) { 1272 int cmp = Long.compare(seconds, otherInstant.seconds); 1273 if (cmp != 0) { 1274 return cmp; 1275 } 1276 return nanos - otherInstant.nanos; 1277 } 1278 1279 /** 1280 * Checks if this instant is after the specified instant. 1281 * <p> 1282 * The comparison is based on the time-line position of the instants. 1283 * 1284 * @param otherInstant the other instant to compare to, not null 1285 * @return true if this instant is after the specified instant 1286 * @throws NullPointerException if otherInstant is null 1287 */ 1288 public boolean isAfter(Instant otherInstant) { 1289 return compareTo(otherInstant) > 0; 1290 } 1291 1292 /** 1293 * Checks if this instant is before the specified instant. 1294 * <p> 1295 * The comparison is based on the time-line position of the instants. 1296 * 1297 * @param otherInstant the other instant to compare to, not null 1298 * @return true if this instant is before the specified instant 1299 * @throws NullPointerException if otherInstant is null 1300 */ 1301 public boolean isBefore(Instant otherInstant) { 1302 return compareTo(otherInstant) < 0; 1303 } 1304 1305 //----------------------------------------------------------------------- 1306 /** 1307 * Checks if this instant is equal to the specified instant. 1308 * <p> 1309 * The comparison is based on the time-line position of the instants. 1310 * 1311 * @param other the other instant, null returns false 1312 * @return true if the other instant is equal to this one 1313 */ 1314 @Override 1315 public boolean equals(Object other) { 1316 if (this == other) { 1317 return true; 1318 } 1319 return (other instanceof Instant otherInstant) 1320 && this.seconds == otherInstant.seconds 1321 && this.nanos == otherInstant.nanos; 1322 } 1323 1324 /** 1325 * Returns a hash code for this instant. 1326 * 1327 * @return a suitable hash code 1328 */ 1329 @Override 1330 public int hashCode() { 1331 return ((int) (seconds ^ (seconds >>> 32))) + 51 * nanos; 1332 } 1333 1334 //----------------------------------------------------------------------- 1335 /** 1336 * A string representation of this instant using ISO-8601 representation. 1337 * <p> 1338 * The format used is the same as {@link DateTimeFormatter#ISO_INSTANT}. 1339 * 1340 * @return an ISO-8601 representation of this instant, not null 1341 */ 1342 @Override 1343 public String toString() { 1344 return DateTimeFormatter.ISO_INSTANT.format(this); 1345 } 1346 1347 // ----------------------------------------------------------------------- 1348 /** 1349 * Writes the object using a 1350 * <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>. 1351 * @serialData 1352 * <pre> 1353 * out.writeByte(2); // identifies an Instant 1354 * out.writeLong(seconds); 1355 * out.writeInt(nanos); 1356 * </pre> 1357 * 1358 * @return the instance of {@code Ser}, not null 1359 */ 1360 @java.io.Serial 1361 private Object writeReplace() { 1362 return new Ser(Ser.INSTANT_TYPE, this); 1363 } 1364 1365 /** 1366 * Defend against malicious streams. 1367 * 1368 * @param s the stream to read 1369 * @throws InvalidObjectException always 1370 */ 1371 @java.io.Serial 1372 private void readObject(ObjectInputStream s) throws InvalidObjectException { 1373 throw new InvalidObjectException("Deserialization via serialization delegate"); 1374 } 1375 1376 void writeExternal(DataOutput out) throws IOException { 1377 out.writeLong(seconds); 1378 out.writeInt(nanos); 1379 } 1380 1381 static Instant readExternal(DataInput in) throws IOException { 1382 long seconds = in.readLong(); 1383 int nanos = in.readInt(); 1384 return Instant.ofEpochSecond(seconds, nanos); 1385 } 1386 1387 }