Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/time/LocalTime.java
38829 views
/*1* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file:30*31* Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos32*33* All rights reserved.34*35* Redistribution and use in source and binary forms, with or without36* modification, are permitted provided that the following conditions are met:37*38* * Redistributions of source code must retain the above copyright notice,39* this list of conditions and the following disclaimer.40*41* * Redistributions in binary form must reproduce the above copyright notice,42* this list of conditions and the following disclaimer in the documentation43* and/or other materials provided with the distribution.44*45* * Neither the name of JSR-310 nor the names of its contributors46* may be used to endorse or promote products derived from this software47* without specific prior written permission.48*49* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS50* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT51* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR52* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR53* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,54* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,55* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR56* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF57* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING58* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS59* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.60*/61package java.time;6263import static java.time.temporal.ChronoField.HOUR_OF_DAY;64import static java.time.temporal.ChronoField.MICRO_OF_DAY;65import static java.time.temporal.ChronoField.MINUTE_OF_HOUR;66import static java.time.temporal.ChronoField.NANO_OF_DAY;67import static java.time.temporal.ChronoField.NANO_OF_SECOND;68import static java.time.temporal.ChronoField.SECOND_OF_DAY;69import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;70import static java.time.temporal.ChronoUnit.NANOS;7172import java.io.DataInput;73import java.io.DataOutput;74import java.io.IOException;75import java.io.InvalidObjectException;76import java.io.ObjectInputStream;77import java.io.Serializable;78import java.time.format.DateTimeFormatter;79import java.time.format.DateTimeParseException;80import java.time.temporal.ChronoField;81import java.time.temporal.ChronoUnit;82import java.time.temporal.Temporal;83import java.time.temporal.TemporalAccessor;84import java.time.temporal.TemporalAdjuster;85import java.time.temporal.TemporalAmount;86import java.time.temporal.TemporalField;87import java.time.temporal.TemporalQueries;88import java.time.temporal.TemporalQuery;89import java.time.temporal.TemporalUnit;90import java.time.temporal.UnsupportedTemporalTypeException;91import java.time.temporal.ValueRange;92import java.util.Objects;9394/**95* A time without a 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* This class 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 information106* such as an offset or time-zone.107* <p>108* The ISO-8601 calendar system is the modern civil calendar system used today109* in most of the world. This API assumes that all calendar systems use the same110* representation, this class, for time-of-day.111*112* <p>113* This is a <a href="{@docRoot}/java/lang/doc-files/ValueBased.html">value-based</a>114* class; use of identity-sensitive operations (including reference equality115* ({@code ==}), identity hash code, or synchronization) on instances of116* {@code LocalTime} may have unpredictable results and should be avoided.117* The {@code equals} method should be used for comparisons.118*119* @implSpec120* This class is immutable and thread-safe.121*122* @since 1.8123*/124public final class LocalTime125implements Temporal, TemporalAdjuster, Comparable<LocalTime>, Serializable {126127/**128* The minimum supported {@code LocalTime}, '00:00'.129* This is the time of midnight at the start of the day.130*/131public static final LocalTime MIN;132/**133* The maximum supported {@code LocalTime}, '23:59:59.999999999'.134* This is the time just before midnight at the end of the day.135*/136public static final LocalTime MAX;137/**138* The time of midnight at the start of the day, '00:00'.139*/140public static final LocalTime MIDNIGHT;141/**142* The time of noon in the middle of the day, '12:00'.143*/144public static final LocalTime NOON;145/**146* Constants for the local time of each hour.147*/148private static final LocalTime[] HOURS = new LocalTime[24];149static {150for (int i = 0; i < HOURS.length; i++) {151HOURS[i] = new LocalTime(i, 0, 0, 0);152}153MIDNIGHT = HOURS[0];154NOON = HOURS[12];155MIN = HOURS[0];156MAX = new LocalTime(23, 59, 59, 999_999_999);157}158159/**160* Hours per day.161*/162static final int HOURS_PER_DAY = 24;163/**164* Minutes per hour.165*/166static final int MINUTES_PER_HOUR = 60;167/**168* Minutes per day.169*/170static final int MINUTES_PER_DAY = MINUTES_PER_HOUR * HOURS_PER_DAY;171/**172* Seconds per minute.173*/174static final int SECONDS_PER_MINUTE = 60;175/**176* Seconds per hour.177*/178static final int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR;179/**180* Seconds per day.181*/182static final int SECONDS_PER_DAY = SECONDS_PER_HOUR * HOURS_PER_DAY;183/**184* Milliseconds per day.185*/186static final long MILLIS_PER_DAY = SECONDS_PER_DAY * 1000L;187/**188* Microseconds per day.189*/190static final long MICROS_PER_DAY = SECONDS_PER_DAY * 1000_000L;191/**192* Nanos per second.193*/194static final long NANOS_PER_SECOND = 1000_000_000L;195/**196* Nanos per minute.197*/198static final long NANOS_PER_MINUTE = NANOS_PER_SECOND * SECONDS_PER_MINUTE;199/**200* Nanos per hour.201*/202static final long NANOS_PER_HOUR = NANOS_PER_MINUTE * MINUTES_PER_HOUR;203/**204* Nanos per day.205*/206static final long NANOS_PER_DAY = NANOS_PER_HOUR * HOURS_PER_DAY;207208/**209* Serialization version.210*/211private static final long serialVersionUID = 6414437269572265201L;212213/**214* The hour.215*/216private final byte hour;217/**218* The minute.219*/220private final byte minute;221/**222* The second.223*/224private final byte second;225/**226* The nanosecond.227*/228private final int nano;229230//-----------------------------------------------------------------------231/**232* Obtains the current time from the system clock in the default time-zone.233* <p>234* This will query the {@link Clock#systemDefaultZone() system clock} in the default235* time-zone to obtain the current time.236* <p>237* Using this method will prevent the ability to use an alternate clock for testing238* because the clock is hard-coded.239*240* @return the current time using the system clock and default time-zone, not null241*/242public static LocalTime now() {243return now(Clock.systemDefaultZone());244}245246/**247* Obtains the current time from the system clock in the specified time-zone.248* <p>249* This will query the {@link Clock#system(ZoneId) system clock} to obtain the current time.250* Specifying the time-zone avoids dependence on the default time-zone.251* <p>252* Using this method will prevent the ability to use an alternate clock for testing253* because the clock is hard-coded.254*255* @param zone the zone ID to use, not null256* @return the current time using the system clock, not null257*/258public static LocalTime now(ZoneId zone) {259return now(Clock.system(zone));260}261262/**263* Obtains the current time from the specified clock.264* <p>265* This will query the specified clock to obtain the current time.266* Using this method allows the use of an alternate clock for testing.267* The alternate clock may be introduced using {@link Clock dependency injection}.268*269* @param clock the clock to use, not null270* @return the current time, not null271*/272public static LocalTime now(Clock clock) {273Objects.requireNonNull(clock, "clock");274// inline OffsetTime factory to avoid creating object and InstantProvider checks275final Instant now = clock.instant(); // called once276ZoneOffset offset = clock.getZone().getRules().getOffset(now);277long localSecond = now.getEpochSecond() + offset.getTotalSeconds(); // overflow caught later278int secsOfDay = (int) Math.floorMod(localSecond, SECONDS_PER_DAY);279return ofNanoOfDay(secsOfDay * NANOS_PER_SECOND + now.getNano());280}281282//-----------------------------------------------------------------------283/**284* Obtains an instance of {@code LocalTime} from an hour and minute.285* <p>286* This returns a {@code LocalTime} with the specified hour and minute.287* The second and nanosecond fields will be set to zero.288*289* @param hour the hour-of-day to represent, from 0 to 23290* @param minute the minute-of-hour to represent, from 0 to 59291* @return the local time, not null292* @throws DateTimeException if the value of any field is out of range293*/294public static LocalTime of(int hour, int minute) {295HOUR_OF_DAY.checkValidValue(hour);296if (minute == 0) {297return HOURS[hour]; // for performance298}299MINUTE_OF_HOUR.checkValidValue(minute);300return new LocalTime(hour, minute, 0, 0);301}302303/**304* Obtains an instance of {@code LocalTime} from an hour, minute and second.305* <p>306* This returns a {@code LocalTime} with the specified hour, minute and second.307* The nanosecond field will be set to zero.308*309* @param hour the hour-of-day to represent, from 0 to 23310* @param minute the minute-of-hour to represent, from 0 to 59311* @param second the second-of-minute to represent, from 0 to 59312* @return the local time, not null313* @throws DateTimeException if the value of any field is out of range314*/315public static LocalTime of(int hour, int minute, int second) {316HOUR_OF_DAY.checkValidValue(hour);317if ((minute | second) == 0) {318return HOURS[hour]; // for performance319}320MINUTE_OF_HOUR.checkValidValue(minute);321SECOND_OF_MINUTE.checkValidValue(second);322return new LocalTime(hour, minute, second, 0);323}324325/**326* Obtains an instance of {@code LocalTime} from an hour, minute, second and nanosecond.327* <p>328* This returns a {@code LocalTime} with the specified hour, minute, second and nanosecond.329*330* @param hour the hour-of-day to represent, from 0 to 23331* @param minute the minute-of-hour to represent, from 0 to 59332* @param second the second-of-minute to represent, from 0 to 59333* @param nanoOfSecond the nano-of-second to represent, from 0 to 999,999,999334* @return the local time, not null335* @throws DateTimeException if the value of any field is out of range336*/337public static LocalTime of(int hour, int minute, int second, int nanoOfSecond) {338HOUR_OF_DAY.checkValidValue(hour);339MINUTE_OF_HOUR.checkValidValue(minute);340SECOND_OF_MINUTE.checkValidValue(second);341NANO_OF_SECOND.checkValidValue(nanoOfSecond);342return create(hour, minute, second, nanoOfSecond);343}344345//-----------------------------------------------------------------------346/**347* Obtains an instance of {@code LocalTime} from a second-of-day value.348* <p>349* This returns a {@code LocalTime} with the specified second-of-day.350* The nanosecond field will be set to zero.351*352* @param secondOfDay the second-of-day, from {@code 0} to {@code 24 * 60 * 60 - 1}353* @return the local time, not null354* @throws DateTimeException if the second-of-day value is invalid355*/356public static LocalTime ofSecondOfDay(long secondOfDay) {357SECOND_OF_DAY.checkValidValue(secondOfDay);358int hours = (int) (secondOfDay / SECONDS_PER_HOUR);359secondOfDay -= hours * SECONDS_PER_HOUR;360int minutes = (int) (secondOfDay / SECONDS_PER_MINUTE);361secondOfDay -= minutes * SECONDS_PER_MINUTE;362return create(hours, minutes, (int) secondOfDay, 0);363}364365/**366* Obtains an instance of {@code LocalTime} from a nanos-of-day value.367* <p>368* This returns a {@code LocalTime} with the specified nanosecond-of-day.369*370* @param nanoOfDay the nano of day, from {@code 0} to {@code 24 * 60 * 60 * 1,000,000,000 - 1}371* @return the local time, not null372* @throws DateTimeException if the nanos of day value is invalid373*/374public static LocalTime ofNanoOfDay(long nanoOfDay) {375NANO_OF_DAY.checkValidValue(nanoOfDay);376int hours = (int) (nanoOfDay / NANOS_PER_HOUR);377nanoOfDay -= hours * NANOS_PER_HOUR;378int minutes = (int) (nanoOfDay / NANOS_PER_MINUTE);379nanoOfDay -= minutes * NANOS_PER_MINUTE;380int seconds = (int) (nanoOfDay / NANOS_PER_SECOND);381nanoOfDay -= seconds * NANOS_PER_SECOND;382return create(hours, minutes, seconds, (int) nanoOfDay);383}384385//-----------------------------------------------------------------------386/**387* Obtains an instance of {@code LocalTime} from a temporal object.388* <p>389* This obtains a local time based on the specified temporal.390* A {@code TemporalAccessor} represents an arbitrary set of date and time information,391* which this factory converts to an instance of {@code LocalTime}.392* <p>393* The conversion uses the {@link TemporalQueries#localTime()} query, which relies394* on extracting the {@link ChronoField#NANO_OF_DAY NANO_OF_DAY} field.395* <p>396* This method matches the signature of the functional interface {@link TemporalQuery}397* allowing it to be used as a query via method reference, {@code LocalTime::from}.398*399* @param temporal the temporal object to convert, not null400* @return the local time, not null401* @throws DateTimeException if unable to convert to a {@code LocalTime}402*/403public static LocalTime from(TemporalAccessor temporal) {404Objects.requireNonNull(temporal, "temporal");405LocalTime time = temporal.query(TemporalQueries.localTime());406if (time == null) {407throw new DateTimeException("Unable to obtain LocalTime from TemporalAccessor: " +408temporal + " of type " + temporal.getClass().getName());409}410return time;411}412413//-----------------------------------------------------------------------414/**415* Obtains an instance of {@code LocalTime} from a text string such as {@code 10:15}.416* <p>417* The string must represent a valid time and is parsed using418* {@link java.time.format.DateTimeFormatter#ISO_LOCAL_TIME}.419*420* @param text the text to parse such as "10:15:30", not null421* @return the parsed local time, not null422* @throws DateTimeParseException if the text cannot be parsed423*/424public static LocalTime parse(CharSequence text) {425return parse(text, DateTimeFormatter.ISO_LOCAL_TIME);426}427428/**429* Obtains an instance of {@code LocalTime} from a text string using a specific formatter.430* <p>431* The text is parsed using the formatter, returning a time.432*433* @param text the text to parse, not null434* @param formatter the formatter to use, not null435* @return the parsed local time, not null436* @throws DateTimeParseException if the text cannot be parsed437*/438public static LocalTime parse(CharSequence text, DateTimeFormatter formatter) {439Objects.requireNonNull(formatter, "formatter");440return formatter.parse(text, LocalTime::from);441}442443//-----------------------------------------------------------------------444/**445* Creates a local time from the hour, minute, second and nanosecond fields.446* <p>447* This factory may return a cached value, but applications must not rely on this.448*449* @param hour the hour-of-day to represent, validated from 0 to 23450* @param minute the minute-of-hour to represent, validated from 0 to 59451* @param second the second-of-minute to represent, validated from 0 to 59452* @param nanoOfSecond the nano-of-second to represent, validated from 0 to 999,999,999453* @return the local time, not null454*/455private static LocalTime create(int hour, int minute, int second, int nanoOfSecond) {456if ((minute | second | nanoOfSecond) == 0) {457return HOURS[hour];458}459return new LocalTime(hour, minute, second, nanoOfSecond);460}461462/**463* Constructor, previously validated.464*465* @param hour the hour-of-day to represent, validated from 0 to 23466* @param minute the minute-of-hour to represent, validated from 0 to 59467* @param second the second-of-minute to represent, validated from 0 to 59468* @param nanoOfSecond the nano-of-second to represent, validated from 0 to 999,999,999469*/470private LocalTime(int hour, int minute, int second, int nanoOfSecond) {471this.hour = (byte) hour;472this.minute = (byte) minute;473this.second = (byte) second;474this.nano = nanoOfSecond;475}476477//-----------------------------------------------------------------------478/**479* Checks if the specified field is supported.480* <p>481* This checks if this time can be queried for the specified field.482* If false, then calling the {@link #range(TemporalField) range},483* {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}484* methods will throw an exception.485* <p>486* If the field is a {@link ChronoField} then the query is implemented here.487* The supported fields are:488* <ul>489* <li>{@code NANO_OF_SECOND}490* <li>{@code NANO_OF_DAY}491* <li>{@code MICRO_OF_SECOND}492* <li>{@code MICRO_OF_DAY}493* <li>{@code MILLI_OF_SECOND}494* <li>{@code MILLI_OF_DAY}495* <li>{@code SECOND_OF_MINUTE}496* <li>{@code SECOND_OF_DAY}497* <li>{@code MINUTE_OF_HOUR}498* <li>{@code MINUTE_OF_DAY}499* <li>{@code HOUR_OF_AMPM}500* <li>{@code CLOCK_HOUR_OF_AMPM}501* <li>{@code HOUR_OF_DAY}502* <li>{@code CLOCK_HOUR_OF_DAY}503* <li>{@code AMPM_OF_DAY}504* </ul>505* All other {@code ChronoField} instances will return false.506* <p>507* If the field is not a {@code ChronoField}, then the result of this method508* is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}509* passing {@code this} as the argument.510* Whether the field is supported is determined by the field.511*512* @param field the field to check, null returns false513* @return true if the field is supported on this time, false if not514*/515@Override516public boolean isSupported(TemporalField field) {517if (field instanceof ChronoField) {518return field.isTimeBased();519}520return field != null && field.isSupportedBy(this);521}522523/**524* Checks if the specified unit is supported.525* <p>526* This checks if the specified unit can be added to, or subtracted from, this time.527* If false, then calling the {@link #plus(long, TemporalUnit)} and528* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.529* <p>530* If the unit is a {@link ChronoUnit} then the query is implemented here.531* The supported units are:532* <ul>533* <li>{@code NANOS}534* <li>{@code MICROS}535* <li>{@code MILLIS}536* <li>{@code SECONDS}537* <li>{@code MINUTES}538* <li>{@code HOURS}539* <li>{@code HALF_DAYS}540* </ul>541* All other {@code ChronoUnit} instances will return false.542* <p>543* If the unit is not a {@code ChronoUnit}, then the result of this method544* is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}545* passing {@code this} as the argument.546* Whether the unit is supported is determined by the unit.547*548* @param unit the unit to check, null returns false549* @return true if the unit can be added/subtracted, false if not550*/551@Override // override for Javadoc552public boolean isSupported(TemporalUnit unit) {553if (unit instanceof ChronoUnit) {554return unit.isTimeBased();555}556return unit != null && unit.isSupportedBy(this);557}558559//-----------------------------------------------------------------------560/**561* Gets the range of valid values for the specified field.562* <p>563* The range object expresses the minimum and maximum valid values for a field.564* This time is used to enhance the accuracy of the returned range.565* If it is not possible to return the range, because the field is not supported566* or for some other reason, an exception is thrown.567* <p>568* If the field is a {@link ChronoField} then the query is implemented here.569* The {@link #isSupported(TemporalField) supported fields} will return570* appropriate range instances.571* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.572* <p>573* If the field is not a {@code ChronoField}, then the result of this method574* is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}575* passing {@code this} as the argument.576* Whether the range can be obtained is determined by the field.577*578* @param field the field to query the range for, not null579* @return the range of valid values for the field, not null580* @throws DateTimeException if the range for the field cannot be obtained581* @throws UnsupportedTemporalTypeException if the field is not supported582*/583@Override // override for Javadoc584public ValueRange range(TemporalField field) {585return Temporal.super.range(field);586}587588/**589* Gets the value of the specified field from this time as an {@code int}.590* <p>591* This queries this time for the value of the specified field.592* The returned value will always be within the valid range of values for the field.593* If it is not possible to return the value, because the field is not supported594* or for some other reason, an exception is thrown.595* <p>596* If the field is a {@link ChronoField} then the query is implemented here.597* The {@link #isSupported(TemporalField) supported fields} will return valid598* values based on this time, except {@code NANO_OF_DAY} and {@code MICRO_OF_DAY}599* which are too large to fit in an {@code int} and throw a {@code DateTimeException}.600* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.601* <p>602* If the field is not a {@code ChronoField}, then the result of this method603* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}604* passing {@code this} as the argument. Whether the value can be obtained,605* and what the value represents, is determined by the field.606*607* @param field the field to get, not null608* @return the value for the field609* @throws DateTimeException if a value for the field cannot be obtained or610* the value is outside the range of valid values for the field611* @throws UnsupportedTemporalTypeException if the field is not supported or612* the range of values exceeds an {@code int}613* @throws ArithmeticException if numeric overflow occurs614*/615@Override // override for Javadoc and performance616public int get(TemporalField field) {617if (field instanceof ChronoField) {618return get0(field);619}620return Temporal.super.get(field);621}622623/**624* Gets the value of the specified field from this time as a {@code long}.625* <p>626* This queries this time for the value of the specified field.627* If it is not possible to return the value, because the field is not supported628* or for some other reason, an exception is thrown.629* <p>630* If the field is a {@link ChronoField} then the query is implemented here.631* The {@link #isSupported(TemporalField) supported fields} will return valid632* values based on this time.633* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.634* <p>635* If the field is not a {@code ChronoField}, then the result of this method636* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}637* passing {@code this} as the argument. Whether the value can be obtained,638* and what the value represents, is determined by the field.639*640* @param field the field to get, not null641* @return the value for the field642* @throws DateTimeException if a value for the field cannot be obtained643* @throws UnsupportedTemporalTypeException if the field is not supported644* @throws ArithmeticException if numeric overflow occurs645*/646@Override647public long getLong(TemporalField field) {648if (field instanceof ChronoField) {649if (field == NANO_OF_DAY) {650return toNanoOfDay();651}652if (field == MICRO_OF_DAY) {653return toNanoOfDay() / 1000;654}655return get0(field);656}657return field.getFrom(this);658}659660private int get0(TemporalField field) {661switch ((ChronoField) field) {662case NANO_OF_SECOND: return nano;663case NANO_OF_DAY: throw new UnsupportedTemporalTypeException("Invalid field 'NanoOfDay' for get() method, use getLong() instead");664case MICRO_OF_SECOND: return nano / 1000;665case MICRO_OF_DAY: throw new UnsupportedTemporalTypeException("Invalid field 'MicroOfDay' for get() method, use getLong() instead");666case MILLI_OF_SECOND: return nano / 1000_000;667case MILLI_OF_DAY: return (int) (toNanoOfDay() / 1000_000);668case SECOND_OF_MINUTE: return second;669case SECOND_OF_DAY: return toSecondOfDay();670case MINUTE_OF_HOUR: return minute;671case MINUTE_OF_DAY: return hour * 60 + minute;672case HOUR_OF_AMPM: return hour % 12;673case CLOCK_HOUR_OF_AMPM: int ham = hour % 12; return (ham % 12 == 0 ? 12 : ham);674case HOUR_OF_DAY: return hour;675case CLOCK_HOUR_OF_DAY: return (hour == 0 ? 24 : hour);676case AMPM_OF_DAY: return hour / 12;677}678throw new UnsupportedTemporalTypeException("Unsupported field: " + field);679}680681//-----------------------------------------------------------------------682/**683* Gets the hour-of-day field.684*685* @return the hour-of-day, from 0 to 23686*/687public int getHour() {688return hour;689}690691/**692* Gets the minute-of-hour field.693*694* @return the minute-of-hour, from 0 to 59695*/696public int getMinute() {697return minute;698}699700/**701* Gets the second-of-minute field.702*703* @return the second-of-minute, from 0 to 59704*/705public int getSecond() {706return second;707}708709/**710* Gets the nano-of-second field.711*712* @return the nano-of-second, from 0 to 999,999,999713*/714public int getNano() {715return nano;716}717718//-----------------------------------------------------------------------719/**720* Returns an adjusted copy of this time.721* <p>722* This returns a {@code LocalTime}, based on this one, with the time adjusted.723* The adjustment takes place using the specified adjuster strategy object.724* Read the documentation of the adjuster to understand what adjustment will be made.725* <p>726* A simple adjuster might simply set the one of the fields, such as the hour field.727* A more complex adjuster might set the time to the last hour of the day.728* <p>729* The result of this method is obtained by invoking the730* {@link TemporalAdjuster#adjustInto(Temporal)} method on the731* specified adjuster passing {@code this} as the argument.732* <p>733* This instance is immutable and unaffected by this method call.734*735* @param adjuster the adjuster to use, not null736* @return a {@code LocalTime} based on {@code this} with the adjustment made, not null737* @throws DateTimeException if the adjustment cannot be made738* @throws ArithmeticException if numeric overflow occurs739*/740@Override741public LocalTime with(TemporalAdjuster adjuster) {742// optimizations743if (adjuster instanceof LocalTime) {744return (LocalTime) adjuster;745}746return (LocalTime) adjuster.adjustInto(this);747}748749/**750* Returns a copy of this time with the specified field set to a new value.751* <p>752* This returns a {@code LocalTime}, based on this one, with the value753* for the specified field changed.754* This can be used to change any supported field, such as the hour, minute or second.755* If it is not possible to set the value, because the field is not supported or for756* some other reason, an exception is thrown.757* <p>758* If the field is a {@link ChronoField} then the adjustment is implemented here.759* The supported fields behave as follows:760* <ul>761* <li>{@code NANO_OF_SECOND} -762* Returns a {@code LocalTime} with the specified nano-of-second.763* The hour, minute and second will be unchanged.764* <li>{@code NANO_OF_DAY} -765* Returns a {@code LocalTime} with the specified nano-of-day.766* This completely replaces the time and is equivalent to {@link #ofNanoOfDay(long)}.767* <li>{@code MICRO_OF_SECOND} -768* Returns a {@code LocalTime} with the nano-of-second replaced by the specified769* micro-of-second multiplied by 1,000.770* The hour, minute and second will be unchanged.771* <li>{@code MICRO_OF_DAY} -772* Returns a {@code LocalTime} with the specified micro-of-day.773* This completely replaces the time and is equivalent to using {@link #ofNanoOfDay(long)}774* with the micro-of-day multiplied by 1,000.775* <li>{@code MILLI_OF_SECOND} -776* Returns a {@code LocalTime} with the nano-of-second replaced by the specified777* milli-of-second multiplied by 1,000,000.778* The hour, minute and second will be unchanged.779* <li>{@code MILLI_OF_DAY} -780* Returns a {@code LocalTime} with the specified milli-of-day.781* This completely replaces the time and is equivalent to using {@link #ofNanoOfDay(long)}782* with the milli-of-day multiplied by 1,000,000.783* <li>{@code SECOND_OF_MINUTE} -784* Returns a {@code LocalTime} with the specified second-of-minute.785* The hour, minute and nano-of-second will be unchanged.786* <li>{@code SECOND_OF_DAY} -787* Returns a {@code LocalTime} with the specified second-of-day.788* The nano-of-second will be unchanged.789* <li>{@code MINUTE_OF_HOUR} -790* Returns a {@code LocalTime} with the specified minute-of-hour.791* The hour, second-of-minute and nano-of-second will be unchanged.792* <li>{@code MINUTE_OF_DAY} -793* Returns a {@code LocalTime} with the specified minute-of-day.794* The second-of-minute and nano-of-second will be unchanged.795* <li>{@code HOUR_OF_AMPM} -796* Returns a {@code LocalTime} with the specified hour-of-am-pm.797* The AM/PM, minute-of-hour, second-of-minute and nano-of-second will be unchanged.798* <li>{@code CLOCK_HOUR_OF_AMPM} -799* Returns a {@code LocalTime} with the specified clock-hour-of-am-pm.800* The AM/PM, minute-of-hour, second-of-minute and nano-of-second will be unchanged.801* <li>{@code HOUR_OF_DAY} -802* Returns a {@code LocalTime} with the specified hour-of-day.803* The minute-of-hour, second-of-minute and nano-of-second will be unchanged.804* <li>{@code CLOCK_HOUR_OF_DAY} -805* Returns a {@code LocalTime} with the specified clock-hour-of-day.806* The minute-of-hour, second-of-minute and nano-of-second will be unchanged.807* <li>{@code AMPM_OF_DAY} -808* Returns a {@code LocalTime} with the specified AM/PM.809* The hour-of-am-pm, minute-of-hour, second-of-minute and nano-of-second will be unchanged.810* </ul>811* <p>812* In all cases, if the new value is outside the valid range of values for the field813* then a {@code DateTimeException} will be thrown.814* <p>815* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.816* <p>817* If the field is not a {@code ChronoField}, then the result of this method818* is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}819* passing {@code this} as the argument. In this case, the field determines820* whether and how to adjust the instant.821* <p>822* This instance is immutable and unaffected by this method call.823*824* @param field the field to set in the result, not null825* @param newValue the new value of the field in the result826* @return a {@code LocalTime} based on {@code this} with the specified field set, not null827* @throws DateTimeException if the field cannot be set828* @throws UnsupportedTemporalTypeException if the field is not supported829* @throws ArithmeticException if numeric overflow occurs830*/831@Override832public LocalTime with(TemporalField field, long newValue) {833if (field instanceof ChronoField) {834ChronoField f = (ChronoField) field;835f.checkValidValue(newValue);836switch (f) {837case NANO_OF_SECOND: return withNano((int) newValue);838case NANO_OF_DAY: return LocalTime.ofNanoOfDay(newValue);839case MICRO_OF_SECOND: return withNano((int) newValue * 1000);840case MICRO_OF_DAY: return LocalTime.ofNanoOfDay(newValue * 1000);841case MILLI_OF_SECOND: return withNano((int) newValue * 1000_000);842case MILLI_OF_DAY: return LocalTime.ofNanoOfDay(newValue * 1000_000);843case SECOND_OF_MINUTE: return withSecond((int) newValue);844case SECOND_OF_DAY: return plusSeconds(newValue - toSecondOfDay());845case MINUTE_OF_HOUR: return withMinute((int) newValue);846case MINUTE_OF_DAY: return plusMinutes(newValue - (hour * 60 + minute));847case HOUR_OF_AMPM: return plusHours(newValue - (hour % 12));848case CLOCK_HOUR_OF_AMPM: return plusHours((newValue == 12 ? 0 : newValue) - (hour % 12));849case HOUR_OF_DAY: return withHour((int) newValue);850case CLOCK_HOUR_OF_DAY: return withHour((int) (newValue == 24 ? 0 : newValue));851case AMPM_OF_DAY: return plusHours((newValue - (hour / 12)) * 12);852}853throw new UnsupportedTemporalTypeException("Unsupported field: " + field);854}855return field.adjustInto(this, newValue);856}857858//-----------------------------------------------------------------------859/**860* Returns a copy of this {@code LocalTime} with the hour-of-day altered.861* <p>862* This instance is immutable and unaffected by this method call.863*864* @param hour the hour-of-day to set in the result, from 0 to 23865* @return a {@code LocalTime} based on this time with the requested hour, not null866* @throws DateTimeException if the hour value is invalid867*/868public LocalTime withHour(int hour) {869if (this.hour == hour) {870return this;871}872HOUR_OF_DAY.checkValidValue(hour);873return create(hour, minute, second, nano);874}875876/**877* Returns a copy of this {@code LocalTime} with the minute-of-hour altered.878* <p>879* This instance is immutable and unaffected by this method call.880*881* @param minute the minute-of-hour to set in the result, from 0 to 59882* @return a {@code LocalTime} based on this time with the requested minute, not null883* @throws DateTimeException if the minute value is invalid884*/885public LocalTime withMinute(int minute) {886if (this.minute == minute) {887return this;888}889MINUTE_OF_HOUR.checkValidValue(minute);890return create(hour, minute, second, nano);891}892893/**894* Returns a copy of this {@code LocalTime} with the second-of-minute altered.895* <p>896* This instance is immutable and unaffected by this method call.897*898* @param second the second-of-minute to set in the result, from 0 to 59899* @return a {@code LocalTime} based on this time with the requested second, not null900* @throws DateTimeException if the second value is invalid901*/902public LocalTime withSecond(int second) {903if (this.second == second) {904return this;905}906SECOND_OF_MINUTE.checkValidValue(second);907return create(hour, minute, second, nano);908}909910/**911* Returns a copy of this {@code LocalTime} with the nano-of-second altered.912* <p>913* This instance is immutable and unaffected by this method call.914*915* @param nanoOfSecond the nano-of-second to set in the result, from 0 to 999,999,999916* @return a {@code LocalTime} based on this time with the requested nanosecond, not null917* @throws DateTimeException if the nanos value is invalid918*/919public LocalTime withNano(int nanoOfSecond) {920if (this.nano == nanoOfSecond) {921return this;922}923NANO_OF_SECOND.checkValidValue(nanoOfSecond);924return create(hour, minute, second, nanoOfSecond);925}926927//-----------------------------------------------------------------------928/**929* Returns a copy of this {@code LocalTime} with the time truncated.930* <p>931* Truncation returns a copy of the original time with fields932* smaller than the specified unit set to zero.933* For example, truncating with the {@link ChronoUnit#MINUTES minutes} unit934* will set the second-of-minute and nano-of-second field to zero.935* <p>936* The unit must have a {@linkplain TemporalUnit#getDuration() duration}937* that divides into the length of a standard day without remainder.938* This includes all supplied time units on {@link ChronoUnit} and939* {@link ChronoUnit#DAYS DAYS}. Other units throw an exception.940* <p>941* This instance is immutable and unaffected by this method call.942*943* @param unit the unit to truncate to, not null944* @return a {@code LocalTime} based on this time with the time truncated, not null945* @throws DateTimeException if unable to truncate946* @throws UnsupportedTemporalTypeException if the unit is not supported947*/948public LocalTime truncatedTo(TemporalUnit unit) {949if (unit == ChronoUnit.NANOS) {950return this;951}952Duration unitDur = unit.getDuration();953if (unitDur.getSeconds() > SECONDS_PER_DAY) {954throw new UnsupportedTemporalTypeException("Unit is too large to be used for truncation");955}956long dur = unitDur.toNanos();957if ((NANOS_PER_DAY % dur) != 0) {958throw new UnsupportedTemporalTypeException("Unit must divide into a standard day without remainder");959}960long nod = toNanoOfDay();961return ofNanoOfDay((nod / dur) * dur);962}963964//-----------------------------------------------------------------------965/**966* Returns a copy of this time with the specified amount added.967* <p>968* This returns a {@code LocalTime}, based on this one, with the specified amount added.969* The amount is typically {@link Duration} but may be any other type implementing970* the {@link TemporalAmount} interface.971* <p>972* The calculation is delegated to the amount object by calling973* {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free974* to implement the addition in any way it wishes, however it typically975* calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation976* of the amount implementation to determine if it can be successfully added.977* <p>978* This instance is immutable and unaffected by this method call.979*980* @param amountToAdd the amount to add, not null981* @return a {@code LocalTime} based on this time with the addition made, not null982* @throws DateTimeException if the addition cannot be made983* @throws ArithmeticException if numeric overflow occurs984*/985@Override986public LocalTime plus(TemporalAmount amountToAdd) {987return (LocalTime) amountToAdd.addTo(this);988}989990/**991* Returns a copy of this time with the specified amount added.992* <p>993* This returns a {@code LocalTime}, based on this one, with the amount994* in terms of the unit added. If it is not possible to add the amount, because the995* unit is not supported or for some other reason, an exception is thrown.996* <p>997* If the field is a {@link ChronoUnit} then the addition is implemented here.998* The supported fields behave as follows:999* <ul>1000* <li>{@code NANOS} -1001* Returns a {@code LocalTime} with the specified number of nanoseconds added.1002* This is equivalent to {@link #plusNanos(long)}.1003* <li>{@code MICROS} -1004* Returns a {@code LocalTime} with the specified number of microseconds added.1005* This is equivalent to {@link #plusNanos(long)} with the amount1006* multiplied by 1,000.1007* <li>{@code MILLIS} -1008* Returns a {@code LocalTime} with the specified number of milliseconds added.1009* This is equivalent to {@link #plusNanos(long)} with the amount1010* multiplied by 1,000,000.1011* <li>{@code SECONDS} -1012* Returns a {@code LocalTime} with the specified number of seconds added.1013* This is equivalent to {@link #plusSeconds(long)}.1014* <li>{@code MINUTES} -1015* Returns a {@code LocalTime} with the specified number of minutes added.1016* This is equivalent to {@link #plusMinutes(long)}.1017* <li>{@code HOURS} -1018* Returns a {@code LocalTime} with the specified number of hours added.1019* This is equivalent to {@link #plusHours(long)}.1020* <li>{@code HALF_DAYS} -1021* Returns a {@code LocalTime} with the specified number of half-days added.1022* This is equivalent to {@link #plusHours(long)} with the amount1023* multiplied by 12.1024* </ul>1025* <p>1026* All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}.1027* <p>1028* If the field is not a {@code ChronoUnit}, then the result of this method1029* is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}1030* passing {@code this} as the argument. In this case, the unit determines1031* whether and how to perform the addition.1032* <p>1033* This instance is immutable and unaffected by this method call.1034*1035* @param amountToAdd the amount of the unit to add to the result, may be negative1036* @param unit the unit of the amount to add, not null1037* @return a {@code LocalTime} based on this time with the specified amount added, not null1038* @throws DateTimeException if the addition cannot be made1039* @throws UnsupportedTemporalTypeException if the unit is not supported1040* @throws ArithmeticException if numeric overflow occurs1041*/1042@Override1043public LocalTime plus(long amountToAdd, TemporalUnit unit) {1044if (unit instanceof ChronoUnit) {1045switch ((ChronoUnit) unit) {1046case NANOS: return plusNanos(amountToAdd);1047case MICROS: return plusNanos((amountToAdd % MICROS_PER_DAY) * 1000);1048case MILLIS: return plusNanos((amountToAdd % MILLIS_PER_DAY) * 1000_000);1049case SECONDS: return plusSeconds(amountToAdd);1050case MINUTES: return plusMinutes(amountToAdd);1051case HOURS: return plusHours(amountToAdd);1052case HALF_DAYS: return plusHours((amountToAdd % 2) * 12);1053}1054throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);1055}1056return unit.addTo(this, amountToAdd);1057}10581059//-----------------------------------------------------------------------1060/**1061* Returns a copy of this {@code LocalTime} with the specified number of hours added.1062* <p>1063* This adds the specified number of hours to this time, returning a new time.1064* The calculation wraps around midnight.1065* <p>1066* This instance is immutable and unaffected by this method call.1067*1068* @param hoursToAdd the hours to add, may be negative1069* @return a {@code LocalTime} based on this time with the hours added, not null1070*/1071public LocalTime plusHours(long hoursToAdd) {1072if (hoursToAdd == 0) {1073return this;1074}1075int newHour = ((int) (hoursToAdd % HOURS_PER_DAY) + hour + HOURS_PER_DAY) % HOURS_PER_DAY;1076return create(newHour, minute, second, nano);1077}10781079/**1080* Returns a copy of this {@code LocalTime} with the specified number of minutes added.1081* <p>1082* This adds the specified number of minutes to this time, returning a new time.1083* The calculation wraps around midnight.1084* <p>1085* This instance is immutable and unaffected by this method call.1086*1087* @param minutesToAdd the minutes to add, may be negative1088* @return a {@code LocalTime} based on this time with the minutes added, not null1089*/1090public LocalTime plusMinutes(long minutesToAdd) {1091if (minutesToAdd == 0) {1092return this;1093}1094int mofd = hour * MINUTES_PER_HOUR + minute;1095int newMofd = ((int) (minutesToAdd % MINUTES_PER_DAY) + mofd + MINUTES_PER_DAY) % MINUTES_PER_DAY;1096if (mofd == newMofd) {1097return this;1098}1099int newHour = newMofd / MINUTES_PER_HOUR;1100int newMinute = newMofd % MINUTES_PER_HOUR;1101return create(newHour, newMinute, second, nano);1102}11031104/**1105* Returns a copy of this {@code LocalTime} with the specified number of seconds added.1106* <p>1107* This adds the specified number of seconds to this time, returning a new time.1108* The calculation wraps around midnight.1109* <p>1110* This instance is immutable and unaffected by this method call.1111*1112* @param secondstoAdd the seconds to add, may be negative1113* @return a {@code LocalTime} based on this time with the seconds added, not null1114*/1115public LocalTime plusSeconds(long secondstoAdd) {1116if (secondstoAdd == 0) {1117return this;1118}1119int sofd = hour * SECONDS_PER_HOUR +1120minute * SECONDS_PER_MINUTE + second;1121int newSofd = ((int) (secondstoAdd % SECONDS_PER_DAY) + sofd + SECONDS_PER_DAY) % SECONDS_PER_DAY;1122if (sofd == newSofd) {1123return this;1124}1125int newHour = newSofd / SECONDS_PER_HOUR;1126int newMinute = (newSofd / SECONDS_PER_MINUTE) % MINUTES_PER_HOUR;1127int newSecond = newSofd % SECONDS_PER_MINUTE;1128return create(newHour, newMinute, newSecond, nano);1129}11301131/**1132* Returns a copy of this {@code LocalTime} with the specified number of nanoseconds added.1133* <p>1134* This adds the specified number of nanoseconds to this time, returning a new time.1135* The calculation wraps around midnight.1136* <p>1137* This instance is immutable and unaffected by this method call.1138*1139* @param nanosToAdd the nanos to add, may be negative1140* @return a {@code LocalTime} based on this time with the nanoseconds added, not null1141*/1142public LocalTime plusNanos(long nanosToAdd) {1143if (nanosToAdd == 0) {1144return this;1145}1146long nofd = toNanoOfDay();1147long newNofd = ((nanosToAdd % NANOS_PER_DAY) + nofd + NANOS_PER_DAY) % NANOS_PER_DAY;1148if (nofd == newNofd) {1149return this;1150}1151int newHour = (int) (newNofd / NANOS_PER_HOUR);1152int newMinute = (int) ((newNofd / NANOS_PER_MINUTE) % MINUTES_PER_HOUR);1153int newSecond = (int) ((newNofd / NANOS_PER_SECOND) % SECONDS_PER_MINUTE);1154int newNano = (int) (newNofd % NANOS_PER_SECOND);1155return create(newHour, newMinute, newSecond, newNano);1156}11571158//-----------------------------------------------------------------------1159/**1160* Returns a copy of this time with the specified amount subtracted.1161* <p>1162* This returns a {@code LocalTime}, based on this one, with the specified amount subtracted.1163* The amount is typically {@link Duration} but may be any other type implementing1164* the {@link TemporalAmount} interface.1165* <p>1166* The calculation is delegated to the amount object by calling1167* {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free1168* to implement the subtraction in any way it wishes, however it typically1169* calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation1170* of the amount implementation to determine if it can be successfully subtracted.1171* <p>1172* This instance is immutable and unaffected by this method call.1173*1174* @param amountToSubtract the amount to subtract, not null1175* @return a {@code LocalTime} based on this time with the subtraction made, not null1176* @throws DateTimeException if the subtraction cannot be made1177* @throws ArithmeticException if numeric overflow occurs1178*/1179@Override1180public LocalTime minus(TemporalAmount amountToSubtract) {1181return (LocalTime) amountToSubtract.subtractFrom(this);1182}11831184/**1185* Returns a copy of this time with the specified amount subtracted.1186* <p>1187* This returns a {@code LocalTime}, based on this one, with the amount1188* in terms of the unit subtracted. If it is not possible to subtract the amount,1189* because the unit is not supported or for some other reason, an exception is thrown.1190* <p>1191* This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.1192* See that method for a full description of how addition, and thus subtraction, works.1193* <p>1194* This instance is immutable and unaffected by this method call.1195*1196* @param amountToSubtract the amount of the unit to subtract from the result, may be negative1197* @param unit the unit of the amount to subtract, not null1198* @return a {@code LocalTime} based on this time with the specified amount subtracted, not null1199* @throws DateTimeException if the subtraction cannot be made1200* @throws UnsupportedTemporalTypeException if the unit is not supported1201* @throws ArithmeticException if numeric overflow occurs1202*/1203@Override1204public LocalTime minus(long amountToSubtract, TemporalUnit unit) {1205return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));1206}12071208//-----------------------------------------------------------------------1209/**1210* Returns a copy of this {@code LocalTime} with the specified number of hours subtracted.1211* <p>1212* This subtracts the specified number of hours from this time, returning a new time.1213* The calculation wraps around midnight.1214* <p>1215* This instance is immutable and unaffected by this method call.1216*1217* @param hoursToSubtract the hours to subtract, may be negative1218* @return a {@code LocalTime} based on this time with the hours subtracted, not null1219*/1220public LocalTime minusHours(long hoursToSubtract) {1221return plusHours(-(hoursToSubtract % HOURS_PER_DAY));1222}12231224/**1225* Returns a copy of this {@code LocalTime} with the specified number of minutes subtracted.1226* <p>1227* This subtracts the specified number of minutes from this time, returning a new time.1228* The calculation wraps around midnight.1229* <p>1230* This instance is immutable and unaffected by this method call.1231*1232* @param minutesToSubtract the minutes to subtract, may be negative1233* @return a {@code LocalTime} based on this time with the minutes subtracted, not null1234*/1235public LocalTime minusMinutes(long minutesToSubtract) {1236return plusMinutes(-(minutesToSubtract % MINUTES_PER_DAY));1237}12381239/**1240* Returns a copy of this {@code LocalTime} with the specified number of seconds subtracted.1241* <p>1242* This subtracts the specified number of seconds from this time, returning a new time.1243* The calculation wraps around midnight.1244* <p>1245* This instance is immutable and unaffected by this method call.1246*1247* @param secondsToSubtract the seconds to subtract, may be negative1248* @return a {@code LocalTime} based on this time with the seconds subtracted, not null1249*/1250public LocalTime minusSeconds(long secondsToSubtract) {1251return plusSeconds(-(secondsToSubtract % SECONDS_PER_DAY));1252}12531254/**1255* Returns a copy of this {@code LocalTime} with the specified number of nanoseconds subtracted.1256* <p>1257* This subtracts the specified number of nanoseconds from this time, returning a new time.1258* The calculation wraps around midnight.1259* <p>1260* This instance is immutable and unaffected by this method call.1261*1262* @param nanosToSubtract the nanos to subtract, may be negative1263* @return a {@code LocalTime} based on this time with the nanoseconds subtracted, not null1264*/1265public LocalTime minusNanos(long nanosToSubtract) {1266return plusNanos(-(nanosToSubtract % NANOS_PER_DAY));1267}12681269//-----------------------------------------------------------------------1270/**1271* Queries this time using the specified query.1272* <p>1273* This queries this time using the specified query strategy object.1274* The {@code TemporalQuery} object defines the logic to be used to1275* obtain the result. Read the documentation of the query to understand1276* what the result of this method will be.1277* <p>1278* The result of this method is obtained by invoking the1279* {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the1280* specified query passing {@code this} as the argument.1281*1282* @param <R> the type of the result1283* @param query the query to invoke, not null1284* @return the query result, null may be returned (defined by the query)1285* @throws DateTimeException if unable to query (defined by the query)1286* @throws ArithmeticException if numeric overflow occurs (defined by the query)1287*/1288@SuppressWarnings("unchecked")1289@Override1290public <R> R query(TemporalQuery<R> query) {1291if (query == TemporalQueries.chronology() || query == TemporalQueries.zoneId() ||1292query == TemporalQueries.zone() || query == TemporalQueries.offset()) {1293return null;1294} else if (query == TemporalQueries.localTime()) {1295return (R) this;1296} else if (query == TemporalQueries.localDate()) {1297return null;1298} else if (query == TemporalQueries.precision()) {1299return (R) NANOS;1300}1301// inline TemporalAccessor.super.query(query) as an optimization1302// non-JDK classes are not permitted to make this optimization1303return query.queryFrom(this);1304}13051306/**1307* Adjusts the specified temporal object to have the same time as this object.1308* <p>1309* This returns a temporal object of the same observable type as the input1310* with the time changed to be the same as this.1311* <p>1312* The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}1313* passing {@link ChronoField#NANO_OF_DAY} as the field.1314* <p>1315* In most cases, it is clearer to reverse the calling pattern by using1316* {@link Temporal#with(TemporalAdjuster)}:1317* <pre>1318* // these two lines are equivalent, but the second approach is recommended1319* temporal = thisLocalTime.adjustInto(temporal);1320* temporal = temporal.with(thisLocalTime);1321* </pre>1322* <p>1323* This instance is immutable and unaffected by this method call.1324*1325* @param temporal the target object to be adjusted, not null1326* @return the adjusted object, not null1327* @throws DateTimeException if unable to make the adjustment1328* @throws ArithmeticException if numeric overflow occurs1329*/1330@Override1331public Temporal adjustInto(Temporal temporal) {1332return temporal.with(NANO_OF_DAY, toNanoOfDay());1333}13341335/**1336* Calculates the amount of time until another time in terms of the specified unit.1337* <p>1338* This calculates the amount of time between two {@code LocalTime}1339* objects in terms of a single {@code TemporalUnit}.1340* The start and end points are {@code this} and the specified time.1341* The result will be negative if the end is before the start.1342* The {@code Temporal} passed to this method is converted to a1343* {@code LocalTime} using {@link #from(TemporalAccessor)}.1344* For example, the amount in hours between two times can be calculated1345* using {@code startTime.until(endTime, HOURS)}.1346* <p>1347* The calculation returns a whole number, representing the number of1348* complete units between the two times.1349* For example, the amount in hours between 11:30 and 13:29 will only1350* be one hour as it is one minute short of two hours.1351* <p>1352* There are two equivalent ways of using this method.1353* The first is to invoke this method.1354* The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:1355* <pre>1356* // these two lines are equivalent1357* amount = start.until(end, MINUTES);1358* amount = MINUTES.between(start, end);1359* </pre>1360* The choice should be made based on which makes the code more readable.1361* <p>1362* The calculation is implemented in this method for {@link ChronoUnit}.1363* The units {@code NANOS}, {@code MICROS}, {@code MILLIS}, {@code SECONDS},1364* {@code MINUTES}, {@code HOURS} and {@code HALF_DAYS} are supported.1365* Other {@code ChronoUnit} values will throw an exception.1366* <p>1367* If the unit is not a {@code ChronoUnit}, then the result of this method1368* is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}1369* passing {@code this} as the first argument and the converted input temporal1370* as the second argument.1371* <p>1372* This instance is immutable and unaffected by this method call.1373*1374* @param endExclusive the end time, exclusive, which is converted to a {@code LocalTime}, not null1375* @param unit the unit to measure the amount in, not null1376* @return the amount of time between this time and the end time1377* @throws DateTimeException if the amount cannot be calculated, or the end1378* temporal cannot be converted to a {@code LocalTime}1379* @throws UnsupportedTemporalTypeException if the unit is not supported1380* @throws ArithmeticException if numeric overflow occurs1381*/1382@Override1383public long until(Temporal endExclusive, TemporalUnit unit) {1384LocalTime end = LocalTime.from(endExclusive);1385if (unit instanceof ChronoUnit) {1386long nanosUntil = end.toNanoOfDay() - toNanoOfDay(); // no overflow1387switch ((ChronoUnit) unit) {1388case NANOS: return nanosUntil;1389case MICROS: return nanosUntil / 1000;1390case MILLIS: return nanosUntil / 1000_000;1391case SECONDS: return nanosUntil / NANOS_PER_SECOND;1392case MINUTES: return nanosUntil / NANOS_PER_MINUTE;1393case HOURS: return nanosUntil / NANOS_PER_HOUR;1394case HALF_DAYS: return nanosUntil / (12 * NANOS_PER_HOUR);1395}1396throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);1397}1398return unit.between(this, end);1399}14001401/**1402* Formats this time using the specified formatter.1403* <p>1404* This time will be passed to the formatter to produce a string.1405*1406* @param formatter the formatter to use, not null1407* @return the formatted time string, not null1408* @throws DateTimeException if an error occurs during printing1409*/1410public String format(DateTimeFormatter formatter) {1411Objects.requireNonNull(formatter, "formatter");1412return formatter.format(this);1413}14141415//-----------------------------------------------------------------------1416/**1417* Combines this time with a date to create a {@code LocalDateTime}.1418* <p>1419* This returns a {@code LocalDateTime} formed from this time at the specified date.1420* All possible combinations of date and time are valid.1421*1422* @param date the date to combine with, not null1423* @return the local date-time formed from this time and the specified date, not null1424*/1425public LocalDateTime atDate(LocalDate date) {1426return LocalDateTime.of(date, this);1427}14281429/**1430* Combines this time with an offset to create an {@code OffsetTime}.1431* <p>1432* This returns an {@code OffsetTime} formed from this time at the specified offset.1433* All possible combinations of time and offset are valid.1434*1435* @param offset the offset to combine with, not null1436* @return the offset time formed from this time and the specified offset, not null1437*/1438public OffsetTime atOffset(ZoneOffset offset) {1439return OffsetTime.of(this, offset);1440}14411442//-----------------------------------------------------------------------1443/**1444* Extracts the time as seconds of day,1445* from {@code 0} to {@code 24 * 60 * 60 - 1}.1446*1447* @return the second-of-day equivalent to this time1448*/1449public int toSecondOfDay() {1450int total = hour * SECONDS_PER_HOUR;1451total += minute * SECONDS_PER_MINUTE;1452total += second;1453return total;1454}14551456/**1457* Extracts the time as nanos of day,1458* from {@code 0} to {@code 24 * 60 * 60 * 1,000,000,000 - 1}.1459*1460* @return the nano of day equivalent to this time1461*/1462public long toNanoOfDay() {1463long total = hour * NANOS_PER_HOUR;1464total += minute * NANOS_PER_MINUTE;1465total += second * NANOS_PER_SECOND;1466total += nano;1467return total;1468}14691470//-----------------------------------------------------------------------1471/**1472* Compares this time to another time.1473* <p>1474* The comparison is based on the time-line position of the local times within a day.1475* It is "consistent with equals", as defined by {@link Comparable}.1476*1477* @param other the other time to compare to, not null1478* @return the comparator value, negative if less, positive if greater1479* @throws NullPointerException if {@code other} is null1480*/1481@Override1482public int compareTo(LocalTime other) {1483int cmp = Integer.compare(hour, other.hour);1484if (cmp == 0) {1485cmp = Integer.compare(minute, other.minute);1486if (cmp == 0) {1487cmp = Integer.compare(second, other.second);1488if (cmp == 0) {1489cmp = Integer.compare(nano, other.nano);1490}1491}1492}1493return cmp;1494}14951496/**1497* Checks if this time is after the specified time.1498* <p>1499* The comparison is based on the time-line position of the time within a day.1500*1501* @param other the other time to compare to, not null1502* @return true if this is after the specified time1503* @throws NullPointerException if {@code other} is null1504*/1505public boolean isAfter(LocalTime other) {1506return compareTo(other) > 0;1507}15081509/**1510* Checks if this time is before the specified time.1511* <p>1512* The comparison is based on the time-line position of the time within a day.1513*1514* @param other the other time to compare to, not null1515* @return true if this point is before the specified time1516* @throws NullPointerException if {@code other} is null1517*/1518public boolean isBefore(LocalTime other) {1519return compareTo(other) < 0;1520}15211522//-----------------------------------------------------------------------1523/**1524* Checks if this time is equal to another time.1525* <p>1526* The comparison is based on the time-line position of the time within a day.1527* <p>1528* Only objects of type {@code LocalTime} are compared, other types return false.1529* To compare the date of two {@code TemporalAccessor} instances, use1530* {@link ChronoField#NANO_OF_DAY} as a comparator.1531*1532* @param obj the object to check, null returns false1533* @return true if this is equal to the other time1534*/1535@Override1536public boolean equals(Object obj) {1537if (this == obj) {1538return true;1539}1540if (obj instanceof LocalTime) {1541LocalTime other = (LocalTime) obj;1542return hour == other.hour && minute == other.minute &&1543second == other.second && nano == other.nano;1544}1545return false;1546}15471548/**1549* A hash code for this time.1550*1551* @return a suitable hash code1552*/1553@Override1554public int hashCode() {1555long nod = toNanoOfDay();1556return (int) (nod ^ (nod >>> 32));1557}15581559//-----------------------------------------------------------------------1560/**1561* Outputs this time as a {@code String}, such as {@code 10:15}.1562* <p>1563* The output will be one of the following ISO-8601 formats:1564* <ul>1565* <li>{@code HH:mm}</li>1566* <li>{@code HH:mm:ss}</li>1567* <li>{@code HH:mm:ss.SSS}</li>1568* <li>{@code HH:mm:ss.SSSSSS}</li>1569* <li>{@code HH:mm:ss.SSSSSSSSS}</li>1570* </ul>1571* The format used will be the shortest that outputs the full value of1572* the time where the omitted parts are implied to be zero.1573*1574* @return a string representation of this time, not null1575*/1576@Override1577public String toString() {1578StringBuilder buf = new StringBuilder(18);1579int hourValue = hour;1580int minuteValue = minute;1581int secondValue = second;1582int nanoValue = nano;1583buf.append(hourValue < 10 ? "0" : "").append(hourValue)1584.append(minuteValue < 10 ? ":0" : ":").append(minuteValue);1585if (secondValue > 0 || nanoValue > 0) {1586buf.append(secondValue < 10 ? ":0" : ":").append(secondValue);1587if (nanoValue > 0) {1588buf.append('.');1589if (nanoValue % 1000_000 == 0) {1590buf.append(Integer.toString((nanoValue / 1000_000) + 1000).substring(1));1591} else if (nanoValue % 1000 == 0) {1592buf.append(Integer.toString((nanoValue / 1000) + 1000_000).substring(1));1593} else {1594buf.append(Integer.toString((nanoValue) + 1000_000_000).substring(1));1595}1596}1597}1598return buf.toString();1599}16001601//-----------------------------------------------------------------------1602/**1603* Writes the object using a1604* <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>.1605* @serialData1606* A twos-complement value indicates the remaining values are not in the stream1607* and should be set to zero.1608* <pre>1609* out.writeByte(4); // identifies a LocalTime1610* if (nano == 0) {1611* if (second == 0) {1612* if (minute == 0) {1613* out.writeByte(~hour);1614* } else {1615* out.writeByte(hour);1616* out.writeByte(~minute);1617* }1618* } else {1619* out.writeByte(hour);1620* out.writeByte(minute);1621* out.writeByte(~second);1622* }1623* } else {1624* out.writeByte(hour);1625* out.writeByte(minute);1626* out.writeByte(second);1627* out.writeInt(nano);1628* }1629* </pre>1630*1631* @return the instance of {@code Ser}, not null1632*/1633private Object writeReplace() {1634return new Ser(Ser.LOCAL_TIME_TYPE, this);1635}16361637/**1638* Defend against malicious streams.1639*1640* @param s the stream to read1641* @throws InvalidObjectException always1642*/1643private void readObject(ObjectInputStream s) throws InvalidObjectException {1644throw new InvalidObjectException("Deserialization via serialization delegate");1645}16461647void writeExternal(DataOutput out) throws IOException {1648if (nano == 0) {1649if (second == 0) {1650if (minute == 0) {1651out.writeByte(~hour);1652} else {1653out.writeByte(hour);1654out.writeByte(~minute);1655}1656} else {1657out.writeByte(hour);1658out.writeByte(minute);1659out.writeByte(~second);1660}1661} else {1662out.writeByte(hour);1663out.writeByte(minute);1664out.writeByte(second);1665out.writeInt(nano);1666}1667}16681669static LocalTime readExternal(DataInput in) throws IOException {1670int hour = in.readByte();1671int minute = 0;1672int second = 0;1673int nano = 0;1674if (hour < 0) {1675hour = ~hour;1676} else {1677minute = in.readByte();1678if (minute < 0) {1679minute = ~minute;1680} else {1681second = in.readByte();1682if (second < 0) {1683second = ~second;1684} else {1685nano = in.readInt();1686}1687}1688}1689return LocalTime.of(hour, minute, second, nano);1690}16911692}169316941695