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