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