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