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