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