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