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