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.LocalTime.NANOS_PER_HOUR; 35 import static org.threeten.bp.LocalTime.NANOS_PER_MINUTE; 36 import static org.threeten.bp.LocalTime.NANOS_PER_SECOND; 37 import static org.threeten.bp.LocalTime.SECONDS_PER_DAY; 38 import static org.threeten.bp.temporal.ChronoField.NANO_OF_DAY; 39 import static org.threeten.bp.temporal.ChronoField.OFFSET_SECONDS; 40 import static org.threeten.bp.temporal.ChronoUnit.NANOS; 41 42 import java.io.DataInput; 43 import java.io.DataOutput; 44 import java.io.IOException; 45 import java.io.InvalidObjectException; 46 import java.io.ObjectStreamException; 47 import java.io.Serializable; 48 49 import org.threeten.bp.format.DateTimeFormatter; 50 import org.threeten.bp.format.DateTimeParseException; 51 import org.threeten.bp.jdk8.DefaultInterfaceTemporalAccessor; 52 import org.threeten.bp.jdk8.Jdk8Methods; 53 import org.threeten.bp.temporal.ChronoField; 54 import org.threeten.bp.temporal.ChronoUnit; 55 import org.threeten.bp.temporal.Temporal; 56 import org.threeten.bp.temporal.TemporalAccessor; 57 import org.threeten.bp.temporal.TemporalAdjuster; 58 import org.threeten.bp.temporal.TemporalAmount; 59 import org.threeten.bp.temporal.TemporalField; 60 import org.threeten.bp.temporal.TemporalQueries; 61 import org.threeten.bp.temporal.TemporalQuery; 62 import org.threeten.bp.temporal.TemporalUnit; 63 import org.threeten.bp.temporal.UnsupportedTemporalTypeException; 64 import org.threeten.bp.temporal.ValueRange; 65 import org.threeten.bp.zone.ZoneRules; 66 67 /** 68 * A time with an offset from UTC/Greenwich in the ISO-8601 calendar system, 69 * such as {@code 10:15:30+01:00}. 70 * <p> 71 * {@code OffsetTime} is an immutable date-time object that represents a time, often 72 * viewed as hour-minute-second-offset. 73 * This class stores all time fields, to a precision of nanoseconds, 74 * as well as a zone offset. 75 * For example, the value "13:45.30.123456789+02:00" can be stored 76 * in an {@code OffsetTime}. 77 * 78 * <h3>Specification for implementors</h3> 79 * This class is immutable and thread-safe. 80 */ 81 public final class OffsetTime 82 extends DefaultInterfaceTemporalAccessor 83 implements Temporal, TemporalAdjuster, Comparable<OffsetTime>, Serializable { 84 85 /** 86 * The minimum supported {@code OffsetTime}, '00:00:00+18:00'. 87 * This is the time of midnight at the start of the day in the maximum offset 88 * (larger offsets are earlier on the time-line). 89 * This combines {@link LocalTime#MIN} and {@link ZoneOffset#MAX}. 90 * This could be used by an application as a "far past" date. 91 */ 92 public static final OffsetTime MIN = LocalTime.MIN.atOffset(ZoneOffset.MAX); 93 /** 94 * The maximum supported {@code OffsetTime}, '23:59:59.999999999-18:00'. 95 * This is the time just before midnight at the end of the day in the minimum offset 96 * (larger negative offsets are later on the time-line). 97 * This combines {@link LocalTime#MAX} and {@link ZoneOffset#MIN}. 98 * This could be used by an application as a "far future" date. 99 */ 100 public static final OffsetTime MAX = LocalTime.MAX.atOffset(ZoneOffset.MIN); 101 /** 102 * Simulate JDK 8 method reference OffsetTime::from. 103 */ 104 public static final TemporalQuery<OffsetTime> FROM = new TemporalQuery<OffsetTime>() { 105 @Override 106 public OffsetTime queryFrom(TemporalAccessor temporal) { 107 return OffsetTime.from(temporal); 108 } 109 }; 110 111 /** 112 * Serialization version. 113 */ 114 private static final long serialVersionUID = 7264499704384272492L; 115 116 /** 117 * The local date-time. 118 */ 119 private final LocalTime time; 120 /** 121 * The offset from UTC/Greenwich. 122 */ 123 private final ZoneOffset offset; 124 125 //----------------------------------------------------------------------- 126 /** 127 * Obtains the current time from the system clock in the default time-zone. 128 * <p> 129 * This will query the {@link Clock#systemDefaultZone() system clock} in the default 130 * time-zone to obtain the current time. 131 * The offset will be calculated from the time-zone in the clock. 132 * <p> 133 * Using this method will prevent the ability to use an alternate clock for testing 134 * because the clock is hard-coded. 135 * 136 * @return the current time using the system clock, not null 137 */ now()138 public static OffsetTime now() { 139 return now(Clock.systemDefaultZone()); 140 } 141 142 /** 143 * Obtains the current time from the system clock in the specified time-zone. 144 * <p> 145 * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current time. 146 * Specifying the time-zone avoids dependence on the default time-zone. 147 * The offset will be calculated from the specified time-zone. 148 * <p> 149 * Using this method will prevent the ability to use an alternate clock for testing 150 * because the clock is hard-coded. 151 * 152 * @param zone the zone ID to use, not null 153 * @return the current time using the system clock, not null 154 */ now(ZoneId zone)155 public static OffsetTime now(ZoneId zone) { 156 return now(Clock.system(zone)); 157 } 158 159 /** 160 * Obtains the current time from the specified clock. 161 * <p> 162 * This will query the specified clock to obtain the current time. 163 * The offset will be calculated from the time-zone in the clock. 164 * <p> 165 * Using this method allows the use of an alternate clock for testing. 166 * The alternate clock may be introduced using {@link Clock dependency injection}. 167 * 168 * @param clock the clock to use, not null 169 * @return the current time, not null 170 */ now(Clock clock)171 public static OffsetTime now(Clock clock) { 172 Jdk8Methods.requireNonNull(clock, "clock"); 173 final Instant now = clock.instant(); // called once 174 return ofInstant(now, clock.getZone().getRules().getOffset(now)); 175 } 176 177 //----------------------------------------------------------------------- 178 /** 179 * Obtains an instance of {@code OffsetTime} from a local time and an offset. 180 * 181 * @param time the local time, not null 182 * @param offset the zone offset, not null 183 * @return the offset time, not null 184 */ of(LocalTime time, ZoneOffset offset)185 public static OffsetTime of(LocalTime time, ZoneOffset offset) { 186 return new OffsetTime(time, offset); 187 } 188 189 /** 190 * Obtains an instance of {@code OffsetTime} from an hour, minute, second and nanosecond. 191 * <p> 192 * This creates an offset time with the four specified fields. 193 * <p> 194 * This method exists primarily for writing test cases. 195 * Non test-code will typically use other methods to create an offset time. 196 * {@code LocalTime} has two additional convenience variants of the 197 * equivalent factory method taking fewer arguments. 198 * They are not provided here to reduce the footprint of the API. 199 * 200 * @param hour the hour-of-day to represent, from 0 to 23 201 * @param minute the minute-of-hour to represent, from 0 to 59 202 * @param second the second-of-minute to represent, from 0 to 59 203 * @param nanoOfSecond the nano-of-second to represent, from 0 to 999,999,999 204 * @param offset the zone offset, not null 205 * @return the offset time, not null 206 * @throws DateTimeException if the value of any field is out of range 207 */ of(int hour, int minute, int second, int nanoOfSecond, ZoneOffset offset)208 public static OffsetTime of(int hour, int minute, int second, int nanoOfSecond, ZoneOffset offset) { 209 return new OffsetTime(LocalTime.of(hour, minute, second, nanoOfSecond), offset); 210 } 211 212 //----------------------------------------------------------------------- 213 /** 214 * Obtains an instance of {@code OffsetTime} from an {@code Instant} and zone ID. 215 * <p> 216 * This creates an offset time with the same instant as that specified. 217 * Finding the offset from UTC/Greenwich is simple as there is only one valid 218 * offset for each instant. 219 * <p> 220 * The date component of the instant is dropped during the conversion. 221 * This means that the conversion can never fail due to the instant being 222 * out of the valid range of dates. 223 * 224 * @param instant the instant to create the time from, not null 225 * @param zone the time-zone, which may be an offset, not null 226 * @return the offset time, not null 227 */ ofInstant(Instant instant, ZoneId zone)228 public static OffsetTime ofInstant(Instant instant, ZoneId zone) { 229 Jdk8Methods.requireNonNull(instant, "instant"); 230 Jdk8Methods.requireNonNull(zone, "zone"); 231 ZoneRules rules = zone.getRules(); 232 ZoneOffset offset = rules.getOffset(instant); 233 long secsOfDay = instant.getEpochSecond() % SECONDS_PER_DAY; 234 secsOfDay = (secsOfDay + offset.getTotalSeconds()) % SECONDS_PER_DAY; 235 if (secsOfDay < 0) { 236 secsOfDay += SECONDS_PER_DAY; 237 } 238 LocalTime time = LocalTime.ofSecondOfDay(secsOfDay, instant.getNano()); 239 return new OffsetTime(time, offset); 240 } 241 242 //----------------------------------------------------------------------- 243 /** 244 * Obtains an instance of {@code OffsetTime} from a temporal object. 245 * <p> 246 * A {@code TemporalAccessor} represents some form of date and time information. 247 * This factory converts the arbitrary temporal object to an instance of {@code OffsetTime}. 248 * <p> 249 * The conversion extracts and combines {@code LocalTime} and {@code ZoneOffset}. 250 * <p> 251 * This method matches the signature of the functional interface {@link TemporalQuery} 252 * allowing it to be used in queries via method reference, {@code OffsetTime::from}. 253 * 254 * @param temporal the temporal object to convert, not null 255 * @return the offset time, not null 256 * @throws DateTimeException if unable to convert to an {@code OffsetTime} 257 */ from(TemporalAccessor temporal)258 public static OffsetTime from(TemporalAccessor temporal) { 259 if (temporal instanceof OffsetTime) { 260 return (OffsetTime) temporal; 261 } 262 try { 263 LocalTime time = LocalTime.from(temporal); 264 ZoneOffset offset = ZoneOffset.from(temporal); 265 return new OffsetTime(time, offset); 266 } catch (DateTimeException ex) { 267 throw new DateTimeException("Unable to obtain OffsetTime from TemporalAccessor: " + 268 temporal + ", type " + temporal.getClass().getName()); 269 } 270 } 271 272 //----------------------------------------------------------------------- 273 /** 274 * Obtains an instance of {@code OffsetTime} from a text string such as {@code 10:15:30+01:00}. 275 * <p> 276 * The string must represent a valid time and is parsed using 277 * {@link org.threeten.bp.format.DateTimeFormatter#ISO_OFFSET_TIME}. 278 * 279 * @param text the text to parse such as "10:15:30+01:00", not null 280 * @return the parsed local time, not null 281 * @throws DateTimeParseException if the text cannot be parsed 282 */ parse(CharSequence text)283 public static OffsetTime parse(CharSequence text) { 284 return parse(text, DateTimeFormatter.ISO_OFFSET_TIME); 285 } 286 287 /** 288 * Obtains an instance of {@code OffsetTime} from a text string using a specific formatter. 289 * <p> 290 * The text is parsed using the formatter, returning a time. 291 * 292 * @param text the text to parse, not null 293 * @param formatter the formatter to use, not null 294 * @return the parsed offset time, not null 295 * @throws DateTimeParseException if the text cannot be parsed 296 */ parse(CharSequence text, DateTimeFormatter formatter)297 public static OffsetTime parse(CharSequence text, DateTimeFormatter formatter) { 298 Jdk8Methods.requireNonNull(formatter, "formatter"); 299 return formatter.parse(text, OffsetTime.FROM); 300 } 301 302 //----------------------------------------------------------------------- 303 /** 304 * Constructor. 305 * 306 * @param time the local time, not null 307 * @param offset the zone offset, not null 308 */ OffsetTime(LocalTime time, ZoneOffset offset)309 private OffsetTime(LocalTime time, ZoneOffset offset) { 310 this.time = Jdk8Methods.requireNonNull(time, "time"); 311 this.offset = Jdk8Methods.requireNonNull(offset, "offset"); 312 } 313 314 /** 315 * Returns a new time based on this one, returning {@code this} where possible. 316 * 317 * @param time the time to create with, not null 318 * @param offset the zone offset to create with, not null 319 */ with(LocalTime time, ZoneOffset offset)320 private OffsetTime with(LocalTime time, ZoneOffset offset) { 321 if (this.time == time && this.offset.equals(offset)) { 322 return this; 323 } 324 return new OffsetTime(time, offset); 325 } 326 327 //----------------------------------------------------------------------- 328 /** 329 * Checks if the specified field is supported. 330 * <p> 331 * This checks if this time can be queried for the specified field. 332 * If false, then calling the {@link #range(TemporalField) range} and 333 * {@link #get(TemporalField) get} methods will throw an exception. 334 * <p> 335 * If the field is a {@link ChronoField} then the query is implemented here. 336 * The supported fields are: 337 * <ul> 338 * <li>{@code NANO_OF_SECOND} 339 * <li>{@code NANO_OF_DAY} 340 * <li>{@code MICRO_OF_SECOND} 341 * <li>{@code MICRO_OF_DAY} 342 * <li>{@code MILLI_OF_SECOND} 343 * <li>{@code MILLI_OF_DAY} 344 * <li>{@code SECOND_OF_MINUTE} 345 * <li>{@code SECOND_OF_DAY} 346 * <li>{@code MINUTE_OF_HOUR} 347 * <li>{@code MINUTE_OF_DAY} 348 * <li>{@code HOUR_OF_AMPM} 349 * <li>{@code CLOCK_HOUR_OF_AMPM} 350 * <li>{@code HOUR_OF_DAY} 351 * <li>{@code CLOCK_HOUR_OF_DAY} 352 * <li>{@code AMPM_OF_DAY} 353 * <li>{@code OFFSET_SECONDS} 354 * </ul> 355 * All other {@code ChronoField} instances will return false. 356 * <p> 357 * If the field is not a {@code ChronoField}, then the result of this method 358 * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)} 359 * passing {@code this} as the argument. 360 * Whether the field is supported is determined by the field. 361 * 362 * @param field the field to check, null returns false 363 * @return true if the field is supported on this time, false if not 364 */ 365 @Override isSupported(TemporalField field)366 public boolean isSupported(TemporalField field) { 367 if (field instanceof ChronoField) { 368 return field.isTimeBased() || field == OFFSET_SECONDS; 369 } 370 return field != null && field.isSupportedBy(this); 371 } 372 373 @Override isSupported(TemporalUnit unit)374 public boolean isSupported(TemporalUnit unit) { 375 if (unit instanceof ChronoUnit) { 376 return unit.isTimeBased(); 377 } 378 return unit != null && unit.isSupportedBy(this); 379 } 380 381 /** 382 * Gets the range of valid values for the specified field. 383 * <p> 384 * The range object expresses the minimum and maximum valid values for a field. 385 * This time is used to enhance the accuracy of the returned range. 386 * If it is not possible to return the range, because the field is not supported 387 * or for some other reason, an exception is thrown. 388 * <p> 389 * If the field is a {@link ChronoField} then the query is implemented here. 390 * The {@link #isSupported(TemporalField) supported fields} will return 391 * appropriate range instances. 392 * All other {@code ChronoField} instances will throw a {@code DateTimeException}. 393 * <p> 394 * If the field is not a {@code ChronoField}, then the result of this method 395 * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)} 396 * passing {@code this} as the argument. 397 * Whether the range can be obtained is determined by the field. 398 * 399 * @param field the field to query the range for, not null 400 * @return the range of valid values for the field, not null 401 * @throws DateTimeException if the range for the field cannot be obtained 402 */ 403 @Override range(TemporalField field)404 public ValueRange range(TemporalField field) { 405 if (field instanceof ChronoField) { 406 if (field == OFFSET_SECONDS) { 407 return field.range(); 408 } 409 return time.range(field); 410 } 411 return field.rangeRefinedBy(this); 412 } 413 414 /** 415 * Gets the value of the specified field from this time as an {@code int}. 416 * <p> 417 * This queries this time for the value for the specified field. 418 * The returned value will always be within the valid range of values for the field. 419 * If it is not possible to return the value, because the field is not supported 420 * or for some other reason, an exception is thrown. 421 * <p> 422 * If the field is a {@link ChronoField} then the query is implemented here. 423 * The {@link #isSupported(TemporalField) supported fields} will return valid 424 * values based on this time, except {@code NANO_OF_DAY} and {@code MICRO_OF_DAY} 425 * which are too large to fit in an {@code int} and throw a {@code DateTimeException}. 426 * All other {@code ChronoField} instances will throw a {@code DateTimeException}. 427 * <p> 428 * If the field is not a {@code ChronoField}, then the result of this method 429 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} 430 * passing {@code this} as the argument. Whether the value can be obtained, 431 * and what the value represents, is determined by the field. 432 * 433 * @param field the field to get, not null 434 * @return the value for the field 435 * @throws DateTimeException if a value for the field cannot be obtained 436 * @throws ArithmeticException if numeric overflow occurs 437 */ 438 @Override // override for Javadoc get(TemporalField field)439 public int get(TemporalField field) { 440 return super.get(field); 441 } 442 443 /** 444 * Gets the value of the specified field from this time as a {@code long}. 445 * <p> 446 * This queries this time for the value for the specified field. 447 * If it is not possible to return the value, because the field is not supported 448 * or for some other reason, an exception is thrown. 449 * <p> 450 * If the field is a {@link ChronoField} then the query is implemented here. 451 * The {@link #isSupported(TemporalField) supported fields} will return valid 452 * values based on this time. 453 * All other {@code ChronoField} instances will throw a {@code DateTimeException}. 454 * <p> 455 * If the field is not a {@code ChronoField}, then the result of this method 456 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} 457 * passing {@code this} as the argument. Whether the value can be obtained, 458 * and what the value represents, is determined by the field. 459 * 460 * @param field the field to get, not null 461 * @return the value for the field 462 * @throws DateTimeException if a value for the field cannot be obtained 463 * @throws ArithmeticException if numeric overflow occurs 464 */ 465 @Override getLong(TemporalField field)466 public long getLong(TemporalField field) { 467 if (field instanceof ChronoField) { 468 if (field == OFFSET_SECONDS) { 469 return getOffset().getTotalSeconds(); 470 } 471 return time.getLong(field); 472 } 473 return field.getFrom(this); 474 } 475 476 //----------------------------------------------------------------------- 477 /** 478 * Gets the zone offset, such as '+01:00'. 479 * <p> 480 * This is the offset of the local time from UTC/Greenwich. 481 * 482 * @return the zone offset, not null 483 */ getOffset()484 public ZoneOffset getOffset() { 485 return offset; 486 } 487 488 /** 489 * Returns a copy of this {@code OffsetTime} with the specified offset ensuring 490 * that the result has the same local time. 491 * <p> 492 * This method returns an object with the same {@code LocalTime} and the specified {@code ZoneOffset}. 493 * No calculation is needed or performed. 494 * For example, if this time represents {@code 10:30+02:00} and the offset specified is 495 * {@code +03:00}, then this method will return {@code 10:30+03:00}. 496 * <p> 497 * To take into account the difference between the offsets, and adjust the time fields, 498 * use {@link #withOffsetSameInstant}. 499 * <p> 500 * This instance is immutable and unaffected by this method call. 501 * 502 * @param offset the zone offset to change to, not null 503 * @return an {@code OffsetTime} based on this time with the requested offset, not null 504 */ withOffsetSameLocal(ZoneOffset offset)505 public OffsetTime withOffsetSameLocal(ZoneOffset offset) { 506 return offset != null && offset.equals(this.offset) ? this : new OffsetTime(time, offset); 507 } 508 509 /** 510 * Returns a copy of this {@code OffsetTime} with the specified offset ensuring 511 * that the result is at the same instant on an implied day. 512 * <p> 513 * This method returns an object with the specified {@code ZoneOffset} and a {@code LocalTime} 514 * adjusted by the difference between the two offsets. 515 * This will result in the old and new objects representing the same instant on an implied day. 516 * This is useful for finding the local time in a different offset. 517 * For example, if this time represents {@code 10:30+02:00} and the offset specified is 518 * {@code +03:00}, then this method will return {@code 11:30+03:00}. 519 * <p> 520 * To change the offset without adjusting the local time use {@link #withOffsetSameLocal}. 521 * <p> 522 * This instance is immutable and unaffected by this method call. 523 * 524 * @param offset the zone offset to change to, not null 525 * @return an {@code OffsetTime} based on this time with the requested offset, not null 526 */ withOffsetSameInstant(ZoneOffset offset)527 public OffsetTime withOffsetSameInstant(ZoneOffset offset) { 528 if (offset.equals(this.offset)) { 529 return this; 530 } 531 int difference = offset.getTotalSeconds() - this.offset.getTotalSeconds(); 532 LocalTime adjusted = time.plusSeconds(difference); 533 return new OffsetTime(adjusted, offset); 534 } 535 536 //----------------------------------------------------------------------- 537 /** 538 * Gets the hour-of-day field. 539 * 540 * @return the hour-of-day, from 0 to 23 541 */ getHour()542 public int getHour() { 543 return time.getHour(); 544 } 545 546 /** 547 * Gets the minute-of-hour field. 548 * 549 * @return the minute-of-hour, from 0 to 59 550 */ getMinute()551 public int getMinute() { 552 return time.getMinute(); 553 } 554 555 /** 556 * Gets the second-of-minute field. 557 * 558 * @return the second-of-minute, from 0 to 59 559 */ getSecond()560 public int getSecond() { 561 return time.getSecond(); 562 } 563 564 /** 565 * Gets the nano-of-second field. 566 * 567 * @return the nano-of-second, from 0 to 999,999,999 568 */ getNano()569 public int getNano() { 570 return time.getNano(); 571 } 572 573 //----------------------------------------------------------------------- 574 /** 575 * Returns an adjusted copy of this time. 576 * <p> 577 * This returns a new {@code OffsetTime}, based on this one, with the time adjusted. 578 * The adjustment takes place using the specified adjuster strategy object. 579 * Read the documentation of the adjuster to understand what adjustment will be made. 580 * <p> 581 * A simple adjuster might simply set the one of the fields, such as the hour field. 582 * A more complex adjuster might set the time to the last hour of the day. 583 * <p> 584 * The classes {@link LocalTime} and {@link ZoneOffset} implement {@code TemporalAdjuster}, 585 * thus this method can be used to change the time or offset: 586 * <pre> 587 * result = offsetTime.with(time); 588 * result = offsetTime.with(offset); 589 * </pre> 590 * <p> 591 * The result of this method is obtained by invoking the 592 * {@link TemporalAdjuster#adjustInto(Temporal)} method on the 593 * specified adjuster passing {@code this} as the argument. 594 * <p> 595 * This instance is immutable and unaffected by this method call. 596 * 597 * @param adjuster the adjuster to use, not null 598 * @return an {@code OffsetTime} based on {@code this} with the adjustment made, not null 599 * @throws DateTimeException if the adjustment cannot be made 600 * @throws ArithmeticException if numeric overflow occurs 601 */ 602 @Override with(TemporalAdjuster adjuster)603 public OffsetTime with(TemporalAdjuster adjuster) { 604 // optimizations 605 if (adjuster instanceof LocalTime) { 606 return with((LocalTime) adjuster, offset); 607 } else if (adjuster instanceof ZoneOffset) { 608 return with(time, (ZoneOffset) adjuster); 609 } else if (adjuster instanceof OffsetTime) { 610 return (OffsetTime) adjuster; 611 } 612 return (OffsetTime) adjuster.adjustInto(this); 613 } 614 615 /** 616 * Returns a copy of this time with the specified field set to a new value. 617 * <p> 618 * This returns a new {@code OffsetTime}, based on this one, with the value 619 * for the specified field changed. 620 * This can be used to change any supported field, such as the hour, minute or second. 621 * If it is not possible to set the value, because the field is not supported or for 622 * some other reason, an exception is thrown. 623 * <p> 624 * If the field is a {@link ChronoField} then the adjustment is implemented here. 625 * <p> 626 * The {@code OFFSET_SECONDS} field will return a time with the specified offset. 627 * The local time is unaltered. If the new offset value is outside the valid range 628 * then a {@code DateTimeException} will be thrown. 629 * <p> 630 * The other {@link #isSupported(TemporalField) supported fields} will behave as per 631 * the matching method on {@link LocalTime#with(TemporalField, long)} LocalTime}. 632 * In this case, the offset is not part of the calculation and will be unchanged. 633 * <p> 634 * All other {@code ChronoField} instances will throw a {@code DateTimeException}. 635 * <p> 636 * If the field is not a {@code ChronoField}, then the result of this method 637 * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)} 638 * passing {@code this} as the argument. In this case, the field determines 639 * whether and how to adjust the instant. 640 * <p> 641 * This instance is immutable and unaffected by this method call. 642 * 643 * @param field the field to set in the result, not null 644 * @param newValue the new value of the field in the result 645 * @return an {@code OffsetTime} based on {@code this} with the specified field set, not null 646 * @throws DateTimeException if the field cannot be set 647 * @throws ArithmeticException if numeric overflow occurs 648 */ 649 @Override with(TemporalField field, long newValue)650 public OffsetTime with(TemporalField field, long newValue) { 651 if (field instanceof ChronoField) { 652 if (field == OFFSET_SECONDS) { 653 ChronoField f = (ChronoField) field; 654 return with(time, ZoneOffset.ofTotalSeconds(f.checkValidIntValue(newValue))); 655 } 656 return with(time.with(field, newValue), offset); 657 } 658 return field.adjustInto(this, newValue); 659 } 660 661 //----------------------------------------------------------------------- 662 /** 663 * Returns a copy of this {@code OffsetTime} with the hour-of-day value altered. 664 * <p> 665 * The offset does not affect the calculation and will be the same in the result. 666 * <p> 667 * This instance is immutable and unaffected by this method call. 668 * 669 * @param hour the hour-of-day to set in the result, from 0 to 23 670 * @return an {@code OffsetTime} based on this time with the requested hour, not null 671 * @throws DateTimeException if the hour value is invalid 672 */ withHour(int hour)673 public OffsetTime withHour(int hour) { 674 return with(time.withHour(hour), offset); 675 } 676 677 /** 678 * Returns a copy of this {@code OffsetTime} with the minute-of-hour value altered. 679 * <p> 680 * The offset does not affect the calculation and will be the same in the result. 681 * <p> 682 * This instance is immutable and unaffected by this method call. 683 * 684 * @param minute the minute-of-hour to set in the result, from 0 to 59 685 * @return an {@code OffsetTime} based on this time with the requested minute, not null 686 * @throws DateTimeException if the minute value is invalid 687 */ withMinute(int minute)688 public OffsetTime withMinute(int minute) { 689 return with(time.withMinute(minute), offset); 690 } 691 692 /** 693 * Returns a copy of this {@code OffsetTime} with the second-of-minute value altered. 694 * <p> 695 * The offset does not affect the calculation and will be the same in the result. 696 * <p> 697 * This instance is immutable and unaffected by this method call. 698 * 699 * @param second the second-of-minute to set in the result, from 0 to 59 700 * @return an {@code OffsetTime} based on this time with the requested second, not null 701 * @throws DateTimeException if the second value is invalid 702 */ withSecond(int second)703 public OffsetTime withSecond(int second) { 704 return with(time.withSecond(second), offset); 705 } 706 707 /** 708 * Returns a copy of this {@code OffsetTime} with the nano-of-second value altered. 709 * <p> 710 * The offset does not affect the calculation and will be the same in the result. 711 * <p> 712 * This instance is immutable and unaffected by this method call. 713 * 714 * @param nanoOfSecond the nano-of-second to set in the result, from 0 to 999,999,999 715 * @return an {@code OffsetTime} based on this time with the requested nanosecond, not null 716 * @throws DateTimeException if the nanos value is invalid 717 */ withNano(int nanoOfSecond)718 public OffsetTime withNano(int nanoOfSecond) { 719 return with(time.withNano(nanoOfSecond), offset); 720 } 721 722 //----------------------------------------------------------------------- 723 /** 724 * Returns a copy of this {@code OffsetTime} with the time truncated. 725 * <p> 726 * Truncation returns a copy of the original time with fields 727 * smaller than the specified unit set to zero. 728 * For example, truncating with the {@link ChronoUnit#MINUTES minutes} unit 729 * will set the second-of-minute and nano-of-second field to zero. 730 * <p> 731 * The unit must have a {@linkplain TemporalUnit#getDuration() duration} 732 * that divides into the length of a standard day without remainder. 733 * This includes all supplied time units on {@link ChronoUnit} and 734 * {@link ChronoUnit#DAYS DAYS}. Other units throw an exception. 735 * <p> 736 * The offset does not affect the calculation and will be the same in the result. 737 * <p> 738 * This instance is immutable and unaffected by this method call. 739 * 740 * @param unit the unit to truncate to, not null 741 * @return an {@code OffsetTime} based on this time with the time truncated, not null 742 * @throws DateTimeException if unable to truncate 743 */ truncatedTo(TemporalUnit unit)744 public OffsetTime truncatedTo(TemporalUnit unit) { 745 return with(time.truncatedTo(unit), offset); 746 } 747 748 //----------------------------------------------------------------------- 749 /** 750 * Returns a copy of this date with the specified period added. 751 * <p> 752 * This method returns a new time based on this time with the specified period added. 753 * The amount is typically {@link Period} but may be any other type implementing 754 * the {@link TemporalAmount} interface. 755 * The calculation is delegated to the specified adjuster, which typically calls 756 * back to {@link #plus(long, TemporalUnit)}. 757 * The offset is not part of the calculation and will be unchanged in the result. 758 * <p> 759 * This instance is immutable and unaffected by this method call. 760 * 761 * @param amount the amount to add, not null 762 * @return an {@code OffsetTime} based on this time with the addition made, not null 763 * @throws DateTimeException if the addition cannot be made 764 * @throws ArithmeticException if numeric overflow occurs 765 */ 766 @Override plus(TemporalAmount amount)767 public OffsetTime plus(TemporalAmount amount) { 768 return (OffsetTime) amount.addTo(this); 769 } 770 771 /** 772 * Returns a copy of this time with the specified period added. 773 * <p> 774 * This method returns a new time based on this time with the specified period added. 775 * This can be used to add any period that is defined by a unit, for example to add hours, minutes or seconds. 776 * The unit is responsible for the details of the calculation, including the resolution 777 * of any edge cases in the calculation. 778 * The offset is not part of the calculation and will be unchanged in the result. 779 * <p> 780 * This instance is immutable and unaffected by this method call. 781 * 782 * @param amountToAdd the amount of the unit to add to the result, may be negative 783 * @param unit the unit of the period to add, not null 784 * @return an {@code OffsetTime} based on this time with the specified period added, not null 785 * @throws DateTimeException if the unit cannot be added to this type 786 */ 787 @Override plus(long amountToAdd, TemporalUnit unit)788 public OffsetTime plus(long amountToAdd, TemporalUnit unit) { 789 if (unit instanceof ChronoUnit) { 790 return with(time.plus(amountToAdd, unit), offset); 791 } 792 return unit.addTo(this, amountToAdd); 793 } 794 795 //----------------------------------------------------------------------- 796 /** 797 * Returns a copy of this {@code OffsetTime} with the specified period in hours added. 798 * <p> 799 * This adds the specified number of hours to this time, returning a new time. 800 * The calculation wraps around midnight. 801 * <p> 802 * This instance is immutable and unaffected by this method call. 803 * 804 * @param hours the hours to add, may be negative 805 * @return an {@code OffsetTime} based on this time with the hours added, not null 806 */ plusHours(long hours)807 public OffsetTime plusHours(long hours) { 808 return with(time.plusHours(hours), offset); 809 } 810 811 /** 812 * Returns a copy of this {@code OffsetTime} with the specified period in minutes added. 813 * <p> 814 * This adds the specified number of minutes to this time, returning a new time. 815 * The calculation wraps around midnight. 816 * <p> 817 * This instance is immutable and unaffected by this method call. 818 * 819 * @param minutes the minutes to add, may be negative 820 * @return an {@code OffsetTime} based on this time with the minutes added, not null 821 */ plusMinutes(long minutes)822 public OffsetTime plusMinutes(long minutes) { 823 return with(time.plusMinutes(minutes), offset); 824 } 825 826 /** 827 * Returns a copy of this {@code OffsetTime} with the specified period in seconds added. 828 * <p> 829 * This adds the specified number of seconds to this time, returning a new time. 830 * The calculation wraps around midnight. 831 * <p> 832 * This instance is immutable and unaffected by this method call. 833 * 834 * @param seconds the seconds to add, may be negative 835 * @return an {@code OffsetTime} based on this time with the seconds added, not null 836 */ plusSeconds(long seconds)837 public OffsetTime plusSeconds(long seconds) { 838 return with(time.plusSeconds(seconds), offset); 839 } 840 841 /** 842 * Returns a copy of this {@code OffsetTime} with the specified period in nanoseconds added. 843 * <p> 844 * This adds the specified number of nanoseconds to this time, returning a new time. 845 * The calculation wraps around midnight. 846 * <p> 847 * This instance is immutable and unaffected by this method call. 848 * 849 * @param nanos the nanos to add, may be negative 850 * @return an {@code OffsetTime} based on this time with the nanoseconds added, not null 851 */ plusNanos(long nanos)852 public OffsetTime plusNanos(long nanos) { 853 return with(time.plusNanos(nanos), offset); 854 } 855 856 //----------------------------------------------------------------------- 857 /** 858 * Returns a copy of this time with the specified period subtracted. 859 * <p> 860 * This method returns a new time based on this time with the specified period subtracted. 861 * The amount is typically {@link Period} but may be any other type implementing 862 * the {@link TemporalAmount} interface. 863 * The calculation is delegated to the specified adjuster, which typically calls 864 * back to {@link #minus(long, TemporalUnit)}. 865 * The offset is not part of the calculation and will be unchanged in the result. 866 * <p> 867 * This instance is immutable and unaffected by this method call. 868 * 869 * @param amount the amount to subtract, not null 870 * @return an {@code OffsetTime} based on this time with the subtraction made, not null 871 * @throws DateTimeException if the subtraction cannot be made 872 * @throws ArithmeticException if numeric overflow occurs 873 */ 874 @Override minus(TemporalAmount amount)875 public OffsetTime minus(TemporalAmount amount) { 876 return (OffsetTime) amount.subtractFrom(this); 877 } 878 879 /** 880 * Returns a copy of this time with the specified period subtracted. 881 * <p> 882 * This method returns a new time based on this time with the specified period subtracted. 883 * This can be used to subtract any period that is defined by a unit, for example to subtract hours, minutes or seconds. 884 * The unit is responsible for the details of the calculation, including the resolution 885 * of any edge cases in the calculation. 886 * The offset is not part of the calculation and will be unchanged in the result. 887 * <p> 888 * This instance is immutable and unaffected by this method call. 889 * 890 * @param amountToSubtract the amount of the unit to subtract from the result, may be negative 891 * @param unit the unit of the period to subtract, not null 892 * @return an {@code OffsetTime} based on this time with the specified period subtracted, not null 893 * @throws DateTimeException if the unit cannot be added to this type 894 */ 895 @Override minus(long amountToSubtract, TemporalUnit unit)896 public OffsetTime minus(long amountToSubtract, TemporalUnit unit) { 897 return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit)); 898 } 899 900 //----------------------------------------------------------------------- 901 /** 902 * Returns a copy of this {@code OffsetTime} with the specified period in hours subtracted. 903 * <p> 904 * This subtracts the specified number of hours from this time, returning a new time. 905 * The calculation wraps around midnight. 906 * <p> 907 * This instance is immutable and unaffected by this method call. 908 * 909 * @param hours the hours to subtract, may be negative 910 * @return an {@code OffsetTime} based on this time with the hours subtracted, not null 911 */ minusHours(long hours)912 public OffsetTime minusHours(long hours) { 913 return with(time.minusHours(hours), offset); 914 } 915 916 /** 917 * Returns a copy of this {@code OffsetTime} with the specified period in minutes subtracted. 918 * <p> 919 * This subtracts the specified number of minutes from this time, returning a new time. 920 * The calculation wraps around midnight. 921 * <p> 922 * This instance is immutable and unaffected by this method call. 923 * 924 * @param minutes the minutes to subtract, may be negative 925 * @return an {@code OffsetTime} based on this time with the minutes subtracted, not null 926 */ minusMinutes(long minutes)927 public OffsetTime minusMinutes(long minutes) { 928 return with(time.minusMinutes(minutes), offset); 929 } 930 931 /** 932 * Returns a copy of this {@code OffsetTime} with the specified period in seconds subtracted. 933 * <p> 934 * This subtracts the specified number of seconds from this time, returning a new time. 935 * The calculation wraps around midnight. 936 * <p> 937 * This instance is immutable and unaffected by this method call. 938 * 939 * @param seconds the seconds to subtract, may be negative 940 * @return an {@code OffsetTime} based on this time with the seconds subtracted, not null 941 */ minusSeconds(long seconds)942 public OffsetTime minusSeconds(long seconds) { 943 return with(time.minusSeconds(seconds), offset); 944 } 945 946 /** 947 * Returns a copy of this {@code OffsetTime} with the specified period in nanoseconds subtracted. 948 * <p> 949 * This subtracts the specified number of nanoseconds from this time, returning a new time. 950 * The calculation wraps around midnight. 951 * <p> 952 * This instance is immutable and unaffected by this method call. 953 * 954 * @param nanos the nanos to subtract, may be negative 955 * @return an {@code OffsetTime} based on this time with the nanoseconds subtracted, not null 956 */ minusNanos(long nanos)957 public OffsetTime minusNanos(long nanos) { 958 return with(time.minusNanos(nanos), offset); 959 } 960 961 //----------------------------------------------------------------------- 962 /** 963 * Queries this time using the specified query. 964 * <p> 965 * This queries this time using the specified query strategy object. 966 * The {@code TemporalQuery} object defines the logic to be used to 967 * obtain the result. Read the documentation of the query to understand 968 * what the result of this method will be. 969 * <p> 970 * The result of this method is obtained by invoking the 971 * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the 972 * specified query passing {@code this} as the argument. 973 * 974 * @param <R> the type of the result 975 * @param query the query to invoke, not null 976 * @return the query result, null may be returned (defined by the query) 977 * @throws DateTimeException if unable to query (defined by the query) 978 * @throws ArithmeticException if numeric overflow occurs (defined by the query) 979 */ 980 @SuppressWarnings("unchecked") 981 @Override query(TemporalQuery<R> query)982 public <R> R query(TemporalQuery<R> query) { 983 if (query == TemporalQueries.precision()) { 984 return (R) NANOS; 985 } else if (query == TemporalQueries.offset() || query == TemporalQueries.zone()) { 986 return (R) getOffset(); 987 } else if (query == TemporalQueries.localTime()) { 988 return (R) time; 989 } else if (query == TemporalQueries.chronology() || query == TemporalQueries.localDate() || query == TemporalQueries.zoneId()) { 990 return null; 991 } 992 return super.query(query); 993 } 994 995 /** 996 * Adjusts the specified temporal object to have the same offset and time 997 * as this object. 998 * <p> 999 * This returns a temporal object of the same observable type as the input 1000 * with the offset and time changed to be the same as this. 1001 * <p> 1002 * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)} 1003 * twice, passing {@link ChronoField#NANO_OF_DAY} and 1004 * {@link ChronoField#OFFSET_SECONDS} as the fields. 1005 * <p> 1006 * In most cases, it is clearer to reverse the calling pattern by using 1007 * {@link Temporal#with(TemporalAdjuster)}: 1008 * <pre> 1009 * // these two lines are equivalent, but the second approach is recommended 1010 * temporal = thisOffsetTime.adjustInto(temporal); 1011 * temporal = temporal.with(thisOffsetTime); 1012 * </pre> 1013 * <p> 1014 * This instance is immutable and unaffected by this method call. 1015 * 1016 * @param temporal the target object to be adjusted, not null 1017 * @return the adjusted object, not null 1018 * @throws DateTimeException if unable to make the adjustment 1019 * @throws ArithmeticException if numeric overflow occurs 1020 */ 1021 @Override adjustInto(Temporal temporal)1022 public Temporal adjustInto(Temporal temporal) { 1023 return temporal 1024 .with(NANO_OF_DAY, time.toNanoOfDay()) 1025 .with(OFFSET_SECONDS, getOffset().getTotalSeconds()); 1026 } 1027 1028 /** 1029 * Calculates the period between this time and another time in 1030 * terms of the specified unit. 1031 * <p> 1032 * This calculates the period between two times in terms of a single unit. 1033 * The start and end points are {@code this} and the specified time. 1034 * The result will be negative if the end is before the start. 1035 * For example, the period in hours between two times can be calculated 1036 * using {@code startTime.until(endTime, HOURS)}. 1037 * <p> 1038 * The {@code Temporal} passed to this method must be an {@code OffsetTime}. 1039 * If the offset differs between the two times, then the specified 1040 * end time is normalized to have the same offset as this time. 1041 * <p> 1042 * The calculation returns a whole number, representing the number of 1043 * complete units between the two times. 1044 * For example, the period in hours between 11:30Z and 13:29Z will only 1045 * be one hour as it is one minute short of two hours. 1046 * <p> 1047 * This method operates in association with {@link TemporalUnit#between}. 1048 * The result of this method is a {@code long} representing the amount of 1049 * the specified unit. By contrast, the result of {@code between} is an 1050 * object that can be used directly in addition/subtraction: 1051 * <pre> 1052 * long period = start.until(end, HOURS); // this method 1053 * dateTime.plus(HOURS.between(start, end)); // use in plus/minus 1054 * </pre> 1055 * <p> 1056 * The calculation is implemented in this method for {@link ChronoUnit}. 1057 * The units {@code NANOS}, {@code MICROS}, {@code MILLIS}, {@code SECONDS}, 1058 * {@code MINUTES}, {@code HOURS} and {@code HALF_DAYS} are supported. 1059 * Other {@code ChronoUnit} values will throw an exception. 1060 * <p> 1061 * If the unit is not a {@code ChronoUnit}, then the result of this method 1062 * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)} 1063 * passing {@code this} as the first argument and the input temporal as 1064 * the second argument. 1065 * <p> 1066 * This instance is immutable and unaffected by this method call. 1067 * 1068 * @param endExclusive the end time, which is converted to an {@code OffsetTime}, not null 1069 * @param unit the unit to measure the period in, not null 1070 * @return the amount of the period between this time and the end time 1071 * @throws DateTimeException if the period cannot be calculated 1072 * @throws ArithmeticException if numeric overflow occurs 1073 */ 1074 @Override until(Temporal endExclusive, TemporalUnit unit)1075 public long until(Temporal endExclusive, TemporalUnit unit) { 1076 OffsetTime end = OffsetTime.from(endExclusive); 1077 if (unit instanceof ChronoUnit) { 1078 long nanosUntil = end.toEpochNano() - toEpochNano(); // no overflow 1079 switch ((ChronoUnit) unit) { 1080 case NANOS: return nanosUntil; 1081 case MICROS: return nanosUntil / 1000; 1082 case MILLIS: return nanosUntil / 1000000; 1083 case SECONDS: return nanosUntil / NANOS_PER_SECOND; 1084 case MINUTES: return nanosUntil / NANOS_PER_MINUTE; 1085 case HOURS: return nanosUntil / NANOS_PER_HOUR; 1086 case HALF_DAYS: return nanosUntil / (12 * NANOS_PER_HOUR); 1087 } 1088 throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); 1089 } 1090 return unit.between(this, end); 1091 } 1092 1093 //----------------------------------------------------------------------- 1094 /** 1095 * Combines this time with a date to create an {@code OffsetDateTime}. 1096 * <p> 1097 * This returns an {@code OffsetDateTime} formed from this time and the specified date. 1098 * All possible combinations of date and time are valid. 1099 * 1100 * @param date the date to combine with, not null 1101 * @return the offset date-time formed from this time and the specified date, not null 1102 */ atDate(LocalDate date)1103 public OffsetDateTime atDate(LocalDate date) { 1104 return OffsetDateTime.of(date, time, offset); 1105 } 1106 1107 //----------------------------------------------------------------------- 1108 /** 1109 * Gets the {@code LocalTime} part of this date-time. 1110 * <p> 1111 * This returns a {@code LocalTime} with the same hour, minute, second and 1112 * nanosecond as this date-time. 1113 * 1114 * @return the time part of this date-time, not null 1115 */ toLocalTime()1116 public LocalTime toLocalTime() { 1117 return time; 1118 } 1119 1120 //----------------------------------------------------------------------- 1121 /** 1122 * Converts this time to epoch nanos based on 1970-01-01Z. 1123 * 1124 * @return the epoch nanos value 1125 */ toEpochNano()1126 private long toEpochNano() { 1127 long nod = time.toNanoOfDay(); 1128 long offsetNanos = offset.getTotalSeconds() * NANOS_PER_SECOND; 1129 return nod - offsetNanos; 1130 } 1131 1132 //----------------------------------------------------------------------- 1133 /** 1134 * Compares this {@code OffsetTime} to another time. 1135 * <p> 1136 * The comparison is based first on the UTC equivalent instant, then on the local time. 1137 * It is "consistent with equals", as defined by {@link Comparable}. 1138 * <p> 1139 * For example, the following is the comparator order: 1140 * <ol> 1141 * <li>{@code 10:30+01:00}</li> 1142 * <li>{@code 11:00+01:00}</li> 1143 * <li>{@code 12:00+02:00}</li> 1144 * <li>{@code 11:30+01:00}</li> 1145 * <li>{@code 12:00+01:00}</li> 1146 * <li>{@code 12:30+01:00}</li> 1147 * </ol> 1148 * Values #2 and #3 represent the same instant on the time-line. 1149 * When two values represent the same instant, the local time is compared 1150 * to distinguish them. This step is needed to make the ordering 1151 * consistent with {@code equals()}. 1152 * <p> 1153 * To compare the underlying local time of two {@code TemporalAccessor} instances, 1154 * use {@link ChronoField#NANO_OF_DAY} as a comparator. 1155 * 1156 * @param other the other time to compare to, not null 1157 * @return the comparator value, negative if less, positive if greater 1158 * @throws NullPointerException if {@code other} is null 1159 */ 1160 @Override compareTo(OffsetTime other)1161 public int compareTo(OffsetTime other) { 1162 if (offset.equals(other.offset)) { 1163 return time.compareTo(other.time); 1164 } 1165 int compare = Jdk8Methods.compareLongs(toEpochNano(), other.toEpochNano()); 1166 if (compare == 0) { 1167 compare = time.compareTo(other.time); 1168 } 1169 return compare; 1170 } 1171 1172 //----------------------------------------------------------------------- 1173 /** 1174 * Checks if the instant of this {@code OffsetTime} is after that of the 1175 * specified time applying both times to a common date. 1176 * <p> 1177 * This method differs from the comparison in {@link #compareTo} in that it 1178 * only compares the instant of the time. This is equivalent to converting both 1179 * times to an instant using the same date and comparing the instants. 1180 * 1181 * @param other the other time to compare to, not null 1182 * @return true if this is after the instant of the specified time 1183 */ isAfter(OffsetTime other)1184 public boolean isAfter(OffsetTime other) { 1185 return toEpochNano() > other.toEpochNano(); 1186 } 1187 1188 /** 1189 * Checks if the instant of this {@code OffsetTime} is before that of the 1190 * specified time applying both times to a common date. 1191 * <p> 1192 * This method differs from the comparison in {@link #compareTo} in that it 1193 * only compares the instant of the time. This is equivalent to converting both 1194 * times to an instant using the same date and comparing the instants. 1195 * 1196 * @param other the other time to compare to, not null 1197 * @return true if this is before the instant of the specified time 1198 */ isBefore(OffsetTime other)1199 public boolean isBefore(OffsetTime other) { 1200 return toEpochNano() < other.toEpochNano(); 1201 } 1202 1203 /** 1204 * Checks if the instant of this {@code OffsetTime} is equal to that of the 1205 * specified time applying both times to a common date. 1206 * <p> 1207 * This method differs from the comparison in {@link #compareTo} and {@link #equals} 1208 * in that it only compares the instant of the time. This is equivalent to converting both 1209 * times to an instant using the same date and comparing the instants. 1210 * 1211 * @param other the other time to compare to, not null 1212 * @return true if this is equal to the instant of the specified time 1213 */ isEqual(OffsetTime other)1214 public boolean isEqual(OffsetTime other) { 1215 return toEpochNano() == other.toEpochNano(); 1216 } 1217 1218 //----------------------------------------------------------------------- 1219 /** 1220 * Checks if this time is equal to another time. 1221 * <p> 1222 * The comparison is based on the local-time and the offset. 1223 * To compare for the same instant on the time-line, use {@link #isEqual(OffsetTime)}. 1224 * <p> 1225 * Only objects of type {@code OffsetTime} are compared, other types return false. 1226 * To compare the underlying local time of two {@code TemporalAccessor} instances, 1227 * use {@link ChronoField#NANO_OF_DAY} as a comparator. 1228 * 1229 * @param obj the object to check, null returns false 1230 * @return true if this is equal to the other time 1231 */ 1232 @Override equals(Object obj)1233 public boolean equals(Object obj) { 1234 if (this == obj) { 1235 return true; 1236 } 1237 if (obj instanceof OffsetTime) { 1238 OffsetTime other = (OffsetTime) obj; 1239 return time.equals(other.time) && offset.equals(other.offset); 1240 } 1241 return false; 1242 } 1243 1244 /** 1245 * A hash code for this time. 1246 * 1247 * @return a suitable hash code 1248 */ 1249 @Override hashCode()1250 public int hashCode() { 1251 return time.hashCode() ^ offset.hashCode(); 1252 } 1253 1254 //----------------------------------------------------------------------- 1255 /** 1256 * Outputs this time as a {@code String}, such as {@code 10:15:30+01:00}. 1257 * <p> 1258 * The output will be one of the following ISO-8601 formats: 1259 * <p><ul> 1260 * <li>{@code HH:mmXXXXX}</li> 1261 * <li>{@code HH:mm:ssXXXXX}</li> 1262 * <li>{@code HH:mm:ss.SSSXXXXX}</li> 1263 * <li>{@code HH:mm:ss.SSSSSSXXXXX}</li> 1264 * <li>{@code HH:mm:ss.SSSSSSSSSXXXXX}</li> 1265 * </ul><p> 1266 * The format used will be the shortest that outputs the full value of 1267 * the time where the omitted parts are implied to be zero. 1268 * 1269 * @return a string representation of this time, not null 1270 */ 1271 @Override toString()1272 public String toString() { 1273 return time.toString() + offset.toString(); 1274 } 1275 1276 /** 1277 * Outputs this time as a {@code String} using the formatter. 1278 * <p> 1279 * This time will be passed to the formatter 1280 * {@link DateTimeFormatter#format(TemporalAccessor) print method}. 1281 * 1282 * @param formatter the formatter to use, not null 1283 * @return the formatted time string, not null 1284 * @throws DateTimeException if an error occurs during printing 1285 */ format(DateTimeFormatter formatter)1286 public String format(DateTimeFormatter formatter) { 1287 Jdk8Methods.requireNonNull(formatter, "formatter"); 1288 return formatter.format(this); 1289 } 1290 1291 // ----------------------------------------------------------------------- writeReplace()1292 private Object writeReplace() { 1293 return new Ser(Ser.OFFSET_TIME_TYPE, this); 1294 } 1295 1296 /** 1297 * Defend against malicious streams. 1298 * @return never 1299 * @throws InvalidObjectException always 1300 */ readResolve()1301 private Object readResolve() throws ObjectStreamException { 1302 throw new InvalidObjectException("Deserialization via serialization delegate"); 1303 } 1304 writeExternal(DataOutput out)1305 void writeExternal(DataOutput out) throws IOException { 1306 time.writeExternal(out); 1307 offset.writeExternal(out); 1308 } 1309 readExternal(DataInput in)1310 static OffsetTime readExternal(DataInput in) throws IOException { 1311 LocalTime time = LocalTime.readExternal(in); 1312 ZoneOffset offset = ZoneOffset.readExternal(in); 1313 return OffsetTime.of(time, offset); 1314 } 1315 1316 } 1317