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.Queries;
  84 import java.time.temporal.Temporal;
  85 import java.time.temporal.TemporalAccessor;
  86 import java.time.temporal.TemporalAdjuster;
  87 import java.time.temporal.TemporalAmount;
  88 import java.time.temporal.TemporalField;
  89 import java.time.temporal.TemporalQuery;
  90 import java.time.temporal.TemporalUnit;
  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 Queries#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(Queries.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 ((ChronoField) field).isTimeField();
 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 a {@code DateTimeException}.
 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      */
 535     @Override  // override for Javadoc
 536     public ValueRange range(TemporalField field) {
 537         return Temporal.super.range(field);
 538     }
 539 
 540     /**
 541      * Gets the value of the specified field from this time as an {@code int}.
 542      * <p>
 543      * This queries this time for the value for the specified field.
 544      * The returned value will always be within the valid range of values for the field.
 545      * If it is not possible to return the value, because the field is not supported
 546      * or for some other reason, an exception is thrown.
 547      * <p>
 548      * If the field is a {@link ChronoField} then the query is implemented here.
 549      * The {@link #isSupported(TemporalField) supported fields} will return valid
 550      * values based on this time, except {@code NANO_OF_DAY} and {@code MICRO_OF_DAY}
 551      * which are too large to fit in an {@code int} and throw a {@code DateTimeException}.
 552      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 553      * <p>
 554      * If the field is not a {@code ChronoField}, then the result of this method
 555      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
 556      * passing {@code this} as the argument. Whether the value can be obtained,
 557      * and what the value represents, is determined by the field.
 558      *
 559      * @param field  the field to get, not null
 560      * @return the value for the field
 561      * @throws DateTimeException if a value for the field cannot be obtained
 562      * @throws ArithmeticException if numeric overflow occurs
 563      */
 564     @Override  // override for Javadoc and performance
 565     public int get(TemporalField field) {
 566         if (field instanceof ChronoField) {
 567             return get0(field);
 568         }
 569         return Temporal.super.get(field);
 570     }
 571 
 572     /**
 573      * Gets the value of the specified field from this time as a {@code long}.
 574      * <p>
 575      * This queries this time for the value for the specified field.
 576      * If it is not possible to return the value, because the field is not supported
 577      * or for some other reason, an exception is thrown.
 578      * <p>
 579      * If the field is a {@link ChronoField} then the query is implemented here.
 580      * The {@link #isSupported(TemporalField) supported fields} will return valid
 581      * values based on this time.
 582      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 583      * <p>
 584      * If the field is not a {@code ChronoField}, then the result of this method
 585      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
 586      * passing {@code this} as the argument. Whether the value can be obtained,
 587      * and what the value represents, is determined by the field.
 588      *
 589      * @param field  the field to get, not null
 590      * @return the value for the field
 591      * @throws DateTimeException if a value for the field cannot be obtained
 592      * @throws ArithmeticException if numeric overflow occurs
 593      */
 594     @Override
 595     public long getLong(TemporalField field) {
 596         if (field instanceof ChronoField) {
 597             if (field == NANO_OF_DAY) {
 598                 return toNanoOfDay();
 599             }
 600             if (field == MICRO_OF_DAY) {
 601                 return toNanoOfDay() / 1000;
 602             }
 603             return get0(field);
 604         }
 605         return field.getFrom(this);
 606     }
 607 
 608     private int get0(TemporalField field) {
 609         switch ((ChronoField) field) {
 610             case NANO_OF_SECOND: return nano;
 611             case NANO_OF_DAY: throw new DateTimeException("Field too large for an int: " + field);
 612             case MICRO_OF_SECOND: return nano / 1000;
 613             case MICRO_OF_DAY: throw new DateTimeException("Field too large for an int: " + field);
 614             case MILLI_OF_SECOND: return nano / 1000_000;
 615             case MILLI_OF_DAY: return (int) (toNanoOfDay() / 1000_000);
 616             case SECOND_OF_MINUTE: return second;
 617             case SECOND_OF_DAY: return toSecondOfDay();
 618             case MINUTE_OF_HOUR: return minute;
 619             case MINUTE_OF_DAY: return hour * 60 + minute;
 620             case HOUR_OF_AMPM: return hour % 12;
 621             case CLOCK_HOUR_OF_AMPM: int ham = hour % 12; return (ham % 12 == 0 ? 12 : ham);
 622             case HOUR_OF_DAY: return hour;
 623             case CLOCK_HOUR_OF_DAY: return (hour == 0 ? 24 : hour);
 624             case AMPM_OF_DAY: return hour / 12;
 625         }
 626         throw new DateTimeException("Unsupported field: " + field.getName());
 627     }
 628 
 629     //-----------------------------------------------------------------------
 630     /**
 631      * Gets the hour-of-day field.
 632      *
 633      * @return the hour-of-day, from 0 to 23
 634      */
 635     public int getHour() {
 636         return hour;
 637     }
 638 
 639     /**
 640      * Gets the minute-of-hour field.
 641      *
 642      * @return the minute-of-hour, from 0 to 59
 643      */
 644     public int getMinute() {
 645         return minute;
 646     }
 647 
 648     /**
 649      * Gets the second-of-minute field.
 650      *
 651      * @return the second-of-minute, from 0 to 59
 652      */
 653     public int getSecond() {
 654         return second;
 655     }
 656 
 657     /**
 658      * Gets the nano-of-second field.
 659      *
 660      * @return the nano-of-second, from 0 to 999,999,999
 661      */
 662     public int getNano() {
 663         return nano;
 664     }
 665 
 666     //-----------------------------------------------------------------------
 667     /**
 668      * Returns an adjusted copy of this time.
 669      * <p>
 670      * This returns a {@code LocalTime}, based on this one, with the time adjusted.
 671      * The adjustment takes place using the specified adjuster strategy object.
 672      * Read the documentation of the adjuster to understand what adjustment will be made.
 673      * <p>
 674      * A simple adjuster might simply set the one of the fields, such as the hour field.
 675      * A more complex adjuster might set the time to the last hour of the day.
 676      * <p>
 677      * The result of this method is obtained by invoking the
 678      * {@link TemporalAdjuster#adjustInto(Temporal)} method on the
 679      * specified adjuster passing {@code this} as the argument.
 680      * <p>
 681      * This instance is immutable and unaffected by this method call.
 682      *
 683      * @param adjuster the adjuster to use, not null
 684      * @return a {@code LocalTime} based on {@code this} with the adjustment made, not null
 685      * @throws DateTimeException if the adjustment cannot be made
 686      * @throws ArithmeticException if numeric overflow occurs
 687      */
 688     @Override
 689     public LocalTime with(TemporalAdjuster adjuster) {
 690         // optimizations
 691         if (adjuster instanceof LocalTime) {
 692             return (LocalTime) adjuster;
 693         }
 694         return (LocalTime) adjuster.adjustInto(this);
 695     }
 696 
 697     /**
 698      * Returns a copy of this time with the specified field set to a new value.
 699      * <p>
 700      * This returns a {@code LocalTime}, based on this one, with the value
 701      * for the specified field changed.
 702      * This can be used to change any supported field, such as the hour, minute or second.
 703      * If it is not possible to set the value, because the field is not supported or for
 704      * some other reason, an exception is thrown.
 705      * <p>
 706      * If the field is a {@link ChronoField} then the adjustment is implemented here.
 707      * The supported fields behave as follows:
 708      * <ul>
 709      * <li>{@code NANO_OF_SECOND} -
 710      *  Returns a {@code LocalTime} with the specified nano-of-second.
 711      *  The hour, minute and second will be unchanged.
 712      * <li>{@code NANO_OF_DAY} -
 713      *  Returns a {@code LocalTime} with the specified nano-of-day.
 714      *  This completely replaces the time and is equivalent to {@link #ofNanoOfDay(long)}.
 715      * <li>{@code MICRO_OF_SECOND} -
 716      *  Returns a {@code LocalTime} with the nano-of-second replaced by the specified
 717      *  micro-of-second multiplied by 1,000.
 718      *  The hour, minute and second will be unchanged.
 719      * <li>{@code MICRO_OF_DAY} -
 720      *  Returns a {@code LocalTime} with the specified micro-of-day.
 721      *  This completely replaces the time and is equivalent to using {@link #ofNanoOfDay(long)}
 722      *  with the micro-of-day multiplied by 1,000.
 723      * <li>{@code MILLI_OF_SECOND} -
 724      *  Returns a {@code LocalTime} with the nano-of-second replaced by the specified
 725      *  milli-of-second multiplied by 1,000,000.
 726      *  The hour, minute and second will be unchanged.
 727      * <li>{@code MILLI_OF_DAY} -
 728      *  Returns a {@code LocalTime} with the specified milli-of-day.
 729      *  This completely replaces the time and is equivalent to using {@link #ofNanoOfDay(long)}
 730      *  with the milli-of-day multiplied by 1,000,000.
 731      * <li>{@code SECOND_OF_MINUTE} -
 732      *  Returns a {@code LocalTime} with the specified second-of-minute.
 733      *  The hour, minute and nano-of-second will be unchanged.
 734      * <li>{@code SECOND_OF_DAY} -
 735      *  Returns a {@code LocalTime} with the specified second-of-day.
 736      *  The nano-of-second will be unchanged.
 737      * <li>{@code MINUTE_OF_HOUR} -
 738      *  Returns a {@code LocalTime} with the specified minute-of-hour.
 739      *  The hour, second-of-minute and nano-of-second will be unchanged.
 740      * <li>{@code MINUTE_OF_DAY} -
 741      *  Returns a {@code LocalTime} with the specified minute-of-day.
 742      *  The second-of-minute and nano-of-second will be unchanged.
 743      * <li>{@code HOUR_OF_AMPM} -
 744      *  Returns a {@code LocalTime} with the specified hour-of-am-pm.
 745      *  The AM/PM, minute-of-hour, second-of-minute and nano-of-second will be unchanged.
 746      * <li>{@code CLOCK_HOUR_OF_AMPM} -
 747      *  Returns a {@code LocalTime} with the specified clock-hour-of-am-pm.
 748      *  The AM/PM, minute-of-hour, second-of-minute and nano-of-second will be unchanged.
 749      * <li>{@code HOUR_OF_DAY} -
 750      *  Returns a {@code LocalTime} with the specified hour-of-day.
 751      *  The minute-of-hour, second-of-minute and nano-of-second will be unchanged.
 752      * <li>{@code CLOCK_HOUR_OF_DAY} -
 753      *  Returns a {@code LocalTime} with the specified clock-hour-of-day.
 754      *  The minute-of-hour, second-of-minute and nano-of-second will be unchanged.
 755      * <li>{@code AMPM_OF_DAY} -
 756      *  Returns a {@code LocalTime} with the specified AM/PM.
 757      *  The hour-of-am-pm, minute-of-hour, second-of-minute and nano-of-second will be unchanged.
 758      * </ul>
 759      * <p>
 760      * In all cases, if the new value is outside the valid range of values for the field
 761      * then a {@code DateTimeException} will be thrown.
 762      * <p>
 763      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 764      * <p>
 765      * If the field is not a {@code ChronoField}, then the result of this method
 766      * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
 767      * passing {@code this} as the argument. In this case, the field determines
 768      * whether and how to adjust the instant.
 769      * <p>
 770      * This instance is immutable and unaffected by this method call.
 771      *
 772      * @param field  the field to set in the result, not null
 773      * @param newValue  the new value of the field in the result
 774      * @return a {@code LocalTime} based on {@code this} with the specified field set, not null
 775      * @throws DateTimeException if the field cannot be set
 776      * @throws ArithmeticException if numeric overflow occurs
 777      */
 778     @Override
 779     public LocalTime with(TemporalField field, long newValue) {
 780         if (field instanceof ChronoField) {
 781             ChronoField f = (ChronoField) field;
 782             f.checkValidValue(newValue);
 783             switch (f) {
 784                 case NANO_OF_SECOND: return withNano((int) newValue);
 785                 case NANO_OF_DAY: return LocalTime.ofNanoOfDay(newValue);
 786                 case MICRO_OF_SECOND: return withNano((int) newValue * 1000);
 787                 case MICRO_OF_DAY: return plusNanos((newValue - toNanoOfDay() / 1000) * 1000);
 788                 case MILLI_OF_SECOND: return withNano((int) newValue * 1000_000);
 789                 case MILLI_OF_DAY: return plusNanos((newValue - toNanoOfDay() / 1000_000) * 1000_000);
 790                 case SECOND_OF_MINUTE: return withSecond((int) newValue);
 791                 case SECOND_OF_DAY: return plusSeconds(newValue - toSecondOfDay());
 792                 case MINUTE_OF_HOUR: return withMinute((int) newValue);
 793                 case MINUTE_OF_DAY: return plusMinutes(newValue - (hour * 60 + minute));
 794                 case HOUR_OF_AMPM: return plusHours(newValue - (hour % 12));
 795                 case CLOCK_HOUR_OF_AMPM: return plusHours((newValue == 12 ? 0 : newValue) - (hour % 12));
 796                 case HOUR_OF_DAY: return withHour((int) newValue);
 797                 case CLOCK_HOUR_OF_DAY: return withHour((int) (newValue == 24 ? 0 : newValue));
 798                 case AMPM_OF_DAY: return plusHours((newValue - (hour / 12)) * 12);
 799             }
 800             throw new DateTimeException("Unsupported field: " + field.getName());
 801         }
 802         return field.adjustInto(this, newValue);
 803     }
 804 
 805     //-----------------------------------------------------------------------
 806     /**
 807      * Returns a copy of this {@code LocalTime} with the hour-of-day value altered.
 808      * <p>
 809      * This instance is immutable and unaffected by this method call.
 810      *
 811      * @param hour  the hour-of-day to set in the result, from 0 to 23
 812      * @return a {@code LocalTime} based on this time with the requested hour, not null
 813      * @throws DateTimeException if the hour value is invalid
 814      */
 815     public LocalTime withHour(int hour) {
 816         if (this.hour == hour) {
 817             return this;
 818         }
 819         HOUR_OF_DAY.checkValidValue(hour);
 820         return create(hour, minute, second, nano);
 821     }
 822 
 823     /**
 824      * Returns a copy of this {@code LocalTime} with the minute-of-hour value altered.
 825      * <p>
 826      * This instance is immutable and unaffected by this method call.
 827      *
 828      * @param minute  the minute-of-hour to set in the result, from 0 to 59
 829      * @return a {@code LocalTime} based on this time with the requested minute, not null
 830      * @throws DateTimeException if the minute value is invalid
 831      */
 832     public LocalTime withMinute(int minute) {
 833         if (this.minute == minute) {
 834             return this;
 835         }
 836         MINUTE_OF_HOUR.checkValidValue(minute);
 837         return create(hour, minute, second, nano);
 838     }
 839 
 840     /**
 841      * Returns a copy of this {@code LocalTime} with the second-of-minute value altered.
 842      * <p>
 843      * This instance is immutable and unaffected by this method call.
 844      *
 845      * @param second  the second-of-minute to set in the result, from 0 to 59
 846      * @return a {@code LocalTime} based on this time with the requested second, not null
 847      * @throws DateTimeException if the second value is invalid
 848      */
 849     public LocalTime withSecond(int second) {
 850         if (this.second == second) {
 851             return this;
 852         }
 853         SECOND_OF_MINUTE.checkValidValue(second);
 854         return create(hour, minute, second, nano);
 855     }
 856 
 857     /**
 858      * Returns a copy of this {@code LocalTime} with the nano-of-second value altered.
 859      * <p>
 860      * This instance is immutable and unaffected by this method call.
 861      *
 862      * @param nanoOfSecond  the nano-of-second to set in the result, from 0 to 999,999,999
 863      * @return a {@code LocalTime} based on this time with the requested nanosecond, not null
 864      * @throws DateTimeException if the nanos value is invalid
 865      */
 866     public LocalTime withNano(int nanoOfSecond) {
 867         if (this.nano == nanoOfSecond) {
 868             return this;
 869         }
 870         NANO_OF_SECOND.checkValidValue(nanoOfSecond);
 871         return create(hour, minute, second, nanoOfSecond);
 872     }
 873 
 874     //-----------------------------------------------------------------------
 875     /**
 876      * Returns a copy of this {@code LocalTime} with the time truncated.
 877      * <p>
 878      * Truncating the time returns a copy of the original time with fields
 879      * smaller than the specified unit set to zero.
 880      * For example, truncating with the {@link ChronoUnit#MINUTES minutes} unit
 881      * will set the second-of-minute and nano-of-second field to zero.
 882      * <p>
 883      * The unit must have a {@linkplain TemporalUnit#getDuration() duration}
 884      * that divides into the length of a standard day without remainder.
 885      * This includes all supplied time units on {@link ChronoUnit} and
 886      * {@link ChronoUnit#DAYS DAYS}. Other units throw an exception.
 887      * <p>
 888      * This instance is immutable and unaffected by this method call.
 889      *
 890      * @param unit  the unit to truncate to, not null
 891      * @return a {@code LocalTime} based on this time with the time truncated, not null
 892      * @throws DateTimeException if unable to truncate
 893      */
 894     public LocalTime truncatedTo(TemporalUnit unit) {
 895         if (unit == ChronoUnit.NANOS) {
 896             return this;
 897         }
 898         Duration unitDur = unit.getDuration();
 899         if (unitDur.getSeconds() > SECONDS_PER_DAY) {
 900             throw new DateTimeException("Unit is too large to be used for truncation");
 901         }
 902         long dur = unitDur.toNanos();
 903         if ((NANOS_PER_DAY % dur) != 0) {
 904             throw new DateTimeException("Unit must divide into a standard day without remainder");
 905         }
 906         long nod = toNanoOfDay();
 907         return ofNanoOfDay((nod / dur) * dur);
 908     }
 909 
 910     //-----------------------------------------------------------------------
 911     /**
 912      * Returns a copy of this time with the specified amount added.
 913      * <p>
 914      * This returns a {@code LocalTime}, based on this one, with the specified amount added.
 915      * The amount is typically {@link Duration} but may be any other type implementing
 916      * the {@link TemporalAmount} interface.
 917      * <p>
 918      * The calculation is delegated to the amount object by calling
 919      * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free
 920      * to implement the addition in any way it wishes, however it typically
 921      * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation
 922      * of the amount implementation to determine if it can be successfully added.
 923      * <p>
 924      * This instance is immutable and unaffected by this method call.
 925      *
 926      * @param amountToAdd  the amount to add, not null
 927      * @return a {@code LocalTime} based on this time with the addition made, not null
 928      * @throws DateTimeException if the addition cannot be made
 929      * @throws ArithmeticException if numeric overflow occurs
 930      */
 931     @Override
 932     public LocalTime plus(TemporalAmount amountToAdd) {
 933         return (LocalTime) amountToAdd.addTo(this);
 934     }
 935 
 936     /**
 937      * Returns a copy of this time with the specified amount added.
 938      * <p>
 939      * This returns a {@code LocalTime}, based on this one, with the amount
 940      * in terms of the unit added. If it is not possible to add the amount, because the
 941      * unit is not supported or for some other reason, an exception is thrown.
 942      * <p>
 943      * If the field is a {@link ChronoUnit} then the addition is implemented here.
 944      * The supported fields behave as follows:
 945      * <ul>
 946      * <li>{@code NANOS} -
 947      *  Returns a {@code LocalTime} with the specified number of nanoseconds added.
 948      *  This is equivalent to {@link #plusNanos(long)}.
 949      * <li>{@code MICROS} -
 950      *  Returns a {@code LocalTime} with the specified number of microseconds added.
 951      *  This is equivalent to {@link #plusNanos(long)} with the amount
 952      *  multiplied by 1,000.
 953      * <li>{@code MILLIS} -
 954      *  Returns a {@code LocalTime} with the specified number of milliseconds added.
 955      *  This is equivalent to {@link #plusNanos(long)} with the amount
 956      *  multiplied by 1,000,000.
 957      * <li>{@code SECONDS} -
 958      *  Returns a {@code LocalTime} with the specified number of seconds added.
 959      *  This is equivalent to {@link #plusSeconds(long)}.
 960      * <li>{@code MINUTES} -
 961      *  Returns a {@code LocalTime} with the specified number of minutes added.
 962      *  This is equivalent to {@link #plusMinutes(long)}.
 963      * <li>{@code HOURS} -
 964      *  Returns a {@code LocalTime} with the specified number of hours added.
 965      *  This is equivalent to {@link #plusHours(long)}.
 966      * <li>{@code HALF_DAYS} -
 967      *  Returns a {@code LocalTime} with the specified number of half-days added.
 968      *  This is equivalent to {@link #plusHours(long)} with the amount
 969      *  multiplied by 12.
 970      * <li>{@code DAYS} -
 971      *  Returns a {@code LocalTime} with the specified number of days added.
 972      *  This returns {@code this} time.
 973      * </ul>
 974      * <p>
 975      * All other {@code ChronoUnit} instances will throw a {@code DateTimeException}.
 976      * <p>
 977      * If the field is not a {@code ChronoUnit}, then the result of this method
 978      * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
 979      * passing {@code this} as the argument. In this case, the unit determines
 980      * whether and how to perform the addition.
 981      * <p>
 982      * This instance is immutable and unaffected by this method call.
 983      *
 984      * @param amountToAdd  the amount of the unit to add to the result, may be negative
 985      * @param unit  the unit of the amount to add, not null
 986      * @return a {@code LocalTime} based on this time with the specified amount added, not null
 987      * @throws DateTimeException if the addition cannot be made
 988      * @throws ArithmeticException if numeric overflow occurs
 989      */
 990     @Override
 991     public LocalTime plus(long amountToAdd, TemporalUnit unit) {
 992         if (unit instanceof ChronoUnit) {
 993             ChronoUnit f = (ChronoUnit) unit;
 994             switch (f) {
 995                 case NANOS: return plusNanos(amountToAdd);
 996                 case MICROS: return plusNanos((amountToAdd % MICROS_PER_DAY) * 1000);
 997                 case MILLIS: return plusNanos((amountToAdd % MILLIS_PER_DAY) * 1000_000);
 998                 case SECONDS: return plusSeconds(amountToAdd);
 999                 case MINUTES: return plusMinutes(amountToAdd);
1000                 case HOURS: return plusHours(amountToAdd);
1001                 case HALF_DAYS: return plusHours((amountToAdd % 2) * 12);
1002                 case DAYS: return this;
1003             }
1004             throw new DateTimeException("Unsupported unit: " + unit.getName());
1005         }
1006         return unit.addTo(this, amountToAdd);
1007     }
1008 
1009     //-----------------------------------------------------------------------
1010     /**
1011      * Returns a copy of this {@code LocalTime} with the specified period in hours added.
1012      * <p>
1013      * This adds the specified number of hours to this time, returning a new time.
1014      * The calculation wraps around midnight.
1015      * <p>
1016      * This instance is immutable and unaffected by this method call.
1017      *
1018      * @param hoursToAdd  the hours to add, may be negative
1019      * @return a {@code LocalTime} based on this time with the hours added, not null
1020      */
1021     public LocalTime plusHours(long hoursToAdd) {
1022         if (hoursToAdd == 0) {
1023             return this;
1024         }
1025         int newHour = ((int) (hoursToAdd % HOURS_PER_DAY) + hour + HOURS_PER_DAY) % HOURS_PER_DAY;
1026         return create(newHour, minute, second, nano);
1027     }
1028 
1029     /**
1030      * Returns a copy of this {@code LocalTime} with the specified period in minutes added.
1031      * <p>
1032      * This adds the specified number of minutes to this time, returning a new time.
1033      * The calculation wraps around midnight.
1034      * <p>
1035      * This instance is immutable and unaffected by this method call.
1036      *
1037      * @param minutesToAdd  the minutes to add, may be negative
1038      * @return a {@code LocalTime} based on this time with the minutes added, not null
1039      */
1040     public LocalTime plusMinutes(long minutesToAdd) {
1041         if (minutesToAdd == 0) {
1042             return this;
1043         }
1044         int mofd = hour * MINUTES_PER_HOUR + minute;
1045         int newMofd = ((int) (minutesToAdd % MINUTES_PER_DAY) + mofd + MINUTES_PER_DAY) % MINUTES_PER_DAY;
1046         if (mofd == newMofd) {
1047             return this;
1048         }
1049         int newHour = newMofd / MINUTES_PER_HOUR;
1050         int newMinute = newMofd % MINUTES_PER_HOUR;
1051         return create(newHour, newMinute, second, nano);
1052     }
1053 
1054     /**
1055      * Returns a copy of this {@code LocalTime} with the specified period in seconds added.
1056      * <p>
1057      * This adds the specified number of seconds to this time, returning a new time.
1058      * The calculation wraps around midnight.
1059      * <p>
1060      * This instance is immutable and unaffected by this method call.
1061      *
1062      * @param secondstoAdd  the seconds to add, may be negative
1063      * @return a {@code LocalTime} based on this time with the seconds added, not null
1064      */
1065     public LocalTime plusSeconds(long secondstoAdd) {
1066         if (secondstoAdd == 0) {
1067             return this;
1068         }
1069         int sofd = hour * SECONDS_PER_HOUR +
1070                     minute * SECONDS_PER_MINUTE + second;
1071         int newSofd = ((int) (secondstoAdd % SECONDS_PER_DAY) + sofd + SECONDS_PER_DAY) % SECONDS_PER_DAY;
1072         if (sofd == newSofd) {
1073             return this;
1074         }
1075         int newHour = newSofd / SECONDS_PER_HOUR;
1076         int newMinute = (newSofd / SECONDS_PER_MINUTE) % MINUTES_PER_HOUR;
1077         int newSecond = newSofd % SECONDS_PER_MINUTE;
1078         return create(newHour, newMinute, newSecond, nano);
1079     }
1080 
1081     /**
1082      * Returns a copy of this {@code LocalTime} with the specified period in nanoseconds added.
1083      * <p>
1084      * This adds the specified number of nanoseconds to this time, returning a new time.
1085      * The calculation wraps around midnight.
1086      * <p>
1087      * This instance is immutable and unaffected by this method call.
1088      *
1089      * @param nanosToAdd  the nanos to add, may be negative
1090      * @return a {@code LocalTime} based on this time with the nanoseconds added, not null
1091      */
1092     public LocalTime plusNanos(long nanosToAdd) {
1093         if (nanosToAdd == 0) {
1094             return this;
1095         }
1096         long nofd = toNanoOfDay();
1097         long newNofd = ((nanosToAdd % NANOS_PER_DAY) + nofd + NANOS_PER_DAY) % NANOS_PER_DAY;
1098         if (nofd == newNofd) {
1099             return this;
1100         }
1101         int newHour = (int) (newNofd / NANOS_PER_HOUR);
1102         int newMinute = (int) ((newNofd / NANOS_PER_MINUTE) % MINUTES_PER_HOUR);
1103         int newSecond = (int) ((newNofd / NANOS_PER_SECOND) % SECONDS_PER_MINUTE);
1104         int newNano = (int) (newNofd % NANOS_PER_SECOND);
1105         return create(newHour, newMinute, newSecond, newNano);
1106     }
1107 
1108     //-----------------------------------------------------------------------
1109     /**
1110      * Returns a copy of this time with the specified amount subtracted.
1111      * <p>
1112      * This returns a {@code LocalTime}, based on this one, with the specified amount subtracted.
1113      * The amount is typically {@link Duration} but may be any other type implementing
1114      * the {@link TemporalAmount} interface.
1115      * <p>
1116      * The calculation is delegated to the amount object by calling
1117      * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free
1118      * to implement the subtraction in any way it wishes, however it typically
1119      * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation
1120      * of the amount implementation to determine if it can be successfully subtracted.
1121      * <p>
1122      * This instance is immutable and unaffected by this method call.
1123      *
1124      * @param amountToSubtract  the amount to subtract, not null
1125      * @return a {@code LocalTime} based on this time with the subtraction made, not null
1126      * @throws DateTimeException if the subtraction cannot be made
1127      * @throws ArithmeticException if numeric overflow occurs
1128      */
1129     @Override
1130     public LocalTime minus(TemporalAmount amountToSubtract) {
1131         return (LocalTime) amountToSubtract.subtractFrom(this);
1132     }
1133 
1134     /**
1135      * Returns a copy of this time with the specified amount subtracted.
1136      * <p>
1137      * This returns a {@code LocalTime}, based on this one, with the amount
1138      * in terms of the unit subtracted. If it is not possible to subtract the amount,
1139      * because the unit is not supported or for some other reason, an exception is thrown.
1140      * <p>
1141      * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.
1142      * See that method for a full description of how addition, and thus subtraction, works.
1143      * <p>
1144      * This instance is immutable and unaffected by this method call.
1145      *
1146      * @param amountToSubtract  the amount of the unit to subtract from the result, may be negative
1147      * @param unit  the unit of the amount to subtract, not null
1148      * @return a {@code LocalTime} based on this time with the specified amount subtracted, not null
1149      * @throws DateTimeException if the subtraction cannot be made
1150      * @throws ArithmeticException if numeric overflow occurs
1151      */
1152     @Override
1153     public LocalTime minus(long amountToSubtract, TemporalUnit unit) {
1154         return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
1155     }
1156 
1157     //-----------------------------------------------------------------------
1158     /**
1159      * Returns a copy of this {@code LocalTime} with the specified period in hours subtracted.
1160      * <p>
1161      * This subtracts the specified number of hours from this time, returning a new time.
1162      * The calculation wraps around midnight.
1163      * <p>
1164      * This instance is immutable and unaffected by this method call.
1165      *
1166      * @param hoursToSubtract  the hours to subtract, may be negative
1167      * @return a {@code LocalTime} based on this time with the hours subtracted, not null
1168      */
1169     public LocalTime minusHours(long hoursToSubtract) {
1170         return plusHours(-(hoursToSubtract % HOURS_PER_DAY));
1171     }
1172 
1173     /**
1174      * Returns a copy of this {@code LocalTime} with the specified period in minutes subtracted.
1175      * <p>
1176      * This subtracts the specified number of minutes from this time, returning a new time.
1177      * The calculation wraps around midnight.
1178      * <p>
1179      * This instance is immutable and unaffected by this method call.
1180      *
1181      * @param minutesToSubtract  the minutes to subtract, may be negative
1182      * @return a {@code LocalTime} based on this time with the minutes subtracted, not null
1183      */
1184     public LocalTime minusMinutes(long minutesToSubtract) {
1185         return plusMinutes(-(minutesToSubtract % MINUTES_PER_DAY));
1186     }
1187 
1188     /**
1189      * Returns a copy of this {@code LocalTime} with the specified period in seconds subtracted.
1190      * <p>
1191      * This subtracts the specified number of seconds from this time, returning a new time.
1192      * The calculation wraps around midnight.
1193      * <p>
1194      * This instance is immutable and unaffected by this method call.
1195      *
1196      * @param secondsToSubtract  the seconds to subtract, may be negative
1197      * @return a {@code LocalTime} based on this time with the seconds subtracted, not null
1198      */
1199     public LocalTime minusSeconds(long secondsToSubtract) {
1200         return plusSeconds(-(secondsToSubtract % SECONDS_PER_DAY));
1201     }
1202 
1203     /**
1204      * Returns a copy of this {@code LocalTime} with the specified period in nanoseconds subtracted.
1205      * <p>
1206      * This subtracts the specified number of nanoseconds from this time, returning a new time.
1207      * The calculation wraps around midnight.
1208      * <p>
1209      * This instance is immutable and unaffected by this method call.
1210      *
1211      * @param nanosToSubtract  the nanos to subtract, may be negative
1212      * @return a {@code LocalTime} based on this time with the nanoseconds subtracted, not null
1213      */
1214     public LocalTime minusNanos(long nanosToSubtract) {
1215         return plusNanos(-(nanosToSubtract % NANOS_PER_DAY));
1216     }
1217 
1218     //-----------------------------------------------------------------------
1219     /**
1220      * Queries this time using the specified query.
1221      * <p>
1222      * This queries this time using the specified query strategy object.
1223      * The {@code TemporalQuery} object defines the logic to be used to
1224      * obtain the result. Read the documentation of the query to understand
1225      * what the result of this method will be.
1226      * <p>
1227      * The result of this method is obtained by invoking the
1228      * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
1229      * specified query passing {@code this} as the argument.
1230      *
1231      * @param <R> the type of the result
1232      * @param query  the query to invoke, not null
1233      * @return the query result, null may be returned (defined by the query)
1234      * @throws DateTimeException if unable to query (defined by the query)
1235      * @throws ArithmeticException if numeric overflow occurs (defined by the query)
1236      */
1237     @SuppressWarnings("unchecked")
1238     @Override
1239     public <R> R query(TemporalQuery<R> query) {
1240         if (query == Queries.chronology() || query == Queries.zoneId() || query == Queries.zone() || query == Queries.offset()) {
1241             return null;
1242         } else if (query == Queries.localTime()) {
1243             return (R) this;
1244         } else if (query == Queries.localDate()) {
1245             return null;
1246         } else if (query == Queries.precision()) {
1247             return (R) NANOS;
1248         }
1249         // inline TemporalAccessor.super.query(query) as an optimization
1250         // non-JDK classes are not permitted to make this optimization
1251         return query.queryFrom(this);
1252     }
1253 
1254     /**
1255      * Adjusts the specified temporal object to have the same time as this object.
1256      * <p>
1257      * This returns a temporal object of the same observable type as the input
1258      * with the time changed to be the same as this.
1259      * <p>
1260      * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
1261      * passing {@link ChronoField#NANO_OF_DAY} as the field.
1262      * <p>
1263      * In most cases, it is clearer to reverse the calling pattern by using
1264      * {@link Temporal#with(TemporalAdjuster)}:
1265      * <pre>
1266      *   // these two lines are equivalent, but the second approach is recommended
1267      *   temporal = thisLocalTime.adjustInto(temporal);
1268      *   temporal = temporal.with(thisLocalTime);
1269      * </pre>
1270      * <p>
1271      * This instance is immutable and unaffected by this method call.
1272      *
1273      * @param temporal  the target object to be adjusted, not null
1274      * @return the adjusted object, not null
1275      * @throws DateTimeException if unable to make the adjustment
1276      * @throws ArithmeticException if numeric overflow occurs
1277      */
1278     @Override
1279     public Temporal adjustInto(Temporal temporal) {
1280         return temporal.with(NANO_OF_DAY, toNanoOfDay());
1281     }
1282 
1283     /**
1284      * Calculates the period between this time and another time in
1285      * terms of the specified unit.
1286      * <p>
1287      * This calculates the period between two times in terms of a single unit.
1288      * The start and end points are {@code this} and the specified time.
1289      * The result will be negative if the end is before the start.
1290      * The {@code Temporal} passed to this method must be a {@code LocalTime}.
1291      * For example, the period in hours between two times can be calculated
1292      * using {@code startTime.periodUntil(endTime, HOURS)}.
1293      * <p>
1294      * The calculation returns a whole number, representing the number of
1295      * complete units between the two times.
1296      * For example, the period in hours between 11:30 and 13:29 will only
1297      * be one hour as it is one minute short of two hours.
1298      * <p>
1299      * There are two equivalent ways of using this method.
1300      * The first is to invoke this method.
1301      * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
1302      * <pre>
1303      *   // these two lines are equivalent
1304      *   amount = start.periodUntil(end, MINUTES);
1305      *   amount = MINUTES.between(start, end);
1306      * </pre>
1307      * The choice should be made based on which makes the code more readable.
1308      * <p>
1309      * The calculation is implemented in this method for {@link ChronoUnit}.
1310      * The units {@code NANOS}, {@code MICROS}, {@code MILLIS}, {@code SECONDS},
1311      * {@code MINUTES}, {@code HOURS} and {@code HALF_DAYS} are supported.
1312      * Other {@code ChronoUnit} values will throw an exception.
1313      * <p>
1314      * If the unit is not a {@code ChronoUnit}, then the result of this method
1315      * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
1316      * passing {@code this} as the first argument and the input temporal as
1317      * the second argument.
1318      * <p>
1319      * This instance is immutable and unaffected by this method call.
1320      *
1321      * @param endTime  the end time, which must be a {@code LocalTime}, not null
1322      * @param unit  the unit to measure the period in, not null
1323      * @return the amount of the period between this time and the end time
1324      * @throws DateTimeException if the period cannot be calculated
1325      * @throws ArithmeticException if numeric overflow occurs
1326      */
1327     @Override
1328     public long periodUntil(Temporal endTime, TemporalUnit unit) {
1329         if (endTime instanceof LocalTime == false) {
1330             Objects.requireNonNull(endTime, "endTime");
1331             throw new DateTimeException("Unable to calculate period between objects of two different types");
1332         }
1333         LocalTime end = (LocalTime) endTime;
1334         if (unit instanceof ChronoUnit) {
1335             long nanosUntil = end.toNanoOfDay() - toNanoOfDay();  // no overflow
1336             switch ((ChronoUnit) unit) {
1337                 case NANOS: return nanosUntil;
1338                 case MICROS: return nanosUntil / 1000;
1339                 case MILLIS: return nanosUntil / 1000_000;
1340                 case SECONDS: return nanosUntil / NANOS_PER_SECOND;
1341                 case MINUTES: return nanosUntil / NANOS_PER_MINUTE;
1342                 case HOURS: return nanosUntil / NANOS_PER_HOUR;
1343                 case HALF_DAYS: return nanosUntil / (12 * NANOS_PER_HOUR);
1344             }
1345             throw new DateTimeException("Unsupported unit: " + unit.getName());
1346         }
1347         return unit.between(this, endTime);
1348     }
1349 
1350     //-----------------------------------------------------------------------
1351     /**
1352      * Combines this time with a date to create a {@code LocalDateTime}.
1353      * <p>
1354      * This returns a {@code LocalDateTime} formed from this time at the specified date.
1355      * All possible combinations of date and time are valid.
1356      *
1357      * @param date  the date to combine with, not null
1358      * @return the local date-time formed from this time and the specified date, not null
1359      */
1360     public LocalDateTime atDate(LocalDate date) {
1361         return LocalDateTime.of(date, this);
1362     }
1363 
1364     /**
1365      * Combines this time with a date to create an {@code OffsetTime}.
1366      * <p>
1367      * This returns an {@code OffsetTime} formed from this time at the specified offset.
1368      * All possible combinations of time and offset are valid.
1369      *
1370      * @param offset  the offset to combine with, not null
1371      * @return the offset time formed from this time and the specified offset, not null
1372      */
1373     public OffsetTime atOffset(ZoneOffset offset) {
1374         return OffsetTime.of(this, offset);
1375     }
1376 
1377     //-----------------------------------------------------------------------
1378     /**
1379      * Extracts the time as seconds of day,
1380      * from {@code 0} to {@code 24 * 60 * 60 - 1}.
1381      *
1382      * @return the second-of-day equivalent to this time
1383      */
1384     public int toSecondOfDay() {
1385         int total = hour * SECONDS_PER_HOUR;
1386         total += minute * SECONDS_PER_MINUTE;
1387         total += second;
1388         return total;
1389     }
1390 
1391     /**
1392      * Extracts the time as nanos of day,
1393      * from {@code 0} to {@code 24 * 60 * 60 * 1,000,000,000 - 1}.
1394      *
1395      * @return the nano of day equivalent to this time
1396      */
1397     public long toNanoOfDay() {
1398         long total = hour * NANOS_PER_HOUR;
1399         total += minute * NANOS_PER_MINUTE;
1400         total += second * NANOS_PER_SECOND;
1401         total += nano;
1402         return total;
1403     }
1404 
1405     //-----------------------------------------------------------------------
1406     /**
1407      * Compares this {@code LocalTime} to another time.
1408      * <p>
1409      * The comparison is based on the time-line position of the local times within a day.
1410      * It is "consistent with equals", as defined by {@link Comparable}.
1411      *
1412      * @param other  the other time to compare to, not null
1413      * @return the comparator value, negative if less, positive if greater
1414      * @throws NullPointerException if {@code other} is null
1415      */
1416     @Override
1417     public int compareTo(LocalTime other) {
1418         int cmp = Integer.compare(hour, other.hour);
1419         if (cmp == 0) {
1420             cmp = Integer.compare(minute, other.minute);
1421             if (cmp == 0) {
1422                 cmp = Integer.compare(second, other.second);
1423                 if (cmp == 0) {
1424                     cmp = Integer.compare(nano, other.nano);
1425                 }
1426             }
1427         }
1428         return cmp;
1429     }
1430 
1431     /**
1432      * Checks if this {@code LocalTime} is after the specified time.
1433      * <p>
1434      * The comparison is based on the time-line position of the time within a day.
1435      *
1436      * @param other  the other time to compare to, not null
1437      * @return true if this is after the specified time
1438      * @throws NullPointerException if {@code other} is null
1439      */
1440     public boolean isAfter(LocalTime other) {
1441         return compareTo(other) > 0;
1442     }
1443 
1444     /**
1445      * Checks if this {@code LocalTime} is before the specified time.
1446      * <p>
1447      * The comparison is based on the time-line position of the time within a day.
1448      *
1449      * @param other  the other time to compare to, not null
1450      * @return true if this point is before the specified time
1451      * @throws NullPointerException if {@code other} is null
1452      */
1453     public boolean isBefore(LocalTime other) {
1454         return compareTo(other) < 0;
1455     }
1456 
1457     //-----------------------------------------------------------------------
1458     /**
1459      * Checks if this time is equal to another time.
1460      * <p>
1461      * The comparison is based on the time-line position of the time within a day.
1462      * <p>
1463      * Only objects of type {@code LocalTime} are compared, other types return false.
1464      * To compare the date of two {@code TemporalAccessor} instances, use
1465      * {@link ChronoField#NANO_OF_DAY} as a comparator.
1466      *
1467      * @param obj  the object to check, null returns false
1468      * @return true if this is equal to the other time
1469      */
1470     @Override
1471     public boolean equals(Object obj) {
1472         if (this == obj) {
1473             return true;
1474         }
1475         if (obj instanceof LocalTime) {
1476             LocalTime other = (LocalTime) obj;
1477             return hour == other.hour && minute == other.minute &&
1478                     second == other.second && nano == other.nano;
1479         }
1480         return false;
1481     }
1482 
1483     /**
1484      * A hash code for this time.
1485      *
1486      * @return a suitable hash code
1487      */
1488     @Override
1489     public int hashCode() {
1490         long nod = toNanoOfDay();
1491         return (int) (nod ^ (nod >>> 32));
1492     }
1493 
1494     //-----------------------------------------------------------------------
1495     /**
1496      * Outputs this time as a {@code String}, such as {@code 10:15}.
1497      * <p>
1498      * The output will be one of the following ISO-8601 formats:
1499      * <p><ul>
1500      * <li>{@code HH:mm}</li>
1501      * <li>{@code HH:mm:ss}</li>
1502      * <li>{@code HH:mm:ss.SSS}</li>
1503      * <li>{@code HH:mm:ss.SSSSSS}</li>
1504      * <li>{@code HH:mm:ss.SSSSSSSSS}</li>
1505      * </ul><p>
1506      * The format used will be the shortest that outputs the full value of
1507      * the time where the omitted parts are implied to be zero.
1508      *
1509      * @return a string representation of this time, not null
1510      */
1511     @Override
1512     public String toString() {
1513         StringBuilder buf = new StringBuilder(18);
1514         int hourValue = hour;
1515         int minuteValue = minute;
1516         int secondValue = second;
1517         int nanoValue = nano;
1518         buf.append(hourValue < 10 ? "0" : "").append(hourValue)
1519             .append(minuteValue < 10 ? ":0" : ":").append(minuteValue);
1520         if (secondValue > 0 || nanoValue > 0) {
1521             buf.append(secondValue < 10 ? ":0" : ":").append(secondValue);
1522             if (nanoValue > 0) {
1523                 buf.append('.');
1524                 if (nanoValue % 1000_000 == 0) {
1525                     buf.append(Integer.toString((nanoValue / 1000_000) + 1000).substring(1));
1526                 } else if (nanoValue % 1000 == 0) {
1527                     buf.append(Integer.toString((nanoValue / 1000) + 1000_000).substring(1));
1528                 } else {
1529                     buf.append(Integer.toString((nanoValue) + 1000_000_000).substring(1));
1530                 }
1531             }
1532         }
1533         return buf.toString();
1534     }
1535 
1536     /**
1537      * Outputs this time as a {@code String} using the formatter.
1538      * <p>
1539      * This time will be passed to the formatter
1540      * {@link DateTimeFormatter#format(TemporalAccessor) format method}.
1541      *
1542      * @param formatter  the formatter to use, not null
1543      * @return the formatted time string, not null
1544      * @throws DateTimeException if an error occurs during printing
1545      */
1546     public String toString(DateTimeFormatter formatter) {
1547         Objects.requireNonNull(formatter, "formatter");
1548         return formatter.format(this);
1549     }
1550 
1551     //-----------------------------------------------------------------------
1552     /**
1553      * Writes the object using a
1554      * <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>.
1555      * <pre>
1556      *  out.writeByte(4);  // identifies this as a LocalTime
1557      *  if (nano == 0) {
1558      *    if (second == 0) {
1559      *      if (minute == 0) {
1560      *        out.writeByte(~hour);
1561      *      } else {
1562      *        out.writeByte(hour);
1563      *        out.writeByte(~minute);
1564      *      }
1565      *    } else {
1566      *      out.writeByte(hour);
1567      *      out.writeByte(minute);
1568      *      out.writeByte(~second);
1569      *    }
1570      *  } else {
1571      *    out.writeByte(hour);
1572      *    out.writeByte(minute);
1573      *    out.writeByte(second);
1574      *    out.writeInt(nano);
1575      *  }
1576      * </pre>
1577      *
1578      * @return the instance of {@code Ser}, not null
1579      */
1580     private Object writeReplace() {
1581         return new Ser(Ser.LOCAL_TIME_TYPE, this);
1582     }
1583 
1584     /**
1585      * Defend against malicious streams.
1586      * @return never
1587      * @throws InvalidObjectException always
1588      */
1589     private Object readResolve() throws ObjectStreamException {
1590         throw new InvalidObjectException("Deserialization via serialization delegate");
1591     }
1592 
1593     void writeExternal(DataOutput out) throws IOException {
1594         if (nano == 0) {
1595             if (second == 0) {
1596                 if (minute == 0) {
1597                     out.writeByte(~hour);
1598                 } else {
1599                     out.writeByte(hour);
1600                     out.writeByte(~minute);
1601                 }
1602             } else {
1603                 out.writeByte(hour);
1604                 out.writeByte(minute);
1605                 out.writeByte(~second);
1606             }
1607         } else {
1608             out.writeByte(hour);
1609             out.writeByte(minute);
1610             out.writeByte(second);
1611             out.writeInt(nano);
1612         }
1613     }
1614 
1615     static LocalTime readExternal(DataInput in) throws IOException {
1616         int hour = in.readByte();
1617         int minute = 0;
1618         int second = 0;
1619         int nano = 0;
1620         if (hour < 0) {
1621             hour = ~hour;
1622         } else {
1623             minute = in.readByte();
1624             if (minute < 0) {
1625                 minute = ~minute;
1626             } else {
1627                 second = in.readByte();
1628                 if (second < 0) {
1629                     second = ~second;
1630                 } else {
1631                     nano = in.readInt();
1632                 }
1633             }
1634         }
1635         return LocalTime.of(hour, minute, second, nano);
1636     }
1637 
1638 }