001/*
002 * Copyright (c) 2007-2013, Stephen Colebourne & Michael Nascimento Santos
003 *
004 * All rights reserved.
005 *
006 * Redistribution and use in source and binary forms, with or without
007 * modification, are permitted provided that the following conditions are met:
008 *
009 *  * Redistributions of source code must retain the above copyright notice,
010 *    this list of conditions and the following disclaimer.
011 *
012 *  * Redistributions in binary form must reproduce the above copyright notice,
013 *    this list of conditions and the following disclaimer in the documentation
014 *    and/or other materials provided with the distribution.
015 *
016 *  * Neither the name of JSR-310 nor the names of its contributors
017 *    may be used to endorse or promote products derived from this software
018 *    without specific prior written permission.
019 *
020 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
021 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
022 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
023 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
024 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
025 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
026 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
027 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
028 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
029 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
030 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
031 */
032package org.threeten.bp;
033
034import static org.threeten.bp.temporal.ChronoField.HOUR_OF_DAY;
035import static org.threeten.bp.temporal.ChronoField.MICRO_OF_DAY;
036import static org.threeten.bp.temporal.ChronoField.MINUTE_OF_HOUR;
037import static org.threeten.bp.temporal.ChronoField.NANO_OF_DAY;
038import static org.threeten.bp.temporal.ChronoField.NANO_OF_SECOND;
039import static org.threeten.bp.temporal.ChronoField.SECOND_OF_DAY;
040import static org.threeten.bp.temporal.ChronoField.SECOND_OF_MINUTE;
041import static org.threeten.bp.temporal.ChronoUnit.NANOS;
042
043import java.io.DataInput;
044import java.io.DataOutput;
045import java.io.IOException;
046import java.io.InvalidObjectException;
047import java.io.ObjectStreamException;
048import java.io.Serializable;
049import java.util.Objects;
050
051import org.threeten.bp.format.DateTimeBuilder;
052import org.threeten.bp.format.DateTimeFormatter;
053import org.threeten.bp.format.DateTimeFormatters;
054import org.threeten.bp.format.DateTimeParseException;
055import org.threeten.bp.jdk8.DefaultInterfaceTemporalAccessor;
056import org.threeten.bp.temporal.ChronoField;
057import org.threeten.bp.temporal.ChronoLocalDateTime;
058import org.threeten.bp.temporal.ChronoUnit;
059import org.threeten.bp.temporal.ChronoZonedDateTime;
060import org.threeten.bp.temporal.Temporal;
061import org.threeten.bp.temporal.TemporalAccessor;
062import org.threeten.bp.temporal.TemporalAdder;
063import org.threeten.bp.temporal.TemporalAdjuster;
064import org.threeten.bp.temporal.TemporalField;
065import org.threeten.bp.temporal.TemporalQueries;
066import org.threeten.bp.temporal.TemporalQuery;
067import org.threeten.bp.temporal.TemporalSubtractor;
068import org.threeten.bp.temporal.TemporalUnit;
069import org.threeten.bp.temporal.ValueRange;
070
071/**
072 * A time without time-zone in the ISO-8601 calendar system,
073 * such as {@code 10:15:30}.
074 * <p>
075 * {@code LocalTime} is an immutable date-time object that represents a time,
076 * often viewed as hour-minute-second.
077 * Time is represented to nanosecond precision.
078 * For example, the value "13:45.30.123456789" can be stored in a {@code LocalTime}.
079 * <p>
080 * It does not store or represent a date or time-zone.
081 * Instead, it is a description of the local time as seen on a wall clock.
082 * It cannot represent an instant on the time-line without additional information
083 * such as an offset or time-zone.
084 * <p>
085 * The ISO-8601 calendar system is the modern civil calendar system used today
086 * in most of the world. This API assumes that all calendar systems use the same
087 * representation, this class, for time-of-day.
088 *
089 * <h3>Specification for implementors</h3>
090 * This class is immutable and thread-safe.
091 */
092public final class LocalTime
093        extends DefaultInterfaceTemporalAccessor
094        implements Temporal, TemporalAdjuster, Comparable<LocalTime>, Serializable {
095
096    /**
097     * The minimum supported {@code LocalTime}, '00:00'.
098     * This is the time of midnight at the start of the day.
099     */
100    public static final LocalTime MIN;
101    /**
102     * The maximum supported {@code LocalTime}, '23:59:59.999999999'.
103     * This is the time just before midnight at the end of the day.
104     */
105    public static final LocalTime MAX;
106    /**
107     * The time of midnight at the start of the day, '00:00'.
108     */
109    public static final LocalTime MIDNIGHT;
110    /**
111     * The time of noon in the middle of the day, '12:00'.
112     */
113    public static final LocalTime NOON;
114    /**
115     * Constants for the local time of each hour.
116     */
117    private static final LocalTime[] HOURS = new LocalTime[24];
118    static {
119        for (int i = 0; i < HOURS.length; i++) {
120            HOURS[i] = new LocalTime(i, 0, 0, 0);
121        }
122        MIDNIGHT = HOURS[0];
123        NOON = HOURS[12];
124        MIN = HOURS[0];
125        MAX = new LocalTime(23, 59, 59, 999_999_999);
126    }
127
128    /**
129     * Hours per day.
130     */
131    static final int HOURS_PER_DAY = 24;
132    /**
133     * Minutes per hour.
134     */
135    static final int MINUTES_PER_HOUR = 60;
136    /**
137     * Minutes per day.
138     */
139    static final int MINUTES_PER_DAY = MINUTES_PER_HOUR * HOURS_PER_DAY;
140    /**
141     * Seconds per minute.
142     */
143    static final int SECONDS_PER_MINUTE = 60;
144    /**
145     * Seconds per hour.
146     */
147    static final int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR;
148    /**
149     * Seconds per day.
150     */
151    static final int SECONDS_PER_DAY = SECONDS_PER_HOUR * HOURS_PER_DAY;
152    /**
153     * Milliseconds per day.
154     */
155    static final long MILLIS_PER_DAY = SECONDS_PER_DAY * 1000L;
156    /**
157     * Microseconds per day.
158     */
159    static final long MICROS_PER_DAY = SECONDS_PER_DAY * 1000_000L;
160    /**
161     * Nanos per second.
162     */
163    static final long NANOS_PER_SECOND = 1000_000_000L;
164    /**
165     * Nanos per minute.
166     */
167    static final long NANOS_PER_MINUTE = NANOS_PER_SECOND * SECONDS_PER_MINUTE;
168    /**
169     * Nanos per hour.
170     */
171    static final long NANOS_PER_HOUR = NANOS_PER_MINUTE * MINUTES_PER_HOUR;
172    /**
173     * Nanos per day.
174     */
175    static final long NANOS_PER_DAY = NANOS_PER_HOUR * HOURS_PER_DAY;
176
177    /**
178     * Serialization version.
179     */
180    private static final long serialVersionUID = 6414437269572265201L;
181
182    /**
183     * The hour.
184     */
185    private final byte hour;
186    /**
187     * The minute.
188     */
189    private final byte minute;
190    /**
191     * The second.
192     */
193    private final byte second;
194    /**
195     * The nanosecond.
196     */
197    private final int nano;
198
199    //-----------------------------------------------------------------------
200    /**
201     * Obtains the current time from the system clock in the default time-zone.
202     * <p>
203     * This will query the {@link Clock#systemDefaultZone() system clock} in the default
204     * time-zone to obtain the current time.
205     * <p>
206     * Using this method will prevent the ability to use an alternate clock for testing
207     * because the clock is hard-coded.
208     *
209     * @return the current time using the system clock and default time-zone, not null
210     */
211    public static LocalTime now() {
212        return now(Clock.systemDefaultZone());
213    }
214
215    /**
216     * Obtains the current time from the system clock in the specified time-zone.
217     * <p>
218     * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current time.
219     * Specifying the time-zone avoids dependence on the default time-zone.
220     * <p>
221     * Using this method will prevent the ability to use an alternate clock for testing
222     * because the clock is hard-coded.
223     *
224     * @param zone  the zone ID to use, not null
225     * @return the current time using the system clock, not null
226     */
227    public static LocalTime now(ZoneId zone) {
228        return now(Clock.system(zone));
229    }
230
231    /**
232     * Obtains the current time from the specified clock.
233     * <p>
234     * This will query the specified clock to obtain the current time.
235     * Using this method allows the use of an alternate clock for testing.
236     * The alternate clock may be introduced using {@link Clock dependency injection}.
237     *
238     * @param clock  the clock to use, not null
239     * @return the current time, not null
240     */
241    public static LocalTime now(Clock clock) {
242        Objects.requireNonNull(clock, "clock");
243        // inline OffsetTime factory to avoid creating object and InstantProvider checks
244        final Instant now = clock.instant();  // called once
245        ZoneOffset offset = clock.getZone().getRules().getOffset(now);
246        long secsOfDay = now.getEpochSecond() % SECONDS_PER_DAY;
247        secsOfDay = (secsOfDay + offset.getTotalSeconds()) % SECONDS_PER_DAY;
248        if (secsOfDay < 0) {
249            secsOfDay += SECONDS_PER_DAY;
250        }
251        return LocalTime.ofSecondOfDay(secsOfDay, now.getNano());
252    }
253
254    //------------------------get-----------------------------------------------
255    /**
256     * Obtains an instance of {@code LocalTime} from an hour and minute.
257     * <p>
258     * The second and nanosecond fields will be set to zero by this factory method.
259     * <p>
260     * This factory may return a cached value, but applications must not rely on this.
261     *
262     * @param hour  the hour-of-day to represent, from 0 to 23
263     * @param minute  the minute-of-hour to represent, from 0 to 59
264     * @return the local time, not null
265     * @throws DateTimeException if the value of any field is out of range
266     */
267    public static LocalTime of(int hour, int minute) {
268        HOUR_OF_DAY.checkValidValue(hour);
269        if (minute == 0) {
270            return HOURS[hour];  // for performance
271        }
272        MINUTE_OF_HOUR.checkValidValue(minute);
273        return new LocalTime(hour, minute, 0, 0);
274    }
275
276    /**
277     * Obtains an instance of {@code LocalTime} from an hour, minute and second.
278     * <p>
279     * The nanosecond field will be set to zero by this factory method.
280     * <p>
281     * This factory may return a cached value, but applications must not rely on this.
282     *
283     * @param hour  the hour-of-day to represent, from 0 to 23
284     * @param minute  the minute-of-hour to represent, from 0 to 59
285     * @param second  the second-of-minute to represent, from 0 to 59
286     * @return the local time, not null
287     * @throws DateTimeException if the value of any field is out of range
288     */
289    public static LocalTime of(int hour, int minute, int second) {
290        HOUR_OF_DAY.checkValidValue(hour);
291        if ((minute | second) == 0) {
292            return HOURS[hour];  // for performance
293        }
294        MINUTE_OF_HOUR.checkValidValue(minute);
295        SECOND_OF_MINUTE.checkValidValue(second);
296        return new LocalTime(hour, minute, second, 0);
297    }
298
299    /**
300     * Obtains an instance of {@code LocalTime} from an hour, minute, second and nanosecond.
301     * <p>
302     * This factory may return a cached value, but applications must not rely on this.
303     *
304     * @param hour  the hour-of-day to represent, from 0 to 23
305     * @param minute  the minute-of-hour to represent, from 0 to 59
306     * @param second  the second-of-minute to represent, from 0 to 59
307     * @param nanoOfSecond  the nano-of-second to represent, from 0 to 999,999,999
308     * @return the local time, not null
309     * @throws DateTimeException if the value of any field is out of range
310     */
311    public static LocalTime of(int hour, int minute, int second, int nanoOfSecond) {
312        HOUR_OF_DAY.checkValidValue(hour);
313        MINUTE_OF_HOUR.checkValidValue(minute);
314        SECOND_OF_MINUTE.checkValidValue(second);
315        NANO_OF_SECOND.checkValidValue(nanoOfSecond);
316        return create(hour, minute, second, nanoOfSecond);
317    }
318
319    //-----------------------------------------------------------------------
320    /**
321     * Obtains an instance of {@code LocalTime} from a second-of-day value.
322     * <p>
323     * This factory may return a cached value, but applications must not rely on this.
324     *
325     * @param secondOfDay  the second-of-day, from {@code 0} to {@code 24 * 60 * 60 - 1}
326     * @return the local time, not null
327     * @throws DateTimeException if the second-of-day value is invalid
328     */
329    public static LocalTime ofSecondOfDay(long secondOfDay) {
330        SECOND_OF_DAY.checkValidValue(secondOfDay);
331        int hours = (int) (secondOfDay / SECONDS_PER_HOUR);
332        secondOfDay -= hours * SECONDS_PER_HOUR;
333        int minutes = (int) (secondOfDay / SECONDS_PER_MINUTE);
334        secondOfDay -= minutes * SECONDS_PER_MINUTE;
335        return create(hours, minutes, (int) secondOfDay, 0);
336    }
337
338    /**
339     * Obtains an instance of {@code LocalTime} from a second-of-day value, with
340     * associated nanos of second.
341     * <p>
342     * This factory may return a cached value, but applications must not rely on this.
343     *
344     * @param secondOfDay  the second-of-day, from {@code 0} to {@code 24 * 60 * 60 - 1}
345     * @param nanoOfSecond  the nano-of-second, from 0 to 999,999,999
346     * @return the local time, not null
347     * @throws DateTimeException if the either input value is invalid
348     */
349    public static LocalTime ofSecondOfDay(long secondOfDay, int nanoOfSecond) {
350        SECOND_OF_DAY.checkValidValue(secondOfDay);
351        NANO_OF_SECOND.checkValidValue(nanoOfSecond);
352        int hours = (int) (secondOfDay / SECONDS_PER_HOUR);
353        secondOfDay -= hours * SECONDS_PER_HOUR;
354        int minutes = (int) (secondOfDay / SECONDS_PER_MINUTE);
355        secondOfDay -= minutes * SECONDS_PER_MINUTE;
356        return create(hours, minutes, (int) secondOfDay, nanoOfSecond);
357    }
358
359    /**
360     * Obtains an instance of {@code LocalTime} from a nanos-of-day value.
361     * <p>
362     * This factory may return a cached value, but applications must not rely on this.
363     *
364     * @param nanoOfDay  the nano of day, from {@code 0} to {@code 24 * 60 * 60 * 1,000,000,000 - 1}
365     * @return the local time, not null
366     * @throws DateTimeException if the nanos of day value is invalid
367     */
368    public static LocalTime ofNanoOfDay(long nanoOfDay) {
369        NANO_OF_DAY.checkValidValue(nanoOfDay);
370        int hours = (int) (nanoOfDay / NANOS_PER_HOUR);
371        nanoOfDay -= hours * NANOS_PER_HOUR;
372        int minutes = (int) (nanoOfDay / NANOS_PER_MINUTE);
373        nanoOfDay -= minutes * NANOS_PER_MINUTE;
374        int seconds = (int) (nanoOfDay / NANOS_PER_SECOND);
375        nanoOfDay -= seconds * NANOS_PER_SECOND;
376        return create(hours, minutes, seconds, (int) nanoOfDay);
377    }
378
379    //-----------------------------------------------------------------------
380    /**
381     * Obtains an instance of {@code LocalTime} from a temporal object.
382     * <p>
383     * A {@code TemporalAccessor} represents some form of date and time information.
384     * This factory converts the arbitrary temporal object to an instance of {@code LocalTime}.
385     * <p>
386     * The conversion extracts the {@link ChronoField#NANO_OF_DAY NANO_OF_DAY} field.
387     * <p>
388     * This method matches the signature of the functional interface {@link TemporalQuery}
389     * allowing it to be used in queries via method reference, {@code LocalTime::from}.
390     *
391     * @param temporal  the temporal object to convert, not null
392     * @return the local time, not null
393     * @throws DateTimeException if unable to convert to a {@code LocalTime}
394     */
395    public static LocalTime from(TemporalAccessor temporal) {
396        if (temporal instanceof LocalTime) {
397            return (LocalTime) temporal;
398        } else if (temporal instanceof ChronoLocalDateTime) {
399            return ((ChronoLocalDateTime<?>) temporal).getTime();
400        } else if (temporal instanceof ChronoZonedDateTime) {
401            return ((ChronoZonedDateTime<?>) temporal).getTime();
402        }
403        // handle builder as a special case
404        if (temporal instanceof DateTimeBuilder) {
405            DateTimeBuilder builder = (DateTimeBuilder) temporal;
406            LocalTime time = builder.extract(LocalTime.class);
407            if (time != null) {
408                return time;
409            }
410        }
411        try {
412            return ofNanoOfDay(temporal.getLong(NANO_OF_DAY));
413        } catch (DateTimeException ex) {
414            throw new DateTimeException("Unable to obtain LocalTime from TemporalAccessor: " + temporal.getClass(), ex);
415        }
416    }
417
418    //-----------------------------------------------------------------------
419    /**
420     * Obtains an instance of {@code LocalTime} from a text string such as {@code 10:15}.
421     * <p>
422     * The string must represent a valid time and is parsed using
423     * {@link org.threeten.bp.format.DateTimeFormatters#isoLocalTime()}.
424     *
425     * @param text the text to parse such as "10:15:30", not null
426     * @return the parsed local time, not null
427     * @throws DateTimeParseException if the text cannot be parsed
428     */
429    public static LocalTime parse(CharSequence text) {
430        return parse(text, DateTimeFormatters.isoLocalTime());
431    }
432
433    /**
434     * Obtains an instance of {@code LocalTime} from a text string using a specific formatter.
435     * <p>
436     * The text is parsed using the formatter, returning a time.
437     *
438     * @param text  the text to parse, not null
439     * @param formatter  the formatter to use, not null
440     * @return the parsed local time, not null
441     * @throws DateTimeParseException if the text cannot be parsed
442     */
443    public static LocalTime parse(CharSequence text, DateTimeFormatter formatter) {
444        Objects.requireNonNull(formatter, "formatter");
445        return formatter.parse(text, LocalTime.class);
446    }
447
448    //-----------------------------------------------------------------------
449    /**
450     * Creates a local time from the hour, minute, second and nanosecond fields.
451     * <p>
452     * This factory may return a cached value, but applications must not rely on this.
453     *
454     * @param hour  the hour-of-day to represent, validated from 0 to 23
455     * @param minute  the minute-of-hour to represent, validated from 0 to 59
456     * @param second  the second-of-minute to represent, validated from 0 to 59
457     * @param nanoOfSecond  the nano-of-second to represent, validated from 0 to 999,999,999
458     * @return the local time, not null
459     */
460    private static LocalTime create(int hour, int minute, int second, int nanoOfSecond) {
461        if ((minute | second | nanoOfSecond) == 0) {
462            return HOURS[hour];
463        }
464        return new LocalTime(hour, minute, second, nanoOfSecond);
465    }
466
467    /**
468     * Constructor, previously validated.
469     *
470     * @param hour  the hour-of-day to represent, validated from 0 to 23
471     * @param minute  the minute-of-hour to represent, validated from 0 to 59
472     * @param second  the second-of-minute to represent, validated from 0 to 59
473     * @param nanoOfSecond  the nano-of-second to represent, validated from 0 to 999,999,999
474     */
475    private LocalTime(int hour, int minute, int second, int nanoOfSecond) {
476        this.hour = (byte) hour;
477        this.minute = (byte) minute;
478        this.second = (byte) second;
479        this.nano = nanoOfSecond;
480    }
481
482    //-----------------------------------------------------------------------
483    /**
484     * Checks if the specified field is supported.
485     * <p>
486     * This checks if this time can be queried for the specified field.
487     * If false, then calling the {@link #range(TemporalField) range} and
488     * {@link #get(TemporalField) get} methods will throw an exception.
489     * <p>
490     * If the field is a {@link ChronoField} then the query is implemented here.
491     * The supported fields are:
492     * <ul>
493     * <li>{@code NANO_OF_SECOND}
494     * <li>{@code NANO_OF_DAY}
495     * <li>{@code MICRO_OF_SECOND}
496     * <li>{@code MICRO_OF_DAY}
497     * <li>{@code MILLI_OF_SECOND}
498     * <li>{@code MILLI_OF_DAY}
499     * <li>{@code SECOND_OF_MINUTE}
500     * <li>{@code SECOND_OF_DAY}
501     * <li>{@code MINUTE_OF_HOUR}
502     * <li>{@code MINUTE_OF_DAY}
503     * <li>{@code HOUR_OF_AMPM}
504     * <li>{@code CLOCK_HOUR_OF_AMPM}
505     * <li>{@code HOUR_OF_DAY}
506     * <li>{@code CLOCK_HOUR_OF_DAY}
507     * <li>{@code AMPM_OF_DAY}
508     * </ul>
509     * All other {@code ChronoField} instances will return false.
510     * <p>
511     * If the field is not a {@code ChronoField}, then the result of this method
512     * is obtained by invoking {@code TemporalField.doIsSupported(TemporalAccessor)}
513     * passing {@code this} as the argument.
514     * Whether the field is supported is determined by the field.
515     *
516     * @param field  the field to check, null returns false
517     * @return true if the field is supported on this time, false if not
518     */
519    @Override
520    public boolean isSupported(TemporalField field) {
521        if (field instanceof ChronoField) {
522            return ((ChronoField) field).isTimeField();
523        }
524        return field != null && field.doIsSupported(this);
525    }
526
527    /**
528     * Gets the range of valid values for the specified field.
529     * <p>
530     * The range object expresses the minimum and maximum valid values for a field.
531     * This time is used to enhance the accuracy of the returned range.
532     * If it is not possible to return the range, because the field is not supported
533     * or for some other reason, an exception is thrown.
534     * <p>
535     * If the field is a {@link ChronoField} then the query is implemented here.
536     * The {@link #isSupported(TemporalField) supported fields} will return
537     * appropriate range instances.
538     * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
539     * <p>
540     * If the field is not a {@code ChronoField}, then the result of this method
541     * is obtained by invoking {@code TemporalField.doRange(TemporalAccessor)}
542     * passing {@code this} as the argument.
543     * Whether the range can be obtained is determined by the field.
544     *
545     * @param field  the field to query the range for, not null
546     * @return the range of valid values for the field, not null
547     * @throws DateTimeException if the range for the field cannot be obtained
548     */
549    @Override  // override for Javadoc
550    public ValueRange range(TemporalField field) {
551        return super.range(field);
552    }
553
554    /**
555     * Gets the value of the specified field from this time as an {@code int}.
556     * <p>
557     * This queries this time for the value for the specified field.
558     * The returned value will always be within the valid range of values for the field.
559     * If it is not possible to return the value, because the field is not supported
560     * or for some other reason, an exception is thrown.
561     * <p>
562     * If the field is a {@link ChronoField} then the query is implemented here.
563     * The {@link #isSupported(TemporalField) supported fields} will return valid
564     * values based on this time, except {@code NANO_OF_DAY} and {@code MICRO_OF_DAY}
565     * which are too large to fit in an {@code int} and throw a {@code DateTimeException}.
566     * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
567     * <p>
568     * If the field is not a {@code ChronoField}, then the result of this method
569     * is obtained by invoking {@code TemporalField.doGet(TemporalAccessor)}
570     * passing {@code this} as the argument. Whether the value can be obtained,
571     * and what the value represents, is determined by the field.
572     *
573     * @param field  the field to get, not null
574     * @return the value for the field
575     * @throws DateTimeException if a value for the field cannot be obtained
576     * @throws ArithmeticException if numeric overflow occurs
577     */
578    @Override  // override for Javadoc and performance
579    public int get(TemporalField field) {
580        if (field instanceof ChronoField) {
581            return get0(field);
582        }
583        return super.get(field);
584    }
585
586    /**
587     * Gets the value of the specified field from this time as a {@code long}.
588     * <p>
589     * This queries this time for the value for the specified field.
590     * If it is not possible to return the value, because the field is not supported
591     * or for some other reason, an exception is thrown.
592     * <p>
593     * If the field is a {@link ChronoField} then the query is implemented here.
594     * The {@link #isSupported(TemporalField) supported fields} will return valid
595     * values based on this time.
596     * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
597     * <p>
598     * If the field is not a {@code ChronoField}, then the result of this method
599     * is obtained by invoking {@code TemporalField.doGet(TemporalAccessor)}
600     * passing {@code this} as the argument. Whether the value can be obtained,
601     * and what the value represents, is determined by the field.
602     *
603     * @param field  the field to get, not null
604     * @return the value for the field
605     * @throws DateTimeException if a value for the field cannot be obtained
606     * @throws ArithmeticException if numeric overflow occurs
607     */
608    @Override
609    public long getLong(TemporalField field) {
610        if (field instanceof ChronoField) {
611            if (field == NANO_OF_DAY) {
612                return toNanoOfDay();
613            }
614            if (field == MICRO_OF_DAY) {
615                return toNanoOfDay() / 1000;
616            }
617            return get0(field);
618        }
619        return field.doGet(this);
620    }
621
622    private int get0(TemporalField field) {
623        switch ((ChronoField) field) {
624            case NANO_OF_SECOND: return nano;
625            case NANO_OF_DAY: throw new DateTimeException("Field too large for an int: " + field);
626            case MICRO_OF_SECOND: return nano / 1000;
627            case MICRO_OF_DAY: throw new DateTimeException("Field too large for an int: " + field);
628            case MILLI_OF_SECOND: return nano / 1000_000;
629            case MILLI_OF_DAY: return (int) (toNanoOfDay() / 1000_000);
630            case SECOND_OF_MINUTE: return second;
631            case SECOND_OF_DAY: return toSecondOfDay();
632            case MINUTE_OF_HOUR: return minute;
633            case MINUTE_OF_DAY: return hour * 60 + minute;
634            case HOUR_OF_AMPM: return hour % 12;
635            case CLOCK_HOUR_OF_AMPM: int ham = hour % 12; return (ham % 12 == 0 ? 12 : ham);
636            case HOUR_OF_DAY: return hour;
637            case CLOCK_HOUR_OF_DAY: return (hour == 0 ? 24 : hour);
638            case AMPM_OF_DAY: return hour / 12;
639        }
640        throw new DateTimeException("Unsupported field: " + field.getName());
641    }
642
643    //-----------------------------------------------------------------------
644    /**
645     * Gets the hour-of-day field.
646     *
647     * @return the hour-of-day, from 0 to 23
648     */
649    public int getHour() {
650        return hour;
651    }
652
653    /**
654     * Gets the minute-of-hour field.
655     *
656     * @return the minute-of-hour, from 0 to 59
657     */
658    public int getMinute() {
659        return minute;
660    }
661
662    /**
663     * Gets the second-of-minute field.
664     *
665     * @return the second-of-minute, from 0 to 59
666     */
667    public int getSecond() {
668        return second;
669    }
670
671    /**
672     * Gets the nano-of-second field.
673     *
674     * @return the nano-of-second, from 0 to 999,999,999
675     */
676    public int getNano() {
677        return nano;
678    }
679
680    //-----------------------------------------------------------------------
681    /**
682     * Returns an adjusted copy of this time.
683     * <p>
684     * This returns a new {@code LocalTime}, based on this one, with the time adjusted.
685     * The adjustment takes place using the specified adjuster strategy object.
686     * Read the documentation of the adjuster to understand what adjustment will be made.
687     * <p>
688     * A simple adjuster might simply set the one of the fields, such as the hour field.
689     * A more complex adjuster might set the time to the last hour of the day.
690     * <p>
691     * The result of this method is obtained by invoking the
692     * {@link TemporalAdjuster#adjustInto(Temporal)} method on the
693     * specified adjuster passing {@code this} as the argument.
694     * <p>
695     * This instance is immutable and unaffected by this method call.
696     *
697     * @param adjuster the adjuster to use, not null
698     * @return a {@code LocalTime} based on {@code this} with the adjustment made, not null
699     * @throws DateTimeException if the adjustment cannot be made
700     * @throws ArithmeticException if numeric overflow occurs
701     */
702    @Override
703    public LocalTime with(TemporalAdjuster adjuster) {
704        // optimizations
705        if (adjuster instanceof LocalTime) {
706            return (LocalTime) adjuster;
707        }
708        return (LocalTime) adjuster.adjustInto(this);
709    }
710
711    /**
712     * Returns a copy of this time with the specified field set to a new value.
713     * <p>
714     * This returns a new {@code LocalTime}, based on this one, with the value
715     * for the specified field changed.
716     * This can be used to change any supported field, such as the hour, minute or second.
717     * If it is not possible to set the value, because the field is not supported or for
718     * some other reason, an exception is thrown.
719     * <p>
720     * If the field is a {@link ChronoField} then the adjustment is implemented here.
721     * The supported fields behave as follows:
722     * <ul>
723     * <li>{@code NANO_OF_SECOND} -
724     *  Returns a {@code LocalTime} with the specified nano-of-second.
725     *  The hour, minute and second will be unchanged.
726     * <li>{@code NANO_OF_DAY} -
727     *  Returns a {@code LocalTime} with the specified nano-of-day.
728     *  This completely replaces the time and is equivalent to {@link #ofNanoOfDay(long)}.
729     * <li>{@code MICRO_OF_SECOND} -
730     *  Returns a {@code LocalTime} with the nano-of-second replaced by the specified
731     *  micro-of-second multiplied by 1,000.
732     *  The hour, minute and second will be unchanged.
733     * <li>{@code MICRO_OF_DAY} -
734     *  Returns a {@code LocalTime} with the specified micro-of-day.
735     *  This completely replaces the time and is equivalent to using {@link #ofNanoOfDay(long)}
736     *  with the micro-of-day multiplied by 1,000.
737     * <li>{@code MILLI_OF_SECOND} -
738     *  Returns a {@code LocalTime} with the nano-of-second replaced by the specified
739     *  milli-of-second multiplied by 1,000,000.
740     *  The hour, minute and second will be unchanged.
741     * <li>{@code MILLI_OF_DAY} -
742     *  Returns a {@code LocalTime} with the specified milli-of-day.
743     *  This completely replaces the time and is equivalent to using {@link #ofNanoOfDay(long)}
744     *  with the milli-of-day multiplied by 1,000,000.
745     * <li>{@code SECOND_OF_MINUTE} -
746     *  Returns a {@code LocalTime} with the specified second-of-minute.
747     *  The hour, minute and nano-of-second will be unchanged.
748     * <li>{@code SECOND_OF_DAY} -
749     *  Returns a {@code LocalTime} with the specified second-of-day.
750     *  The nano-of-second will be unchanged.
751     * <li>{@code MINUTE_OF_HOUR} -
752     *  Returns a {@code LocalTime} with the specified minute-of-hour.
753     *  The hour, second-of-minute and nano-of-second will be unchanged.
754     * <li>{@code MINUTE_OF_DAY} -
755     *  Returns a {@code LocalTime} with the specified minute-of-day.
756     *  The second-of-minute and nano-of-second will be unchanged.
757     * <li>{@code HOUR_OF_AMPM} -
758     *  Returns a {@code LocalTime} with the specified hour-of-am-pm.
759     *  The AM/PM, minute-of-hour, second-of-minute and nano-of-second will be unchanged.
760     * <li>{@code CLOCK_HOUR_OF_AMPM} -
761     *  Returns a {@code LocalTime} with the specified clock-hour-of-am-pm.
762     *  The AM/PM, minute-of-hour, second-of-minute and nano-of-second will be unchanged.
763     * <li>{@code HOUR_OF_DAY} -
764     *  Returns a {@code LocalTime} with the specified hour-of-day.
765     *  The minute-of-hour, second-of-minute and nano-of-second will be unchanged.
766     * <li>{@code CLOCK_HOUR_OF_DAY} -
767     *  Returns a {@code LocalTime} with the specified clock-hour-of-day.
768     *  The minute-of-hour, second-of-minute and nano-of-second will be unchanged.
769     * <li>{@code AMPM_OF_DAY} -
770     *  Returns a {@code LocalTime} with the specified AM/PM.
771     *  The hour-of-am-pm, minute-of-hour, second-of-minute and nano-of-second will be unchanged.
772     * </ul>
773     * <p>
774     * In all cases, if the new value is outside the valid range of values for the field
775     * then a {@code DateTimeException} will be thrown.
776     * <p>
777     * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
778     * <p>
779     * If the field is not a {@code ChronoField}, then the result of this method
780     * is obtained by invoking {@code TemporalField.doWith(Temporal, long)}
781     * passing {@code this} as the argument. In this case, the field determines
782     * whether and how to adjust the instant.
783     * <p>
784     * This instance is immutable and unaffected by this method call.
785     *
786     * @param field  the field to set in the result, not null
787     * @param newValue  the new value of the field in the result
788     * @return a {@code LocalTime} based on {@code this} with the specified field set, not null
789     * @throws DateTimeException if the field cannot be set
790     * @throws ArithmeticException if numeric overflow occurs
791     */
792    @Override
793    public LocalTime with(TemporalField field, long newValue) {
794        if (field instanceof ChronoField) {
795            ChronoField f = (ChronoField) field;
796            f.checkValidValue(newValue);
797            switch (f) {
798                case NANO_OF_SECOND: return withNano((int) newValue);
799                case NANO_OF_DAY: return LocalTime.ofNanoOfDay(newValue);
800                case MICRO_OF_SECOND: return withNano((int) newValue * 1000);
801                case MICRO_OF_DAY: return plusNanos((newValue - toNanoOfDay() / 1000) * 1000);
802                case MILLI_OF_SECOND: return withNano((int) newValue * 1000_000);
803                case MILLI_OF_DAY: return plusNanos((newValue - toNanoOfDay() / 1000_000) * 1000_000);
804                case SECOND_OF_MINUTE: return withSecond((int) newValue);
805                case SECOND_OF_DAY: return plusSeconds(newValue - toSecondOfDay());
806                case MINUTE_OF_HOUR: return withMinute((int) newValue);
807                case MINUTE_OF_DAY: return plusMinutes(newValue - (hour * 60 + minute));
808                case HOUR_OF_AMPM: return plusHours(newValue - (hour % 12));
809                case CLOCK_HOUR_OF_AMPM: return plusHours((newValue == 12 ? 0 : newValue) - (hour % 12));
810                case HOUR_OF_DAY: return withHour((int) newValue);
811                case CLOCK_HOUR_OF_DAY: return withHour((int) (newValue == 24 ? 0 : newValue));
812                case AMPM_OF_DAY: return plusHours((newValue - (hour / 12)) * 12);
813            }
814            throw new DateTimeException("Unsupported field: " + field.getName());
815        }
816        return field.doWith(this, newValue);
817    }
818
819    //-----------------------------------------------------------------------
820    /**
821     * Returns a copy of this {@code LocalTime} with the hour-of-day value altered.
822     * <p>
823     * This instance is immutable and unaffected by this method call.
824     *
825     * @param hour  the hour-of-day to set in the result, from 0 to 23
826     * @return a {@code LocalTime} based on this time with the requested hour, not null
827     * @throws DateTimeException if the hour value is invalid
828     */
829    public LocalTime withHour(int hour) {
830        if (this.hour == hour) {
831            return this;
832        }
833        HOUR_OF_DAY.checkValidValue(hour);
834        return create(hour, minute, second, nano);
835    }
836
837    /**
838     * Returns a copy of this {@code LocalTime} with the minute-of-hour value altered.
839     * <p>
840     * This instance is immutable and unaffected by this method call.
841     *
842     * @param minute  the minute-of-hour to set in the result, from 0 to 59
843     * @return a {@code LocalTime} based on this time with the requested minute, not null
844     * @throws DateTimeException if the minute value is invalid
845     */
846    public LocalTime withMinute(int minute) {
847        if (this.minute == minute) {
848            return this;
849        }
850        MINUTE_OF_HOUR.checkValidValue(minute);
851        return create(hour, minute, second, nano);
852    }
853
854    /**
855     * Returns a copy of this {@code LocalTime} with the second-of-minute value altered.
856     * <p>
857     * This instance is immutable and unaffected by this method call.
858     *
859     * @param second  the second-of-minute to set in the result, from 0 to 59
860     * @return a {@code LocalTime} based on this time with the requested second, not null
861     * @throws DateTimeException if the second value is invalid
862     */
863    public LocalTime withSecond(int second) {
864        if (this.second == second) {
865            return this;
866        }
867        SECOND_OF_MINUTE.checkValidValue(second);
868        return create(hour, minute, second, nano);
869    }
870
871    /**
872     * Returns a copy of this {@code LocalTime} with the nano-of-second value altered.
873     * <p>
874     * This instance is immutable and unaffected by this method call.
875     *
876     * @param nanoOfSecond  the nano-of-second to set in the result, from 0 to 999,999,999
877     * @return a {@code LocalTime} based on this time with the requested nanosecond, not null
878     * @throws DateTimeException if the nanos value is invalid
879     */
880    public LocalTime withNano(int nanoOfSecond) {
881        if (this.nano == nanoOfSecond) {
882            return this;
883        }
884        NANO_OF_SECOND.checkValidValue(nanoOfSecond);
885        return create(hour, minute, second, nanoOfSecond);
886    }
887
888    //-----------------------------------------------------------------------
889    /**
890     * Returns a copy of this {@code LocalTime} with the time truncated.
891     * <p>
892     * Truncating the time returns a copy of the original time with fields
893     * smaller than the specified unit set to zero.
894     * For example, truncating with the {@link ChronoUnit#MINUTES minutes} unit
895     * will set the second-of-minute and nano-of-second field to zero.
896     * <p>
897     * Not all units are accepted. The {@link ChronoUnit#DAYS days} unit and time
898     * units with an exact duration can be used, other units throw an exception.
899     * <p>
900     * This instance is immutable and unaffected by this method call.
901     *
902     * @param unit  the unit to truncate to, not null
903     * @return a {@code LocalTime} based on this time with the time truncated, not null
904     * @throws DateTimeException if unable to truncate
905     */
906    public LocalTime truncatedTo(TemporalUnit unit) {
907        if (unit == ChronoUnit.NANOS) {
908            return this;
909        } else if (unit == ChronoUnit.DAYS) {
910            return MIDNIGHT;
911        } else if (unit.isDurationEstimated()) {
912            throw new DateTimeException("Unit must not have an estimated duration");
913        }
914        long nod = toNanoOfDay();
915        long dur = unit.getDuration().toNanos();
916        if (dur >= NANOS_PER_DAY) {
917            throw new DateTimeException("Unit must not be a date unit");
918        }
919        nod = (nod / dur) * dur;
920        return ofNanoOfDay(nod);
921    }
922
923    //-----------------------------------------------------------------------
924    /**
925     * Returns a copy of this date with the specified period added.
926     * <p>
927     * This method returns a new time based on this time with the specified period added.
928     * The adder is typically {@link Period} but may be any other type implementing
929     * the {@link TemporalAdder} interface.
930     * The calculation is delegated to the specified adjuster, which typically calls
931     * back to {@link #plus(long, TemporalUnit)}.
932     * <p>
933     * This instance is immutable and unaffected by this method call.
934     *
935     * @param adder  the adder to use, not null
936     * @return a {@code LocalTime} based on this time with the addition made, not null
937     * @throws DateTimeException if the addition cannot be made
938     * @throws ArithmeticException if numeric overflow occurs
939     */
940    @Override
941    public LocalTime plus(TemporalAdder adder) {
942        return (LocalTime) adder.addTo(this);
943    }
944
945    /**
946     * Returns a copy of this time with the specified period added.
947     * <p>
948     * This method returns a new time based on this time with the specified period added.
949     * This can be used to add any period that is defined by a unit, for example to add hours, minutes or seconds.
950     * The unit is responsible for the details of the calculation, including the resolution
951     * of any edge cases in the calculation.
952     * <p>
953     * This instance is immutable and unaffected by this method call.
954     *
955     * @param amountToAdd  the amount of the unit to add to the result, may be negative
956     * @param unit  the unit of the period to add, not null
957     * @return a {@code LocalTime} based on this time with the specified period added, not null
958     * @throws DateTimeException if the unit cannot be added to this type
959     */
960    @Override
961    public LocalTime plus(long amountToAdd, TemporalUnit unit) {
962        if (unit instanceof ChronoUnit) {
963            ChronoUnit f = (ChronoUnit) unit;
964            switch (f) {
965                case NANOS: return plusNanos(amountToAdd);
966                case MICROS: return plusNanos((amountToAdd % MICROS_PER_DAY) * 1000);
967                case MILLIS: return plusNanos((amountToAdd % MILLIS_PER_DAY) * 1000_000);
968                case SECONDS: return plusSeconds(amountToAdd);
969                case MINUTES: return plusMinutes(amountToAdd);
970                case HOURS: return plusHours(amountToAdd);
971                case HALF_DAYS: return plusHours((amountToAdd % 2) * 12);
972                case DAYS: return this;
973            }
974            throw new DateTimeException("Unsupported unit: " + unit.getName());
975        }
976        return unit.doPlus(this, amountToAdd);
977    }
978
979    //-----------------------------------------------------------------------
980    /**
981     * Returns a copy of this {@code LocalTime} with the specified period in hours added.
982     * <p>
983     * This adds the specified number of hours to this time, returning a new time.
984     * The calculation wraps around midnight.
985     * <p>
986     * This instance is immutable and unaffected by this method call.
987     *
988     * @param hoursToAdd  the hours to add, may be negative
989     * @return a {@code LocalTime} based on this time with the hours added, not null
990     */
991    public LocalTime plusHours(long hoursToAdd) {
992        if (hoursToAdd == 0) {
993            return this;
994        }
995        int newHour = ((int) (hoursToAdd % HOURS_PER_DAY) + hour + HOURS_PER_DAY) % HOURS_PER_DAY;
996        return create(newHour, minute, second, nano);
997    }
998
999    /**
1000     * Returns a copy of this {@code LocalTime} with the specified period in minutes added.
1001     * <p>
1002     * This adds the specified number of minutes to this time, returning a new time.
1003     * The calculation wraps around midnight.
1004     * <p>
1005     * This instance is immutable and unaffected by this method call.
1006     *
1007     * @param minutesToAdd  the minutes to add, may be negative
1008     * @return a {@code LocalTime} based on this time with the minutes added, not null
1009     */
1010    public LocalTime plusMinutes(long minutesToAdd) {
1011        if (minutesToAdd == 0) {
1012            return this;
1013        }
1014        int mofd = hour * MINUTES_PER_HOUR + minute;
1015        int newMofd = ((int) (minutesToAdd % MINUTES_PER_DAY) + mofd + MINUTES_PER_DAY) % MINUTES_PER_DAY;
1016        if (mofd == newMofd) {
1017            return this;
1018        }
1019        int newHour = newMofd / MINUTES_PER_HOUR;
1020        int newMinute = newMofd % MINUTES_PER_HOUR;
1021        return create(newHour, newMinute, second, nano);
1022    }
1023
1024    /**
1025     * Returns a copy of this {@code LocalTime} with the specified period in seconds added.
1026     * <p>
1027     * This adds the specified number of seconds to this time, returning a new time.
1028     * The calculation wraps around midnight.
1029     * <p>
1030     * This instance is immutable and unaffected by this method call.
1031     *
1032     * @param secondstoAdd  the seconds to add, may be negative
1033     * @return a {@code LocalTime} based on this time with the seconds added, not null
1034     */
1035    public LocalTime plusSeconds(long secondstoAdd) {
1036        if (secondstoAdd == 0) {
1037            return this;
1038        }
1039        int sofd = hour * SECONDS_PER_HOUR +
1040                    minute * SECONDS_PER_MINUTE + second;
1041        int newSofd = ((int) (secondstoAdd % SECONDS_PER_DAY) + sofd + SECONDS_PER_DAY) % SECONDS_PER_DAY;
1042        if (sofd == newSofd) {
1043            return this;
1044        }
1045        int newHour = newSofd / SECONDS_PER_HOUR;
1046        int newMinute = (newSofd / SECONDS_PER_MINUTE) % MINUTES_PER_HOUR;
1047        int newSecond = newSofd % SECONDS_PER_MINUTE;
1048        return create(newHour, newMinute, newSecond, nano);
1049    }
1050
1051    /**
1052     * Returns a copy of this {@code LocalTime} with the specified period in nanoseconds added.
1053     * <p>
1054     * This adds the specified number of nanoseconds to this time, returning a new time.
1055     * The calculation wraps around midnight.
1056     * <p>
1057     * This instance is immutable and unaffected by this method call.
1058     *
1059     * @param nanosToAdd  the nanos to add, may be negative
1060     * @return a {@code LocalTime} based on this time with the nanoseconds added, not null
1061     */
1062    public LocalTime plusNanos(long nanosToAdd) {
1063        if (nanosToAdd == 0) {
1064            return this;
1065        }
1066        long nofd = toNanoOfDay();
1067        long newNofd = ((nanosToAdd % NANOS_PER_DAY) + nofd + NANOS_PER_DAY) % NANOS_PER_DAY;
1068        if (nofd == newNofd) {
1069            return this;
1070        }
1071        int newHour = (int) (newNofd / NANOS_PER_HOUR);
1072        int newMinute = (int) ((newNofd / NANOS_PER_MINUTE) % MINUTES_PER_HOUR);
1073        int newSecond = (int) ((newNofd / NANOS_PER_SECOND) % SECONDS_PER_MINUTE);
1074        int newNano = (int) (newNofd % NANOS_PER_SECOND);
1075        return create(newHour, newMinute, newSecond, newNano);
1076    }
1077
1078    //-----------------------------------------------------------------------
1079    /**
1080     * Returns a copy of this time with the specified period subtracted.
1081     * <p>
1082     * This method returns a new time based on this time with the specified period subtracted.
1083     * The subtractor is typically {@link Period} but may be any other type implementing
1084     * the {@link TemporalSubtractor} interface.
1085     * The calculation is delegated to the specified adjuster, which typically calls
1086     * back to {@link #minus(long, TemporalUnit)}.
1087     * <p>
1088     * This instance is immutable and unaffected by this method call.
1089     *
1090     * @param subtractor  the subtractor to use, not null
1091     * @return a {@code LocalTime} based on this time with the subtraction made, not null
1092     * @throws DateTimeException if the subtraction cannot be made
1093     * @throws ArithmeticException if numeric overflow occurs
1094     */
1095    @Override
1096    public LocalTime minus(TemporalSubtractor subtractor) {
1097        return (LocalTime) subtractor.subtractFrom(this);
1098    }
1099
1100    /**
1101     * Returns a copy of this time with the specified period subtracted.
1102     * <p>
1103     * This method returns a new time based on this time with the specified period subtracted.
1104     * This can be used to subtract any period that is defined by a unit, for example to subtract hours, minutes or seconds.
1105     * The unit is responsible for the details of the calculation, including the resolution
1106     * of any edge cases in the calculation.
1107     * <p>
1108     * This instance is immutable and unaffected by this method call.
1109     *
1110     * @param amountToSubtract  the amount of the unit to subtract from the result, may be negative
1111     * @param unit  the unit of the period to subtract, not null
1112     * @return a {@code LocalTime} based on this time with the specified period subtracted, not null
1113     * @throws DateTimeException if the unit cannot be added to this type
1114     */
1115    @Override
1116    public LocalTime minus(long amountToSubtract, TemporalUnit unit) {
1117        return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
1118    }
1119
1120    //-----------------------------------------------------------------------
1121    /**
1122     * Returns a copy of this {@code LocalTime} with the specified period in hours subtracted.
1123     * <p>
1124     * This subtracts the specified number of hours from this time, returning a new time.
1125     * The calculation wraps around midnight.
1126     * <p>
1127     * This instance is immutable and unaffected by this method call.
1128     *
1129     * @param hoursToSubtract  the hours to subtract, may be negative
1130     * @return a {@code LocalTime} based on this time with the hours subtracted, not null
1131     */
1132    public LocalTime minusHours(long hoursToSubtract) {
1133        return plusHours(-(hoursToSubtract % HOURS_PER_DAY));
1134    }
1135
1136    /**
1137     * Returns a copy of this {@code LocalTime} with the specified period in minutes subtracted.
1138     * <p>
1139     * This subtracts the specified number of minutes from this time, returning a new time.
1140     * The calculation wraps around midnight.
1141     * <p>
1142     * This instance is immutable and unaffected by this method call.
1143     *
1144     * @param minutesToSubtract  the minutes to subtract, may be negative
1145     * @return a {@code LocalTime} based on this time with the minutes subtracted, not null
1146     */
1147    public LocalTime minusMinutes(long minutesToSubtract) {
1148        return plusMinutes(-(minutesToSubtract % MINUTES_PER_DAY));
1149    }
1150
1151    /**
1152     * Returns a copy of this {@code LocalTime} with the specified period in seconds subtracted.
1153     * <p>
1154     * This subtracts the specified number of seconds from this time, returning a new time.
1155     * The calculation wraps around midnight.
1156     * <p>
1157     * This instance is immutable and unaffected by this method call.
1158     *
1159     * @param secondsToSubtract  the seconds to subtract, may be negative
1160     * @return a {@code LocalTime} based on this time with the seconds subtracted, not null
1161     */
1162    public LocalTime minusSeconds(long secondsToSubtract) {
1163        return plusSeconds(-(secondsToSubtract % SECONDS_PER_DAY));
1164    }
1165
1166    /**
1167     * Returns a copy of this {@code LocalTime} with the specified period in nanoseconds subtracted.
1168     * <p>
1169     * This subtracts the specified number of nanoseconds from this time, returning a new time.
1170     * The calculation wraps around midnight.
1171     * <p>
1172     * This instance is immutable and unaffected by this method call.
1173     *
1174     * @param nanosToSubtract  the nanos to subtract, may be negative
1175     * @return a {@code LocalTime} based on this time with the nanoseconds subtracted, not null
1176     */
1177    public LocalTime minusNanos(long nanosToSubtract) {
1178        return plusNanos(-(nanosToSubtract % NANOS_PER_DAY));
1179    }
1180
1181    //-----------------------------------------------------------------------
1182    /**
1183     * Queries this time using the specified query.
1184     * <p>
1185     * This queries this time using the specified query strategy object.
1186     * The {@code TemporalQuery} object defines the logic to be used to
1187     * obtain the result. Read the documentation of the query to understand
1188     * what the result of this method will be.
1189     * <p>
1190     * The result of this method is obtained by invoking the
1191     * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
1192     * specified query passing {@code this} as the argument.
1193     *
1194     * @param <R> the type of the result
1195     * @param query  the query to invoke, not null
1196     * @return the query result, null may be returned (defined by the query)
1197     * @throws DateTimeException if unable to query (defined by the query)
1198     * @throws ArithmeticException if numeric overflow occurs (defined by the query)
1199     */
1200    @SuppressWarnings("unchecked")
1201    @Override
1202    public <R> R query(TemporalQuery<R> query) {
1203        if (query == TemporalQueries.precision()) {
1204            return (R) NANOS;
1205        }
1206        // inline TemporalAccessor.super.query(query) as an optimization
1207        if (query == TemporalQueries.chrono() || query == TemporalQueries.zoneId() ||
1208                query == TemporalQueries.zone() || query == TemporalQueries.offset()) {
1209            return null;
1210        }
1211        return query.queryFrom(this);
1212    }
1213
1214    /**
1215     * Adjusts the specified temporal object to have the same time as this object.
1216     * <p>
1217     * This returns a temporal object of the same observable type as the input
1218     * with the time changed to be the same as this.
1219     * <p>
1220     * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
1221     * passing {@link ChronoField#NANO_OF_DAY} as the field.
1222     * <p>
1223     * In most cases, it is clearer to reverse the calling pattern by using
1224     * {@link Temporal#with(TemporalAdjuster)}:
1225     * <pre>
1226     *   // these two lines are equivalent, but the second approach is recommended
1227     *   temporal = thisLocalTime.adjustInto(temporal);
1228     *   temporal = temporal.with(thisLocalTime);
1229     * </pre>
1230     * <p>
1231     * This instance is immutable and unaffected by this method call.
1232     *
1233     * @param temporal  the target object to be adjusted, not null
1234     * @return the adjusted object, not null
1235     * @throws DateTimeException if unable to make the adjustment
1236     * @throws ArithmeticException if numeric overflow occurs
1237     */
1238    @Override
1239    public Temporal adjustInto(Temporal temporal) {
1240        return temporal.with(NANO_OF_DAY, toNanoOfDay());
1241    }
1242
1243    /**
1244     * Calculates the period between this time and another time in
1245     * terms of the specified unit.
1246     * <p>
1247     * This calculates the period between two times in terms of a single unit.
1248     * The start and end points are {@code this} and the specified time.
1249     * The result will be negative if the end is before the start.
1250     * The {@code Temporal} passed to this method must be a {@code LocalTime}.
1251     * For example, the period in hours between two times can be calculated
1252     * using {@code startTime.periodUntil(endTime, HOURS)}.
1253     * <p>
1254     * The calculation returns a whole number, representing the number of
1255     * complete units between the two times.
1256     * For example, the period in hours between 11:30 and 13:29 will only
1257     * be one hour as it is one minute short of two hours.
1258     * <p>
1259     * This method operates in association with {@link TemporalUnit#between}.
1260     * The result of this method is a {@code long} representing the amount of
1261     * the specified unit. By contrast, the result of {@code between} is an
1262     * object that can be used directly in addition/subtraction:
1263     * <pre>
1264     *   long period = start.periodUntil(end, HOURS);   // this method
1265     *   dateTime.plus(HOURS.between(start, end));      // use in plus/minus
1266     * </pre>
1267     * <p>
1268     * The calculation is implemented in this method for {@link ChronoUnit}.
1269     * The units {@code NANOS}, {@code MICROS}, {@code MILLIS}, {@code SECONDS},
1270     * {@code MINUTES}, {@code HOURS} and {@code HALF_DAYS} are supported.
1271     * Other {@code ChronoUnit} values will throw an exception.
1272     * <p>
1273     * If the unit is not a {@code ChronoUnit}, then the result of this method
1274     * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
1275     * passing {@code this} as the first argument and the input temporal as
1276     * the second argument.
1277     * <p>
1278     * This instance is immutable and unaffected by this method call.
1279     *
1280     * @param endTime  the end time, which must be a {@code LocalTime}, not null
1281     * @param unit  the unit to measure the period in, not null
1282     * @return the amount of the period between this time and the end time
1283     * @throws DateTimeException if the period cannot be calculated
1284     * @throws ArithmeticException if numeric overflow occurs
1285     */
1286    @Override
1287    public long periodUntil(Temporal endTime, TemporalUnit unit) {
1288        if (endTime instanceof LocalTime == false) {
1289            Objects.requireNonNull(endTime, "endTime");
1290            throw new DateTimeException("Unable to calculate period between objects of two different types");
1291        }
1292        LocalTime end = (LocalTime) endTime;
1293        if (unit instanceof ChronoUnit) {
1294            long nanosUntil = end.toNanoOfDay() - toNanoOfDay();  // no overflow
1295            switch ((ChronoUnit) unit) {
1296                case NANOS: return nanosUntil;
1297                case MICROS: return nanosUntil / 1000;
1298                case MILLIS: return nanosUntil / 1000_000;
1299                case SECONDS: return nanosUntil / NANOS_PER_SECOND;
1300                case MINUTES: return nanosUntil / NANOS_PER_MINUTE;
1301                case HOURS: return nanosUntil / NANOS_PER_HOUR;
1302                case HALF_DAYS: return nanosUntil / (12 * NANOS_PER_HOUR);
1303            }
1304            throw new DateTimeException("Unsupported unit: " + unit.getName());
1305        }
1306        return unit.between(this, endTime).getAmount();
1307    }
1308
1309    //-----------------------------------------------------------------------
1310    /**
1311     * Returns a local date-time formed from this time at the specified date.
1312     * <p>
1313     * This combines this time with the specified date to form a {@code LocalDateTime}.
1314     * All possible combinations of date and time are valid.
1315     * <p>
1316     * This instance is immutable and unaffected by this method call.
1317     *
1318     * @param date  the date to combine with, not null
1319     * @return the local date-time formed from this time and the specified date, not null
1320     */
1321    public LocalDateTime atDate(LocalDate date) {
1322        return LocalDateTime.of(date, this);
1323    }
1324
1325    /**
1326     * Returns an offset time formed from this time and the specified offset.
1327     * <p>
1328     * This combines this time with the specified offset to form an {@code OffsetTime}.
1329     * All possible combinations of time and offset are valid.
1330     * <p>
1331     * This instance is immutable and unaffected by this method call.
1332     *
1333     * @param offset  the offset to combine with, not null
1334     * @return the offset time formed from this time and the specified offset, not null
1335     */
1336    public OffsetTime atOffset(ZoneOffset offset) {
1337        return OffsetTime.of(this, offset);
1338    }
1339
1340    //-----------------------------------------------------------------------
1341    /**
1342     * Extracts the time as seconds of day,
1343     * from {@code 0} to {@code 24 * 60 * 60 - 1}.
1344     *
1345     * @return the second-of-day equivalent to this time
1346     */
1347    public int toSecondOfDay() {
1348        int total = hour * SECONDS_PER_HOUR;
1349        total += minute * SECONDS_PER_MINUTE;
1350        total += second;
1351        return total;
1352    }
1353
1354    /**
1355     * Extracts the time as nanos of day,
1356     * from {@code 0} to {@code 24 * 60 * 60 * 1,000,000,000 - 1}.
1357     *
1358     * @return the nano of day equivalent to this time
1359     */
1360    public long toNanoOfDay() {
1361        long total = hour * NANOS_PER_HOUR;
1362        total += minute * NANOS_PER_MINUTE;
1363        total += second * NANOS_PER_SECOND;
1364        total += nano;
1365        return total;
1366    }
1367
1368    //-----------------------------------------------------------------------
1369    /**
1370     * Compares this {@code LocalTime} to another time.
1371     * <p>
1372     * The comparison is based on the time-line position of the local times within a day.
1373     * It is "consistent with equals", as defined by {@link Comparable}.
1374     *
1375     * @param other  the other time to compare to, not null
1376     * @return the comparator value, negative if less, positive if greater
1377     * @throws NullPointerException if {@code other} is null
1378     */
1379    @Override
1380    public int compareTo(LocalTime other) {
1381        int cmp = Integer.compare(hour, other.hour);
1382        if (cmp == 0) {
1383            cmp = Integer.compare(minute, other.minute);
1384            if (cmp == 0) {
1385                cmp = Integer.compare(second, other.second);
1386                if (cmp == 0) {
1387                    cmp = Integer.compare(nano, other.nano);
1388                }
1389            }
1390        }
1391        return cmp;
1392    }
1393
1394    /**
1395     * Checks if this {@code LocalTime} is after the specified time.
1396     * <p>
1397     * The comparison is based on the time-line position of the time within a day.
1398     *
1399     * @param other  the other time to compare to, not null
1400     * @return true if this is after the specified time
1401     * @throws NullPointerException if {@code other} is null
1402     */
1403    public boolean isAfter(LocalTime other) {
1404        return compareTo(other) > 0;
1405    }
1406
1407    /**
1408     * Checks if this {@code LocalTime} is before the specified time.
1409     * <p>
1410     * The comparison is based on the time-line position of the time within a day.
1411     *
1412     * @param other  the other time to compare to, not null
1413     * @return true if this point is before the specified time
1414     * @throws NullPointerException if {@code other} is null
1415     */
1416    public boolean isBefore(LocalTime other) {
1417        return compareTo(other) < 0;
1418    }
1419
1420    //-----------------------------------------------------------------------
1421    /**
1422     * Checks if this time is equal to another time.
1423     * <p>
1424     * The comparison is based on the time-line position of the time within a day.
1425     * <p>
1426     * Only objects of type {@code LocalTime} are compared, other types return false.
1427     * To compare the date of two {@code TemporalAccessor} instances, use
1428     * {@link ChronoField#NANO_OF_DAY} as a comparator.
1429     *
1430     * @param obj  the object to check, null returns false
1431     * @return true if this is equal to the other time
1432     */
1433    @Override
1434    public boolean equals(Object obj) {
1435        if (this == obj) {
1436            return true;
1437        }
1438        if (obj instanceof LocalTime) {
1439            LocalTime other = (LocalTime) obj;
1440            return hour == other.hour && minute == other.minute &&
1441                    second == other.second && nano == other.nano;
1442        }
1443        return false;
1444    }
1445
1446    /**
1447     * A hash code for this time.
1448     *
1449     * @return a suitable hash code
1450     */
1451    @Override
1452    public int hashCode() {
1453        long nod = toNanoOfDay();
1454        return (int) (nod ^ (nod >>> 32));
1455    }
1456
1457    //-----------------------------------------------------------------------
1458    /**
1459     * Outputs this time as a {@code String}, such as {@code 10:15}.
1460     * <p>
1461     * The output will be one of the following ISO-8601 formats:
1462     * <p><ul>
1463     * <li>{@code HH:mm}</li>
1464     * <li>{@code HH:mm:ss}</li>
1465     * <li>{@code HH:mm:ss.SSS}</li>
1466     * <li>{@code HH:mm:ss.SSSSSS}</li>
1467     * <li>{@code HH:mm:ss.SSSSSSSSS}</li>
1468     * </ul><p>
1469     * The format used will be the shortest that outputs the full value of
1470     * the time where the omitted parts are implied to be zero.
1471     *
1472     * @return a string representation of this time, not null
1473     */
1474    @Override
1475    public String toString() {
1476        StringBuilder buf = new StringBuilder(18);
1477        int hourValue = hour;
1478        int minuteValue = minute;
1479        int secondValue = second;
1480        int nanoValue = nano;
1481        buf.append(hourValue < 10 ? "0" : "").append(hourValue)
1482            .append(minuteValue < 10 ? ":0" : ":").append(minuteValue);
1483        if (secondValue > 0 || nanoValue > 0) {
1484            buf.append(secondValue < 10 ? ":0" : ":").append(secondValue);
1485            if (nanoValue > 0) {
1486                buf.append('.');
1487                if (nanoValue % 1000_000 == 0) {
1488                    buf.append(Integer.toString((nanoValue / 1000_000) + 1000).substring(1));
1489                } else if (nanoValue % 1000 == 0) {
1490                    buf.append(Integer.toString((nanoValue / 1000) + 1000_000).substring(1));
1491                } else {
1492                    buf.append(Integer.toString((nanoValue) + 1000_000_000).substring(1));
1493                }
1494            }
1495        }
1496        return buf.toString();
1497    }
1498
1499    /**
1500     * Outputs this time as a {@code String} using the formatter.
1501     * <p>
1502     * This time will be passed to the formatter
1503     * {@link DateTimeFormatter#print(TemporalAccessor) print method}.
1504     *
1505     * @param formatter  the formatter to use, not null
1506     * @return the formatted time string, not null
1507     * @throws DateTimeException if an error occurs during printing
1508     */
1509    public String toString(DateTimeFormatter formatter) {
1510        Objects.requireNonNull(formatter, "formatter");
1511        return formatter.print(this);
1512    }
1513
1514    //-----------------------------------------------------------------------
1515    private Object writeReplace() {
1516        return new Ser(Ser.LOCAL_TIME_TYPE, this);
1517    }
1518
1519    /**
1520     * Defend against malicious streams.
1521     * @return never
1522     * @throws InvalidObjectException always
1523     */
1524    private Object readResolve() throws ObjectStreamException {
1525        throw new InvalidObjectException("Deserialization via serialization delegate");
1526    }
1527
1528    void writeExternal(DataOutput out) throws IOException {
1529        if (nano == 0) {
1530            if (second == 0) {
1531                if (minute == 0) {
1532                    out.writeByte(~hour);
1533                } else {
1534                    out.writeByte(hour);
1535                    out.writeByte(~minute);
1536                }
1537            } else {
1538                out.writeByte(hour);
1539                out.writeByte(minute);
1540                out.writeByte(~second);
1541            }
1542        } else {
1543            out.writeByte(hour);
1544            out.writeByte(minute);
1545            out.writeByte(second);
1546            out.writeInt(nano);
1547        }
1548    }
1549
1550    static LocalTime readExternal(DataInput in) throws IOException {
1551        int hour = in.readByte();
1552        int minute = 0;
1553        int second = 0;
1554        int nano = 0;
1555        if (hour < 0) {
1556            hour = ~hour;
1557        } else {
1558            minute = in.readByte();
1559            if (minute < 0) {
1560                minute = ~minute;
1561            } else {
1562                second = in.readByte();
1563                if (second < 0) {
1564                    second = ~second;
1565                } else {
1566                    nano = in.readInt();
1567                }
1568            }
1569        }
1570        return LocalTime.of(hour, minute, second, nano);
1571    }
1572
1573}