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