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