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.NANOS_PER_HOUR;
65 import static java.time.LocalTime.NANOS_PER_MINUTE;
66 import static java.time.LocalTime.NANOS_PER_SECOND;
67 import static java.time.LocalTime.SECONDS_PER_DAY;
68 import static java.time.temporal.ChronoField.NANO_OF_DAY;
69 import static java.time.temporal.ChronoField.OFFSET_SECONDS;
70 import static java.time.temporal.ChronoUnit.NANOS;
71
72 import java.io.IOException;
73 import java.io.ObjectInput;
74 import java.io.ObjectOutput;
75 import java.io.InvalidObjectException;
76 import java.io.ObjectInputStream;
77 import java.io.Serializable;
78 import java.time.format.DateTimeFormatter;
79 import java.time.format.DateTimeParseException;
80 import java.time.temporal.ChronoField;
81 import java.time.temporal.ChronoUnit;
82 import java.time.temporal.Temporal;
83 import java.time.temporal.TemporalAccessor;
84 import java.time.temporal.TemporalAdjuster;
85 import java.time.temporal.TemporalAmount;
86 import java.time.temporal.TemporalField;
87 import java.time.temporal.TemporalQueries;
88 import java.time.temporal.TemporalQuery;
89 import java.time.temporal.TemporalUnit;
90 import java.time.temporal.UnsupportedTemporalTypeException;
91 import java.time.temporal.ValueRange;
92 import java.time.zone.ZoneRules;
93 import java.util.Objects;
94
95 import jdk.internal.util.DateTimeHelper;
96
97 /**
98 * A time with an offset from UTC/Greenwich in the ISO-8601 calendar system,
99 * such as {@code 10:15:30+01:00}.
100 * <p>
101 * {@code OffsetTime} is an immutable date-time object that represents a time, often
102 * viewed as hour-minute-second-offset.
103 * This class stores all time fields, to a precision of nanoseconds,
104 * as well as a zone offset.
105 * For example, the value "13:45:30.123456789+02:00" can be stored
106 * in an {@code OffsetTime}.
107 * <p>
108 * This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
109 * class; programmers should treat instances that are
110 * {@linkplain #equals(Object) equal} as interchangeable and should not
111 * use instances for synchronization, or unpredictable behavior may
112 * occur. For example, in a future release, synchronization may fail.
113 * The {@code equals} method should be used for comparisons.
114 *
115 * @implSpec
116 * This class is immutable and thread-safe.
117 *
118 * @since 1.8
119 */
120 @jdk.internal.ValueBased
121 public final class OffsetTime
122 implements Temporal, TemporalAdjuster, Comparable<OffsetTime>, Serializable {
123
124 /**
125 * The minimum supported {@code OffsetTime}, '00:00:00+18:00'.
126 * This is the time of midnight at the start of the day in the maximum offset
127 * (larger offsets are earlier on the time-line).
128 * This combines {@link LocalTime#MIN} and {@link ZoneOffset#MAX}.
129 * This could be used by an application as a "far past" date.
130 */
131 public static final OffsetTime MIN = LocalTime.MIN.atOffset(ZoneOffset.MAX);
132 /**
133 * The maximum supported {@code OffsetTime}, '23:59:59.999999999-18:00'.
134 * This is the time just before midnight at the end of the day in the minimum offset
135 * (larger negative offsets are later on the time-line).
136 * This combines {@link LocalTime#MAX} and {@link ZoneOffset#MIN}.
137 * This could be used by an application as a "far future" date.
138 */
139 public static final OffsetTime MAX = LocalTime.MAX.atOffset(ZoneOffset.MIN);
140
141 /**
142 * Serialization version.
143 */
144 @java.io.Serial
145 private static final long serialVersionUID = 7264499704384272492L;
146
147 /**
148 * @serial The local date-time.
149 */
150 private final LocalTime time;
151 /**
152 * @serial The offset from UTC/Greenwich.
153 */
154 private final ZoneOffset offset;
155
156 //-----------------------------------------------------------------------
157 /**
158 * Obtains the current time from the system clock in the default time-zone.
159 * <p>
160 * This will query the {@link Clock#systemDefaultZone() system clock} in the default
161 * time-zone to obtain the current time.
162 * The offset will be calculated from the time-zone in the clock.
163 * <p>
164 * Using this method will prevent the ability to use an alternate clock for testing
165 * because the clock is hard-coded.
166 *
167 * @return the current time using the system clock and default time-zone, not null
168 */
169 public static OffsetTime now() {
170 return now(Clock.systemDefaultZone());
171 }
172
173 /**
174 * Obtains the current time from the system clock in the specified time-zone.
175 * <p>
176 * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current time.
177 * Specifying the time-zone avoids dependence on the default time-zone.
178 * The offset will be calculated from the specified time-zone.
179 * <p>
180 * Using this method will prevent the ability to use an alternate clock for testing
181 * because the clock is hard-coded.
182 *
183 * @param zone the zone ID to use, not null
184 * @return the current time using the system clock, not null
185 */
186 public static OffsetTime now(ZoneId zone) {
187 return now(Clock.system(zone));
188 }
189
190 /**
191 * Obtains the current time from the specified clock.
192 * <p>
193 * This will query the specified clock to obtain the current time.
194 * The offset will be calculated from the time-zone in the clock.
195 * <p>
196 * Using this method allows the use of an alternate clock for testing.
197 * The alternate clock may be introduced using {@link Clock dependency injection}.
198 *
199 * @param clock the clock to use, not null
200 * @return the current time, not null
201 */
202 public static OffsetTime now(Clock clock) {
203 Objects.requireNonNull(clock, "clock");
204 final Instant now = clock.instant(); // called once
205 return ofInstant(now, clock.getZone().getRules().getOffset(now));
206 }
207
208 //-----------------------------------------------------------------------
209 /**
210 * Obtains an instance of {@code OffsetTime} from a local time and an offset.
211 *
212 * @param time the local time, not null
213 * @param offset the zone offset, not null
214 * @return the offset time, not null
215 */
216 public static OffsetTime of(LocalTime time, ZoneOffset offset) {
217 return new OffsetTime(time, offset);
218 }
219
220 /**
221 * Obtains an instance of {@code OffsetTime} from an hour, minute, second and nanosecond.
222 * <p>
223 * This creates an offset time with the four specified fields.
224 * <p>
225 * This method exists primarily for writing test cases.
226 * Non test-code will typically use other methods to create an offset time.
227 * {@code LocalTime} has two additional convenience variants of the
228 * equivalent factory method taking fewer arguments.
229 * They are not provided here to reduce the footprint of the API.
230 *
231 * @param hour the hour-of-day to represent, from 0 to 23
232 * @param minute the minute-of-hour to represent, from 0 to 59
233 * @param second the second-of-minute to represent, from 0 to 59
234 * @param nanoOfSecond the nano-of-second to represent, from 0 to 999,999,999
235 * @param offset the zone offset, not null
236 * @return the offset time, not null
237 * @throws DateTimeException if the value of any field is out of range
238 */
239 public static OffsetTime of(int hour, int minute, int second, int nanoOfSecond, ZoneOffset offset) {
240 return new OffsetTime(LocalTime.of(hour, minute, second, nanoOfSecond), offset);
241 }
242
243 //-----------------------------------------------------------------------
244 /**
245 * Obtains an instance of {@code OffsetTime} from an {@code Instant} and zone ID.
246 * <p>
247 * This creates an offset time with the same instant as that specified.
248 * Finding the offset from UTC/Greenwich is simple as there is only one valid
249 * offset for each instant.
250 * <p>
251 * The date component of the instant is dropped during the conversion.
252 * This means that the conversion can never fail due to the instant being
253 * out of the valid range of dates.
254 *
255 * @param instant the instant to create the time from, not null
256 * @param zone the time-zone, which may be an offset, not null
257 * @return the offset time, not null
258 */
259 public static OffsetTime ofInstant(Instant instant, ZoneId zone) {
260 Objects.requireNonNull(instant, "instant");
261 Objects.requireNonNull(zone, "zone");
262 ZoneRules rules = zone.getRules();
263 ZoneOffset offset = rules.getOffset(instant);
264 long localSecond = instant.getEpochSecond() + offset.getTotalSeconds(); // overflow caught later
265 int secsOfDay = Math.floorMod(localSecond, SECONDS_PER_DAY);
266 LocalTime time = LocalTime.ofNanoOfDay(secsOfDay * NANOS_PER_SECOND + instant.getNano());
267 return new OffsetTime(time, offset);
268 }
269
270 //-----------------------------------------------------------------------
271 /**
272 * Obtains an instance of {@code OffsetTime} from a temporal object.
273 * <p>
274 * This obtains an offset time based on the specified temporal.
275 * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
276 * which this factory converts to an instance of {@code OffsetTime}.
277 * <p>
278 * The conversion extracts and combines the {@code ZoneOffset} and the
279 * {@code LocalTime} from the temporal object.
280 * Implementations are permitted to perform optimizations such as accessing
281 * those fields that are equivalent to the relevant objects.
282 * <p>
283 * This method matches the signature of the functional interface {@link TemporalQuery}
284 * allowing it to be used as a query via method reference, {@code OffsetTime::from}.
285 *
286 * @param temporal the temporal object to convert, not null
287 * @return the offset time, not null
288 * @throws DateTimeException if unable to convert to an {@code OffsetTime}
289 */
290 public static OffsetTime from(TemporalAccessor temporal) {
291 if (temporal instanceof OffsetTime) {
292 return (OffsetTime) temporal;
293 }
294 try {
295 LocalTime time = LocalTime.from(temporal);
296 ZoneOffset offset = ZoneOffset.from(temporal);
297 return new OffsetTime(time, offset);
298 } catch (DateTimeException ex) {
299 throw new DateTimeException("Unable to obtain OffsetTime from TemporalAccessor: " +
300 temporal + " of type " + temporal.getClass().getName(), ex);
301 }
302 }
303
304 //-----------------------------------------------------------------------
305 /**
306 * Obtains an instance of {@code OffsetTime} from a text string such as {@code 10:15:30+01:00}.
307 * <p>
308 * The string must represent a valid time and is parsed using
309 * {@link java.time.format.DateTimeFormatter#ISO_OFFSET_TIME}.
310 *
311 * @param text the text to parse such as "10:15:30+01:00", not null
312 * @return the parsed local time, not null
313 * @throws DateTimeParseException if the text cannot be parsed
314 */
315 public static OffsetTime parse(CharSequence text) {
316 return parse(text, DateTimeFormatter.ISO_OFFSET_TIME);
317 }
318
319 /**
320 * Obtains an instance of {@code OffsetTime} from a text string using a specific formatter.
321 * <p>
322 * The text is parsed using the formatter, returning a time.
323 *
324 * @param text the text to parse, not null
325 * @param formatter the formatter to use, not null
326 * @return the parsed offset time, not null
327 * @throws DateTimeParseException if the text cannot be parsed
328 */
329 public static OffsetTime parse(CharSequence text, DateTimeFormatter formatter) {
330 Objects.requireNonNull(formatter, "formatter");
331 return formatter.parse(text, OffsetTime::from);
332 }
333
334 //-----------------------------------------------------------------------
335 /**
336 * Constructor.
337 *
338 * @param time the local time, not null
339 * @param offset the zone offset, not null
340 */
341 private OffsetTime(LocalTime time, ZoneOffset offset) {
342 this.time = Objects.requireNonNull(time, "time");
343 this.offset = Objects.requireNonNull(offset, "offset");
344 }
345
346 /**
347 * Returns a new time based on this one, returning {@code this} where possible.
348 *
349 * @param time the time to create with, not null
350 * @param offset the zone offset to create with, not null
351 */
352 private OffsetTime with(LocalTime time, ZoneOffset offset) {
353 if (this.time == time && this.offset.equals(offset)) {
354 return this;
355 }
356 return new OffsetTime(time, offset);
357 }
358
359 //-----------------------------------------------------------------------
360 /**
361 * Checks if the specified field is supported.
362 * <p>
363 * This checks if this time can be queried for the specified field.
364 * If false, then calling the {@link #range(TemporalField) range},
365 * {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}
366 * methods will throw an exception.
367 * <p>
368 * If the field is a {@link ChronoField} then the query is implemented here.
369 * The supported fields are:
370 * <ul>
371 * <li>{@code NANO_OF_SECOND}
372 * <li>{@code NANO_OF_DAY}
373 * <li>{@code MICRO_OF_SECOND}
374 * <li>{@code MICRO_OF_DAY}
375 * <li>{@code MILLI_OF_SECOND}
376 * <li>{@code MILLI_OF_DAY}
377 * <li>{@code SECOND_OF_MINUTE}
378 * <li>{@code SECOND_OF_DAY}
379 * <li>{@code MINUTE_OF_HOUR}
380 * <li>{@code MINUTE_OF_DAY}
381 * <li>{@code HOUR_OF_AMPM}
382 * <li>{@code CLOCK_HOUR_OF_AMPM}
383 * <li>{@code HOUR_OF_DAY}
384 * <li>{@code CLOCK_HOUR_OF_DAY}
385 * <li>{@code AMPM_OF_DAY}
386 * <li>{@code OFFSET_SECONDS}
387 * </ul>
388 * All other {@code ChronoField} instances will return false.
389 * <p>
390 * If the field is not a {@code ChronoField}, then the result of this method
391 * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
392 * passing {@code this} as the argument.
393 * Whether the field is supported is determined by the field.
394 *
395 * @param field the field to check, null returns false
396 * @return true if the field is supported on this time, false if not
397 */
398 @Override
399 public boolean isSupported(TemporalField field) {
400 if (field instanceof ChronoField) {
401 return field.isTimeBased() || field == OFFSET_SECONDS;
402 }
403 return field != null && field.isSupportedBy(this);
404 }
405
406 /**
407 * Checks if the specified unit is supported.
408 * <p>
409 * This checks if the specified unit can be added to, or subtracted from, this offset-time.
410 * If false, then calling the {@link #plus(long, TemporalUnit)} and
411 * {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
412 * <p>
413 * If the unit is a {@link ChronoUnit} then the query is implemented here.
414 * The supported units are:
415 * <ul>
416 * <li>{@code NANOS}
417 * <li>{@code MICROS}
418 * <li>{@code MILLIS}
419 * <li>{@code SECONDS}
420 * <li>{@code MINUTES}
421 * <li>{@code HOURS}
422 * <li>{@code HALF_DAYS}
423 * </ul>
424 * All other {@code ChronoUnit} instances will return false.
425 * <p>
426 * If the unit is not a {@code ChronoUnit}, then the result of this method
427 * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}
428 * passing {@code this} as the argument.
429 * Whether the unit is supported is determined by the unit.
430 *
431 * @param unit the unit to check, null returns false
432 * @return true if the unit can be added/subtracted, false if not
433 */
434 @Override // override for Javadoc
435 public boolean isSupported(TemporalUnit unit) {
436 if (unit instanceof ChronoUnit) {
437 return unit.isTimeBased();
438 }
439 return unit != null && unit.isSupportedBy(this);
440 }
441
442 //-----------------------------------------------------------------------
443 /**
444 * Gets the range of valid values for the specified field.
445 * <p>
446 * The range object expresses the minimum and maximum valid values for a field.
447 * This time is used to enhance the accuracy of the returned range.
448 * If it is not possible to return the range, because the field is not supported
449 * or for some other reason, an exception is thrown.
450 * <p>
451 * If the field is a {@link ChronoField} then the query is implemented here.
452 * The {@link #isSupported(TemporalField) supported fields} will return
453 * appropriate range instances.
454 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
455 * <p>
456 * If the field is not a {@code ChronoField}, then the result of this method
457 * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
458 * passing {@code this} as the argument.
459 * Whether the range can be obtained is determined by the field.
460 *
461 * @param field the field to query the range for, not null
462 * @return the range of valid values for the field, not null
463 * @throws DateTimeException if the range for the field cannot be obtained
464 * @throws UnsupportedTemporalTypeException if the field is not supported
465 */
466 @Override
467 public ValueRange range(TemporalField field) {
468 if (field instanceof ChronoField) {
469 if (field == OFFSET_SECONDS) {
470 return field.range();
471 }
472 return time.range(field);
473 }
474 return field.rangeRefinedBy(this);
475 }
476
477 /**
478 * Gets the value of the specified field from this time as an {@code int}.
479 * <p>
480 * This queries this time for the value of the specified field.
481 * The returned value will always be within the valid range of values for the field.
482 * If it is not possible to return the value, because the field is not supported
483 * or for some other reason, an exception is thrown.
484 * <p>
485 * If the field is a {@link ChronoField} then the query is implemented here.
486 * The {@link #isSupported(TemporalField) supported fields} will return valid
487 * values based on this time, except {@code NANO_OF_DAY} and {@code MICRO_OF_DAY}
488 * which are too large to fit in an {@code int} and throw an {@code UnsupportedTemporalTypeException}.
489 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
490 * <p>
491 * If the field is not a {@code ChronoField}, then the result of this method
492 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
493 * passing {@code this} as the argument. Whether the value can be obtained,
494 * and what the value represents, is determined by the field.
495 *
496 * @param field the field to get, not null
497 * @return the value for the field
498 * @throws DateTimeException if a value for the field cannot be obtained or
499 * the value is outside the range of valid values for the field
500 * @throws UnsupportedTemporalTypeException if the field is not supported or
501 * the range of values exceeds an {@code int}
502 * @throws ArithmeticException if numeric overflow occurs
503 */
504 @Override // override for Javadoc
505 public int get(TemporalField field) {
506 return Temporal.super.get(field);
507 }
508
509 /**
510 * Gets the value of the specified field from this time as a {@code long}.
511 * <p>
512 * This queries this time for the value of the specified field.
513 * If it is not possible to return the value, because the field is not supported
514 * or for some other reason, an exception is thrown.
515 * <p>
516 * If the field is a {@link ChronoField} then the query is implemented here.
517 * The {@link #isSupported(TemporalField) supported fields} will return valid
518 * values based on this time.
519 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
520 * <p>
521 * If the field is not a {@code ChronoField}, then the result of this method
522 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
523 * passing {@code this} as the argument. Whether the value can be obtained,
524 * and what the value represents, is determined by the field.
525 *
526 * @param field the field to get, not null
527 * @return the value for the field
528 * @throws DateTimeException if a value for the field cannot be obtained
529 * @throws UnsupportedTemporalTypeException if the field is not supported
530 * @throws ArithmeticException if numeric overflow occurs
531 */
532 @Override
533 public long getLong(TemporalField field) {
534 if (field instanceof ChronoField) {
535 if (field == OFFSET_SECONDS) {
536 return offset.getTotalSeconds();
537 }
538 return time.getLong(field);
539 }
540 return field.getFrom(this);
541 }
542
543 //-----------------------------------------------------------------------
544 /**
545 * Gets the zone offset, such as '+01:00'.
546 * <p>
547 * This is the offset of the local time from UTC/Greenwich.
548 *
549 * @return the zone offset, not null
550 */
551 public ZoneOffset getOffset() {
552 return offset;
553 }
554
555 /**
556 * Returns a copy of this {@code OffsetTime} with the specified offset ensuring
557 * that the result has the same local time.
558 * <p>
559 * This method returns an object with the same {@code LocalTime} and the specified {@code ZoneOffset}.
560 * No calculation is needed or performed.
561 * For example, if this time represents {@code 10:30+02:00} and the offset specified is
562 * {@code +03:00}, then this method will return {@code 10:30+03:00}.
563 * <p>
564 * To take into account the difference between the offsets, and adjust the time fields,
565 * use {@link #withOffsetSameInstant}.
566 * <p>
567 * This instance is immutable and unaffected by this method call.
568 *
569 * @param offset the zone offset to change to, not null
570 * @return an {@code OffsetTime} based on this time with the requested offset, not null
571 */
572 public OffsetTime withOffsetSameLocal(ZoneOffset offset) {
573 return offset != null && offset.equals(this.offset) ? this : new OffsetTime(time, offset);
574 }
575
576 /**
577 * Returns a copy of this {@code OffsetTime} with the specified offset ensuring
578 * that the result is at the same instant on an implied day.
579 * <p>
580 * This method returns an object with the specified {@code ZoneOffset} and a {@code LocalTime}
581 * adjusted by the difference between the two offsets.
582 * This will result in the old and new objects representing the same instant on an implied day.
583 * This is useful for finding the local time in a different offset.
584 * For example, if this time represents {@code 10:30+02:00} and the offset specified is
585 * {@code +03:00}, then this method will return {@code 11:30+03:00}.
586 * <p>
587 * To change the offset without adjusting the local time use {@link #withOffsetSameLocal}.
588 * <p>
589 * This instance is immutable and unaffected by this method call.
590 *
591 * @param offset the zone offset to change to, not null
592 * @return an {@code OffsetTime} based on this time with the requested offset, not null
593 */
594 public OffsetTime withOffsetSameInstant(ZoneOffset offset) {
595 if (offset.equals(this.offset)) {
596 return this;
597 }
598 int difference = offset.getTotalSeconds() - this.offset.getTotalSeconds();
599 LocalTime adjusted = time.plusSeconds(difference);
600 return new OffsetTime(adjusted, offset);
601 }
602
603 //-----------------------------------------------------------------------
604 /**
605 * Gets the {@code LocalTime} part of this date-time.
606 * <p>
607 * This returns a {@code LocalTime} with the same hour, minute, second and
608 * nanosecond as this date-time.
609 *
610 * @return the time part of this date-time, not null
611 */
612 public LocalTime toLocalTime() {
613 return time;
614 }
615
616 //-----------------------------------------------------------------------
617 /**
618 * Gets the hour-of-day field.
619 *
620 * @return the hour-of-day, from 0 to 23
621 */
622 public int getHour() {
623 return time.getHour();
624 }
625
626 /**
627 * Gets the minute-of-hour field.
628 *
629 * @return the minute-of-hour, from 0 to 59
630 */
631 public int getMinute() {
632 return time.getMinute();
633 }
634
635 /**
636 * Gets the second-of-minute field.
637 *
638 * @return the second-of-minute, from 0 to 59
639 */
640 public int getSecond() {
641 return time.getSecond();
642 }
643
644 /**
645 * Gets the nano-of-second field.
646 *
647 * @return the nano-of-second, from 0 to 999,999,999
648 */
649 public int getNano() {
650 return time.getNano();
651 }
652
653 //-----------------------------------------------------------------------
654 /**
655 * Returns an adjusted copy of this time.
656 * <p>
657 * This returns an {@code OffsetTime}, based on this one, with the time adjusted.
658 * The adjustment takes place using the specified adjuster strategy object.
659 * Read the documentation of the adjuster to understand what adjustment will be made.
660 * <p>
661 * A simple adjuster might simply set the one of the fields, such as the hour field.
662 * A more complex adjuster might set the time to the last hour of the day.
663 * <p>
664 * The classes {@link LocalTime} and {@link ZoneOffset} implement {@code TemporalAdjuster},
665 * thus this method can be used to change the time or offset:
666 * <pre>
667 * result = offsetTime.with(time);
668 * result = offsetTime.with(offset);
669 * </pre>
670 * <p>
671 * The result of this method is obtained by invoking the
672 * {@link TemporalAdjuster#adjustInto(Temporal)} method on the
673 * specified adjuster passing {@code this} as the argument.
674 * <p>
675 * This instance is immutable and unaffected by this method call.
676 *
677 * @param adjuster the adjuster to use, not null
678 * @return an {@code OffsetTime} based on {@code this} with the adjustment made, not null
679 * @throws DateTimeException if the adjustment cannot be made
680 * @throws ArithmeticException if numeric overflow occurs
681 */
682 @Override
683 public OffsetTime with(TemporalAdjuster adjuster) {
684 // optimizations
685 if (adjuster instanceof LocalTime) {
686 return with((LocalTime) adjuster, offset);
687 } else if (adjuster instanceof ZoneOffset) {
688 return with(time, (ZoneOffset) adjuster);
689 } else if (adjuster instanceof OffsetTime) {
690 return (OffsetTime) adjuster;
691 }
692 return (OffsetTime) adjuster.adjustInto(this);
693 }
694
695 /**
696 * Returns a copy of this time with the specified field set to a new value.
697 * <p>
698 * This returns an {@code OffsetTime}, based on this one, with the value
699 * for the specified field changed.
700 * This can be used to change any supported field, such as the hour, minute or second.
701 * If it is not possible to set the value, because the field is not supported or for
702 * some other reason, an exception is thrown.
703 * <p>
704 * If the field is a {@link ChronoField} then the adjustment is implemented here.
705 * <p>
706 * The {@code OFFSET_SECONDS} field will return a time with the specified offset.
707 * The local time is unaltered. If the new offset value is outside the valid range
708 * then a {@code DateTimeException} will be thrown.
709 * <p>
710 * The other {@link #isSupported(TemporalField) supported fields} will behave as per
711 * the matching method on {@link LocalTime#with(TemporalField, long)} LocalTime}.
712 * In this case, the offset is not part of the calculation and will be unchanged.
713 * <p>
714 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
715 * <p>
716 * If the field is not a {@code ChronoField}, then the result of this method
717 * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
718 * passing {@code this} as the argument. In this case, the field determines
719 * whether and how to adjust the instant.
720 * <p>
721 * This instance is immutable and unaffected by this method call.
722 *
723 * @param field the field to set in the result, not null
724 * @param newValue the new value of the field in the result
725 * @return an {@code OffsetTime} based on {@code this} with the specified field set, not null
726 * @throws DateTimeException if the field cannot be set
727 * @throws UnsupportedTemporalTypeException if the field is not supported
728 * @throws ArithmeticException if numeric overflow occurs
729 */
730 @Override
731 public OffsetTime with(TemporalField field, long newValue) {
732 if (field instanceof ChronoField) {
733 if (field == OFFSET_SECONDS) {
734 ChronoField f = (ChronoField) field;
735 return with(time, ZoneOffset.ofTotalSeconds(f.checkValidIntValue(newValue)));
736 }
737 return with(time.with(field, newValue), offset);
738 }
739 return field.adjustInto(this, newValue);
740 }
741
742 //-----------------------------------------------------------------------
743 /**
744 * Returns a copy of this {@code OffsetTime} with the hour-of-day altered.
745 * <p>
746 * The offset does not affect the calculation and will be the same in the result.
747 * <p>
748 * This instance is immutable and unaffected by this method call.
749 *
750 * @param hour the hour-of-day to set in the result, from 0 to 23
751 * @return an {@code OffsetTime} based on this time with the requested hour, not null
752 * @throws DateTimeException if the hour value is invalid
753 */
754 public OffsetTime withHour(int hour) {
755 return with(time.withHour(hour), offset);
756 }
757
758 /**
759 * Returns a copy of this {@code OffsetTime} with the minute-of-hour altered.
760 * <p>
761 * The offset does not affect the calculation and will be the same in the result.
762 * <p>
763 * This instance is immutable and unaffected by this method call.
764 *
765 * @param minute the minute-of-hour to set in the result, from 0 to 59
766 * @return an {@code OffsetTime} based on this time with the requested minute, not null
767 * @throws DateTimeException if the minute value is invalid
768 */
769 public OffsetTime withMinute(int minute) {
770 return with(time.withMinute(minute), offset);
771 }
772
773 /**
774 * Returns a copy of this {@code OffsetTime} with the second-of-minute altered.
775 * <p>
776 * The offset does not affect the calculation and will be the same in the result.
777 * <p>
778 * This instance is immutable and unaffected by this method call.
779 *
780 * @param second the second-of-minute to set in the result, from 0 to 59
781 * @return an {@code OffsetTime} based on this time with the requested second, not null
782 * @throws DateTimeException if the second value is invalid
783 */
784 public OffsetTime withSecond(int second) {
785 return with(time.withSecond(second), offset);
786 }
787
788 /**
789 * Returns a copy of this {@code OffsetTime} with the nano-of-second altered.
790 * <p>
791 * The offset does not affect the calculation and will be the same in the result.
792 * <p>
793 * This instance is immutable and unaffected by this method call.
794 *
795 * @param nanoOfSecond the nano-of-second to set in the result, from 0 to 999,999,999
796 * @return an {@code OffsetTime} based on this time with the requested nanosecond, not null
797 * @throws DateTimeException if the nanos value is invalid
798 */
799 public OffsetTime withNano(int nanoOfSecond) {
800 return with(time.withNano(nanoOfSecond), offset);
801 }
802
803 //-----------------------------------------------------------------------
804 /**
805 * Returns a copy of this {@code OffsetTime} with the time truncated.
806 * <p>
807 * Truncation returns a copy of the original time with fields
808 * smaller than the specified unit set to zero.
809 * For example, truncating with the {@link ChronoUnit#MINUTES minutes} unit
810 * will set the second-of-minute and nano-of-second field to zero.
811 * <p>
812 * The unit must have a {@linkplain TemporalUnit#getDuration() duration}
813 * that divides into the length of a standard day without remainder.
814 * This includes all supplied time units on {@link ChronoUnit} and
815 * {@link ChronoUnit#DAYS DAYS}. Other units throw an exception.
816 * <p>
817 * The offset does not affect the calculation and will be the same in the result.
818 * <p>
819 * This instance is immutable and unaffected by this method call.
820 *
821 * @param unit the unit to truncate to, not null
822 * @return an {@code OffsetTime} based on this time with the time truncated, not null
823 * @throws DateTimeException if unable to truncate
824 * @throws UnsupportedTemporalTypeException if the unit is not supported
825 */
826 public OffsetTime truncatedTo(TemporalUnit unit) {
827 return with(time.truncatedTo(unit), offset);
828 }
829
830 //-----------------------------------------------------------------------
831 /**
832 * Returns a copy of this time with the specified amount added.
833 * <p>
834 * This returns an {@code OffsetTime}, based on this one, with the specified amount added.
835 * The amount is typically {@link Duration} but may be any other type implementing
836 * the {@link TemporalAmount} interface.
837 * <p>
838 * The calculation is delegated to the amount object by calling
839 * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free
840 * to implement the addition in any way it wishes, however it typically
841 * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation
842 * of the amount implementation to determine if it can be successfully added.
843 * <p>
844 * This instance is immutable and unaffected by this method call.
845 *
846 * @param amountToAdd the amount to add, not null
847 * @return an {@code OffsetTime} based on this time with the addition made, not null
848 * @throws DateTimeException if the addition cannot be made
849 * @throws ArithmeticException if numeric overflow occurs
850 */
851 @Override
852 public OffsetTime plus(TemporalAmount amountToAdd) {
853 return (OffsetTime) amountToAdd.addTo(this);
854 }
855
856 /**
857 * Returns a copy of this time with the specified amount added.
858 * <p>
859 * This returns an {@code OffsetTime}, based on this one, with the amount
860 * in terms of the unit added. If it is not possible to add the amount, because the
861 * unit is not supported or for some other reason, an exception is thrown.
862 * <p>
863 * If the field is a {@link ChronoUnit} then the addition is implemented by
864 * {@link LocalTime#plus(long, TemporalUnit)}.
865 * The offset is not part of the calculation and will be unchanged in the result.
866 * <p>
867 * If the field is not a {@code ChronoUnit}, then the result of this method
868 * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
869 * passing {@code this} as the argument. In this case, the unit determines
870 * whether and how to perform the addition.
871 * <p>
872 * This instance is immutable and unaffected by this method call.
873 *
874 * @param amountToAdd the amount of the unit to add to the result, may be negative
875 * @param unit the unit of the amount to add, not null
876 * @return an {@code OffsetTime} based on this time with the specified amount added, not null
877 * @throws DateTimeException if the addition cannot be made
878 * @throws UnsupportedTemporalTypeException if the unit is not supported
879 * @throws ArithmeticException if numeric overflow occurs
880 */
881 @Override
882 public OffsetTime plus(long amountToAdd, TemporalUnit unit) {
883 if (unit instanceof ChronoUnit) {
884 return with(time.plus(amountToAdd, unit), offset);
885 }
886 return unit.addTo(this, amountToAdd);
887 }
888
889 //-----------------------------------------------------------------------
890 /**
891 * Returns a copy of this {@code OffsetTime} with the specified number of hours added.
892 * <p>
893 * This adds the specified number of hours to this time, returning a new time.
894 * The calculation wraps around midnight.
895 * <p>
896 * This instance is immutable and unaffected by this method call.
897 *
898 * @param hours the hours to add, may be negative
899 * @return an {@code OffsetTime} based on this time with the hours added, not null
900 */
901 public OffsetTime plusHours(long hours) {
902 return with(time.plusHours(hours), offset);
903 }
904
905 /**
906 * Returns a copy of this {@code OffsetTime} with the specified number of minutes added.
907 * <p>
908 * This adds the specified number of minutes to this time, returning a new time.
909 * The calculation wraps around midnight.
910 * <p>
911 * This instance is immutable and unaffected by this method call.
912 *
913 * @param minutes the minutes to add, may be negative
914 * @return an {@code OffsetTime} based on this time with the minutes added, not null
915 */
916 public OffsetTime plusMinutes(long minutes) {
917 return with(time.plusMinutes(minutes), offset);
918 }
919
920 /**
921 * Returns a copy of this {@code OffsetTime} with the specified number of seconds added.
922 * <p>
923 * This adds the specified number of seconds to this time, returning a new time.
924 * The calculation wraps around midnight.
925 * <p>
926 * This instance is immutable and unaffected by this method call.
927 *
928 * @param seconds the seconds to add, may be negative
929 * @return an {@code OffsetTime} based on this time with the seconds added, not null
930 */
931 public OffsetTime plusSeconds(long seconds) {
932 return with(time.plusSeconds(seconds), offset);
933 }
934
935 /**
936 * Returns a copy of this {@code OffsetTime} with the specified number of nanoseconds added.
937 * <p>
938 * This adds the specified number of nanoseconds to this time, returning a new time.
939 * The calculation wraps around midnight.
940 * <p>
941 * This instance is immutable and unaffected by this method call.
942 *
943 * @param nanos the nanos to add, may be negative
944 * @return an {@code OffsetTime} based on this time with the nanoseconds added, not null
945 */
946 public OffsetTime plusNanos(long nanos) {
947 return with(time.plusNanos(nanos), offset);
948 }
949
950 //-----------------------------------------------------------------------
951 /**
952 * Returns a copy of this time with the specified amount subtracted.
953 * <p>
954 * This returns an {@code OffsetTime}, based on this one, with the specified amount subtracted.
955 * The amount is typically {@link Duration} but may be any other type implementing
956 * the {@link TemporalAmount} interface.
957 * <p>
958 * The calculation is delegated to the amount object by calling
959 * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free
960 * to implement the subtraction in any way it wishes, however it typically
961 * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation
962 * of the amount implementation to determine if it can be successfully subtracted.
963 * <p>
964 * This instance is immutable and unaffected by this method call.
965 *
966 * @param amountToSubtract the amount to subtract, not null
967 * @return an {@code OffsetTime} based on this time with the subtraction made, not null
968 * @throws DateTimeException if the subtraction cannot be made
969 * @throws ArithmeticException if numeric overflow occurs
970 */
971 @Override
972 public OffsetTime minus(TemporalAmount amountToSubtract) {
973 return (OffsetTime) amountToSubtract.subtractFrom(this);
974 }
975
976 /**
977 * Returns a copy of this time with the specified amount subtracted.
978 * <p>
979 * This returns an {@code OffsetTime}, based on this one, with the amount
980 * in terms of the unit subtracted. If it is not possible to subtract the amount,
981 * because the unit is not supported or for some other reason, an exception is thrown.
982 * <p>
983 * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.
984 * See that method for a full description of how addition, and thus subtraction, works.
985 * <p>
986 * This instance is immutable and unaffected by this method call.
987 *
988 * @param amountToSubtract the amount of the unit to subtract from the result, may be negative
989 * @param unit the unit of the amount to subtract, not null
990 * @return an {@code OffsetTime} based on this time with the specified amount subtracted, not null
991 * @throws DateTimeException if the subtraction cannot be made
992 * @throws UnsupportedTemporalTypeException if the unit is not supported
993 * @throws ArithmeticException if numeric overflow occurs
994 */
995 @Override
996 public OffsetTime minus(long amountToSubtract, TemporalUnit unit) {
997 return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
998 }
999
1000 //-----------------------------------------------------------------------
1001 /**
1002 * Returns a copy of this {@code OffsetTime} with the specified number of hours subtracted.
1003 * <p>
1004 * This subtracts the specified number of hours from this time, returning a new time.
1005 * The calculation wraps around midnight.
1006 * <p>
1007 * This instance is immutable and unaffected by this method call.
1008 *
1009 * @param hours the hours to subtract, may be negative
1010 * @return an {@code OffsetTime} based on this time with the hours subtracted, not null
1011 */
1012 public OffsetTime minusHours(long hours) {
1013 return with(time.minusHours(hours), offset);
1014 }
1015
1016 /**
1017 * Returns a copy of this {@code OffsetTime} with the specified number of minutes subtracted.
1018 * <p>
1019 * This subtracts the specified number of minutes from this time, returning a new time.
1020 * The calculation wraps around midnight.
1021 * <p>
1022 * This instance is immutable and unaffected by this method call.
1023 *
1024 * @param minutes the minutes to subtract, may be negative
1025 * @return an {@code OffsetTime} based on this time with the minutes subtracted, not null
1026 */
1027 public OffsetTime minusMinutes(long minutes) {
1028 return with(time.minusMinutes(minutes), offset);
1029 }
1030
1031 /**
1032 * Returns a copy of this {@code OffsetTime} with the specified number of seconds subtracted.
1033 * <p>
1034 * This subtracts the specified number of seconds from this time, returning a new time.
1035 * The calculation wraps around midnight.
1036 * <p>
1037 * This instance is immutable and unaffected by this method call.
1038 *
1039 * @param seconds the seconds to subtract, may be negative
1040 * @return an {@code OffsetTime} based on this time with the seconds subtracted, not null
1041 */
1042 public OffsetTime minusSeconds(long seconds) {
1043 return with(time.minusSeconds(seconds), offset);
1044 }
1045
1046 /**
1047 * Returns a copy of this {@code OffsetTime} with the specified number of nanoseconds subtracted.
1048 * <p>
1049 * This subtracts the specified number of nanoseconds from this time, returning a new time.
1050 * The calculation wraps around midnight.
1051 * <p>
1052 * This instance is immutable and unaffected by this method call.
1053 *
1054 * @param nanos the nanos to subtract, may be negative
1055 * @return an {@code OffsetTime} based on this time with the nanoseconds subtracted, not null
1056 */
1057 public OffsetTime minusNanos(long nanos) {
1058 return with(time.minusNanos(nanos), offset);
1059 }
1060
1061 //-----------------------------------------------------------------------
1062 /**
1063 * Queries this time using the specified query.
1064 * <p>
1065 * This queries this time using the specified query strategy object.
1066 * The {@code TemporalQuery} object defines the logic to be used to
1067 * obtain the result. Read the documentation of the query to understand
1068 * what the result of this method will be.
1069 * <p>
1070 * The result of this method is obtained by invoking the
1071 * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
1072 * specified query passing {@code this} as the argument.
1073 *
1074 * @param <R> the type of the result
1075 * @param query the query to invoke, not null
1076 * @return the query result, null may be returned (defined by the query)
1077 * @throws DateTimeException if unable to query (defined by the query)
1078 * @throws ArithmeticException if numeric overflow occurs (defined by the query)
1079 */
1080 @SuppressWarnings("unchecked")
1081 @Override
1082 public <R> R query(TemporalQuery<R> query) {
1083 if (query == TemporalQueries.offset() || query == TemporalQueries.zone()) {
1084 return (R) offset;
1085 } else if (query == TemporalQueries.zoneId() | query == TemporalQueries.chronology() || query == TemporalQueries.localDate()) {
1086 return null;
1087 } else if (query == TemporalQueries.localTime()) {
1088 return (R) time;
1089 } else if (query == TemporalQueries.precision()) {
1090 return (R) NANOS;
1091 }
1092 // inline TemporalAccessor.super.query(query) as an optimization
1093 // non-JDK classes are not permitted to make this optimization
1094 return query.queryFrom(this);
1095 }
1096
1097 /**
1098 * Adjusts the specified temporal object to have the same offset and time
1099 * as this object.
1100 * <p>
1101 * This returns a temporal object of the same observable type as the input
1102 * with the offset and time 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#NANO_OF_DAY} and
1106 * {@link ChronoField#OFFSET_SECONDS} 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 = thisOffsetTime.adjustInto(temporal);
1113 * temporal = temporal.with(thisOffsetTime);
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
1126 .with(NANO_OF_DAY, time.toNanoOfDay())
1127 .with(OFFSET_SECONDS, offset.getTotalSeconds());
1128 }
1129
1130 /**
1131 * Calculates the amount of time until another time in terms of the specified unit.
1132 * <p>
1133 * This calculates the amount of time between two {@code OffsetTime}
1134 * objects in terms of a single {@code TemporalUnit}.
1135 * The start and end points are {@code this} and the specified time.
1136 * The result will be negative if the end is before the start.
1137 * For example, the amount in hours between two times can be calculated
1138 * using {@code startTime.until(endTime, HOURS)}.
1139 * <p>
1140 * The {@code Temporal} passed to this method is converted to a
1141 * {@code OffsetTime} using {@link #from(TemporalAccessor)}.
1142 * If the offset differs between the two times, then the specified
1143 * end time is normalized to have the same offset as this time.
1144 * <p>
1145 * The calculation returns a whole number, representing the number of
1146 * complete units between the two times.
1147 * For example, the amount in hours between 11:30Z and 13:29Z will only
1148 * be one hour as it is one minute short of two hours.
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, MINUTES);
1156 * amount = MINUTES.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} and {@code HALF_DAYS} are supported.
1163 * 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 time, exclusive, which is converted to an {@code OffsetTime}, not null
1173 * @param unit the unit to measure the amount in, not null
1174 * @return the amount of time between this time and the end time
1175 * @throws DateTimeException if the amount cannot be calculated, or the end
1176 * temporal cannot be converted to an {@code OffsetTime}
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 OffsetTime end = OffsetTime.from(endExclusive);
1183 if (unit instanceof ChronoUnit chronoUnit) {
1184 long nanosUntil = end.toEpochNano() - toEpochNano(); // no overflow
1185 return switch (chronoUnit) {
1186 case NANOS -> nanosUntil;
1187 case MICROS -> nanosUntil / 1000;
1188 case MILLIS -> nanosUntil / 1000_000;
1189 case SECONDS -> nanosUntil / NANOS_PER_SECOND;
1190 case MINUTES -> nanosUntil / NANOS_PER_MINUTE;
1191 case HOURS -> nanosUntil / NANOS_PER_HOUR;
1192 case HALF_DAYS -> nanosUntil / (12 * NANOS_PER_HOUR);
1193 default -> throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
1194 };
1195 }
1196 return unit.between(this, end);
1197 }
1198
1199 /**
1200 * Formats this time using the specified formatter.
1201 * <p>
1202 * This time will be passed to the formatter to produce a string.
1203 *
1204 * @param formatter the formatter to use, not null
1205 * @return the formatted time string, not null
1206 * @throws DateTimeException if an error occurs during printing
1207 */
1208 public String format(DateTimeFormatter formatter) {
1209 Objects.requireNonNull(formatter, "formatter");
1210 return formatter.format(this);
1211 }
1212
1213 //-----------------------------------------------------------------------
1214 /**
1215 * Combines this time with a date to create an {@code OffsetDateTime}.
1216 * <p>
1217 * This returns an {@code OffsetDateTime} formed from this time and the specified date.
1218 * All possible combinations of date and time are valid.
1219 *
1220 * @param date the date to combine with, not null
1221 * @return the offset date-time formed from this time and the specified date, not null
1222 */
1223 public OffsetDateTime atDate(LocalDate date) {
1224 return OffsetDateTime.of(date, time, offset);
1225 }
1226
1227 //-----------------------------------------------------------------------
1228 /**
1229 * Converts this time to epoch nanos based on 1970-01-01Z.
1230 *
1231 * @return the epoch nanos value
1232 */
1233 private long toEpochNano() {
1234 long nod = time.toNanoOfDay();
1235 long offsetNanos = offset.getTotalSeconds() * NANOS_PER_SECOND;
1236 return nod - offsetNanos;
1237 }
1238
1239 /**
1240 * Converts this {@code OffsetTime} to the number of seconds since the epoch
1241 * of 1970-01-01T00:00:00Z.
1242 * <p>
1243 * This combines this offset time with the specified date to calculate the
1244 * epoch-second value, which is the number of elapsed seconds from
1245 * 1970-01-01T00:00:00Z.
1246 * Instants on the time-line after the epoch are positive, earlier
1247 * are negative.
1248 *
1249 * @param date the localdate, not null
1250 * @return the number of seconds since the epoch of 1970-01-01T00:00:00Z, may be negative
1251 * @since 9
1252 */
1253 public long toEpochSecond(LocalDate date) {
1254 Objects.requireNonNull(date, "date");
1255 long epochDay = date.toEpochDay();
1256 long secs = epochDay * 86400 + time.toSecondOfDay();
1257 secs -= offset.getTotalSeconds();
1258 return secs;
1259 }
1260
1261 //-----------------------------------------------------------------------
1262 /**
1263 * Compares this {@code OffsetTime} to another time.
1264 * <p>
1265 * The comparison is based first on the UTC equivalent instant, then on the local time.
1266 * It is "consistent with equals", as defined by {@link Comparable}.
1267 * <p>
1268 * For example, the following is the comparator order:
1269 * <ol>
1270 * <li>{@code 10:30+01:00}</li>
1271 * <li>{@code 11:00+01:00}</li>
1272 * <li>{@code 12:00+02:00}</li>
1273 * <li>{@code 11:30+01:00}</li>
1274 * <li>{@code 12:00+01:00}</li>
1275 * <li>{@code 12:30+01:00}</li>
1276 * </ol>
1277 * Values #2 and #3 represent the same instant on the time-line.
1278 * When two values represent the same instant, the local time is compared
1279 * to distinguish them. This step is needed to make the ordering
1280 * consistent with {@code equals()}.
1281 * <p>
1282 * To compare the underlying local time of two {@code TemporalAccessor} instances,
1283 * use {@link ChronoField#NANO_OF_DAY} as a comparator.
1284 *
1285 * @param other the other time to compare to, not null
1286 * @return the comparator value, that is the comparison of the UTC equivalent {@code other} instant,
1287 * if they are not equal, and if the UTC equivalent {@code other} instant is equal,
1288 * the comparison of this local time with {@code other} local time
1289 * @see #isBefore
1290 * @see #isAfter
1291 */
1292 @Override
1293 public int compareTo(OffsetTime other) {
1294 if (offset.equals(other.offset)) {
1295 return time.compareTo(other.time);
1296 }
1297 int compare = Long.compare(toEpochNano(), other.toEpochNano());
1298 if (compare == 0) {
1299 compare = time.compareTo(other.time);
1300 }
1301 return compare;
1302 }
1303
1304 //-----------------------------------------------------------------------
1305 /**
1306 * Checks if the instant of this {@code OffsetTime} is after that of the
1307 * specified time applying both times to a common date.
1308 * <p>
1309 * This method differs from the comparison in {@link #compareTo} in that it
1310 * only compares the instant of the time. This is equivalent to converting both
1311 * times to an instant using the same date and comparing the instants.
1312 *
1313 * @param other the other time to compare to, not null
1314 * @return true if this is after the instant of the specified time
1315 */
1316 public boolean isAfter(OffsetTime other) {
1317 return toEpochNano() > other.toEpochNano();
1318 }
1319
1320 /**
1321 * Checks if the instant of this {@code OffsetTime} is before that of the
1322 * specified time applying both times to a common date.
1323 * <p>
1324 * This method differs from the comparison in {@link #compareTo} in that it
1325 * only compares the instant of the time. This is equivalent to converting both
1326 * times to an instant using the same date and comparing the instants.
1327 *
1328 * @param other the other time to compare to, not null
1329 * @return true if this is before the instant of the specified time
1330 */
1331 public boolean isBefore(OffsetTime other) {
1332 return toEpochNano() < other.toEpochNano();
1333 }
1334
1335 /**
1336 * Checks if the instant of this {@code OffsetTime} is equal to that of the
1337 * specified time applying both times to a common date.
1338 * <p>
1339 * This method differs from the comparison in {@link #compareTo} and {@link #equals}
1340 * in that it only compares the instant of the time. This is equivalent to converting both
1341 * times to an instant using the same date and comparing the instants.
1342 *
1343 * @param other the other time to compare to, not null
1344 * @return true if this is equal to the instant of the specified time
1345 */
1346 public boolean isEqual(OffsetTime other) {
1347 return toEpochNano() == other.toEpochNano();
1348 }
1349
1350 //-----------------------------------------------------------------------
1351 /**
1352 * Checks if this time is equal to another time.
1353 * <p>
1354 * The comparison is based on the local-time and the offset.
1355 * To compare for the same instant on the time-line, use {@link #isEqual(OffsetTime)}.
1356 * <p>
1357 * Only objects of type {@code OffsetTime} are compared, other types return false.
1358 * To compare the underlying local time of two {@code TemporalAccessor} instances,
1359 * use {@link ChronoField#NANO_OF_DAY} as a comparator.
1360 *
1361 * @param obj the object to check, null returns false
1362 * @return true if this is equal to the other time
1363 */
1364 @Override
1365 public boolean equals(Object obj) {
1366 if (this == obj) {
1367 return true;
1368 }
1369 return (obj instanceof OffsetTime other)
1370 && time.equals(other.time)
1371 && offset.equals(other.offset);
1372 }
1373
1374 /**
1375 * A hash code for this time.
1376 *
1377 * @return a suitable hash code
1378 */
1379 @Override
1380 public int hashCode() {
1381 return time.hashCode() ^ offset.hashCode();
1382 }
1383
1384 //-----------------------------------------------------------------------
1385 /**
1386 * Outputs this time as a {@code String}, such as {@code 10:15:30+01:00}.
1387 * <p>
1388 * The output will be one of the following ISO-8601 formats:
1389 * <ul>
1390 * <li>{@code HH:mmXXXXX}</li>
1391 * <li>{@code HH:mm:ssXXXXX}</li>
1392 * <li>{@code HH:mm:ss.SSSXXXXX}</li>
1393 * <li>{@code HH:mm:ss.SSSSSSXXXXX}</li>
1394 * <li>{@code HH:mm:ss.SSSSSSSSSXXXXX}</li>
1395 * </ul>
1396 * The format used will be the shortest that outputs the full value of
1397 * the time where the omitted parts are implied to be zero.
1398 *
1399 * @return a string representation of this time, not null
1400 */
1401 @Override
1402 public String toString() {
1403 var offsetStr = offset.toString();
1404 var buf = new StringBuilder(18 + offsetStr.length());
1405 DateTimeHelper.formatTo(buf, time);
1406 return buf.append(offsetStr).toString();
1407 }
1408
1409 //-----------------------------------------------------------------------
1410 /**
1411 * Writes the object using a
1412 * <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>.
1413 * @serialData
1414 * <pre>
1415 * out.writeByte(9); // identifies an OffsetTime
1416 * // the <a href="{@docRoot}/serialized-form.html#java.time.LocalTime">time</a> excluding the one byte header
1417 * // the <a href="{@docRoot}/serialized-form.html#java.time.ZoneOffset">offset</a> excluding the one byte header
1418 * </pre>
1419 *
1420 * @return the instance of {@code Ser}, not null
1421 */
1422 @java.io.Serial
1423 private Object writeReplace() {
1424 return new Ser(Ser.OFFSET_TIME_TYPE, this);
1425 }
1426
1427 /**
1428 * Defend against malicious streams.
1429 *
1430 * @param s the stream to read
1431 * @throws InvalidObjectException always
1432 */
1433 @java.io.Serial
1434 private void readObject(ObjectInputStream s) throws InvalidObjectException {
1435 throw new InvalidObjectException("Deserialization via serialization delegate");
1436 }
1437
1438 void writeExternal(ObjectOutput out) throws IOException {
1439 time.writeExternal(out);
1440 offset.writeExternal(out);
1441 }
1442
1443 static OffsetTime readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
1444 LocalTime time = LocalTime.readExternal(in);
1445 ZoneOffset offset = ZoneOffset.readExternal(in);
1446 return OffsetTime.of(time, offset);
1447 }
1448
1449 }