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