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