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