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