1 /* 2 * Copyright (c) 2012, 2015, 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_SECOND; 65 import static java.time.LocalTime.SECONDS_PER_DAY; 66 import static java.time.LocalTime.SECONDS_PER_HOUR; 67 import static java.time.LocalTime.SECONDS_PER_MINUTE; 68 import static java.time.temporal.ChronoField.INSTANT_SECONDS; 69 import static java.time.temporal.ChronoField.MICRO_OF_SECOND; 70 import static java.time.temporal.ChronoField.MILLI_OF_SECOND; 71 import static java.time.temporal.ChronoField.NANO_OF_SECOND; 72 import static java.time.temporal.ChronoUnit.DAYS; 73 import static java.time.temporal.ChronoUnit.NANOS; 74 75 import java.io.DataInput; 76 import java.io.DataOutput; 77 import java.io.IOException; 78 import java.io.InvalidObjectException; 79 import java.io.ObjectInputStream; 80 import java.io.Serializable; 81 import java.time.format.DateTimeFormatter; 82 import java.time.format.DateTimeParseException; 83 import java.time.temporal.ChronoField; 84 import java.time.temporal.ChronoUnit; 85 import java.time.temporal.Temporal; 86 import java.time.temporal.TemporalAccessor; 87 import java.time.temporal.TemporalAdjuster; 88 import java.time.temporal.TemporalAmount; 89 import java.time.temporal.TemporalField; 90 import java.time.temporal.TemporalQueries; 91 import java.time.temporal.TemporalQuery; 92 import java.time.temporal.TemporalUnit; 93 import java.time.temporal.UnsupportedTemporalTypeException; 94 import java.time.temporal.ValueRange; 95 import java.util.Objects; 96 97 // Android-changed: removed ValueBased paragraph. 98 /** 99 * An instantaneous point on the time-line. 100 * <p> 101 * This class models a single instantaneous point on the time-line. 102 * This might be used to record event time-stamps in the application. 103 * <p> 104 * The range of an instant requires the storage of a number larger than a {@code long}. 105 * To achieve this, the class stores a {@code long} representing epoch-seconds and an 106 * {@code int} representing nanosecond-of-second, which will always be between 0 and 999,999,999. 107 * The epoch-seconds are measured from the standard Java epoch of {@code 1970-01-01T00:00:00Z} 108 * where instants after the epoch have positive values, and earlier instants have negative values. 109 * For both the epoch-second and nanosecond parts, a larger value is always later on the time-line 110 * than a smaller value. 111 * 112 * <h3>Time-scale</h3> 113 * <p> 114 * The length of the solar day is the standard way that humans measure time. 115 * This has traditionally been subdivided into 24 hours of 60 minutes of 60 seconds, 116 * forming a 86400 second day. 117 * <p> 118 * Modern timekeeping is based on atomic clocks which precisely define an SI second 119 * relative to the transitions of a Caesium atom. The length of an SI second was defined 120 * to be very close to the 86400th fraction of a day. 121 * <p> 122 * Unfortunately, as the Earth rotates the length of the day varies. 123 * In addition, over time the average length of the day is getting longer as the Earth slows. 124 * As a result, the length of a solar day in 2012 is slightly longer than 86400 SI seconds. 125 * The actual length of any given day and the amount by which the Earth is slowing 126 * are not predictable and can only be determined by measurement. 127 * The UT1 time-scale captures the accurate length of day, but is only available some 128 * time after the day has completed. 129 * <p> 130 * The UTC time-scale is a standard approach to bundle up all the additional fractions 131 * of a second from UT1 into whole seconds, known as <i>leap-seconds</i>. 132 * A leap-second may be added or removed depending on the Earth's rotational changes. 133 * As such, UTC permits a day to have 86399 SI seconds or 86401 SI seconds where 134 * necessary in order to keep the day aligned with the Sun. 135 * <p> 136 * The modern UTC time-scale was introduced in 1972, introducing the concept of whole leap-seconds. 137 * Between 1958 and 1972, the definition of UTC was complex, with minor sub-second leaps and 138 * alterations to the length of the notional second. As of 2012, discussions are underway 139 * to change the definition of UTC again, with the potential to remove leap seconds or 140 * introduce other changes. 141 * <p> 142 * Given the complexity of accurate timekeeping described above, this Java API defines 143 * its own time-scale, the <i>Java Time-Scale</i>. 144 * <p> 145 * The Java Time-Scale divides each calendar day into exactly 86400 146 * subdivisions, known as seconds. These seconds may differ from the 147 * SI second. It closely matches the de facto international civil time 148 * scale, the definition of which changes from time to time. 149 * <p> 150 * The Java Time-Scale has slightly different definitions for different 151 * segments of the time-line, each based on the consensus international 152 * time scale that is used as the basis for civil time. Whenever the 153 * internationally-agreed time scale is modified or replaced, a new 154 * segment of the Java Time-Scale must be defined for it. Each segment 155 * must meet these requirements: 156 * <ul> 157 * <li>the Java Time-Scale shall closely match the underlying international 158 * civil time scale;</li> 159 * <li>the Java Time-Scale shall exactly match the international civil 160 * time scale at noon each day;</li> 161 * <li>the Java Time-Scale shall have a precisely-defined relationship to 162 * the international civil time scale.</li> 163 * </ul> 164 * There are currently, as of 2013, two segments in the Java time-scale. 165 * <p> 166 * For the segment from 1972-11-03 (exact boundary discussed below) until 167 * further notice, the consensus international time scale is UTC (with 168 * leap seconds). In this segment, the Java Time-Scale is identical to 169 * <a href="http://www.cl.cam.ac.uk/~mgk25/time/utc-sls/">UTC-SLS</a>. 170 * This is identical to UTC on days that do not have a leap second. 171 * On days that do have a leap second, the leap second is spread equally 172 * over the last 1000 seconds of the day, maintaining the appearance of 173 * exactly 86400 seconds per day. 174 * <p> 175 * For the segment prior to 1972-11-03, extending back arbitrarily far, 176 * the consensus international time scale is defined to be UT1, applied 177 * proleptically, which is equivalent to the (mean) solar time on the 178 * prime meridian (Greenwich). In this segment, the Java Time-Scale is 179 * identical to the consensus international time scale. The exact 180 * boundary between the two segments is the instant where UT1 = UTC 181 * between 1972-11-03T00:00 and 1972-11-04T12:00. 182 * <p> 183 * Implementations of the Java time-scale using the JSR-310 API are not 184 * required to provide any clock that is sub-second accurate, or that 185 * progresses monotonically or smoothly. Implementations are therefore 186 * not required to actually perform the UTC-SLS slew or to otherwise be 187 * aware of leap seconds. JSR-310 does, however, require that 188 * implementations must document the approach they use when defining a 189 * clock representing the current instant. 190 * See {@link Clock} for details on the available clocks. 191 * <p> 192 * The Java time-scale is used for all date-time classes. 193 * This includes {@code Instant}, {@code LocalDate}, {@code LocalTime}, {@code OffsetDateTime}, 194 * {@code ZonedDateTime} and {@code Duration}. 195 * 196 * @implSpec 197 * This class is immutable and thread-safe. 198 * 199 * @since 1.8 200 */ 201 public final class Instant 202 implements Temporal, TemporalAdjuster, Comparable<Instant>, Serializable { 203 204 /** 205 * Constant for the 1970-01-01T00:00:00Z epoch instant. 206 */ 207 public static final Instant EPOCH = new Instant(0, 0); 208 /** 209 * The minimum supported epoch second. 210 */ 211 private static final long MIN_SECOND = -31557014167219200L; 212 /** 213 * The maximum supported epoch second. 214 */ 215 private static final long MAX_SECOND = 31556889864403199L; 216 /** 217 * The minimum supported {@code Instant}, '-1000000000-01-01T00:00Z'. 218 * This could be used by an application as a "far past" instant. 219 * <p> 220 * This is one year earlier than the minimum {@code LocalDateTime}. 221 * This provides sufficient values to handle the range of {@code ZoneOffset} 222 * which affect the instant in addition to the local date-time. 223 * The value is also chosen such that the value of the year fits in 224 * an {@code int}. 225 */ 226 public static final Instant MIN = Instant.ofEpochSecond(MIN_SECOND, 0); 227 /** 228 * The maximum supported {@code Instant}, '1000000000-12-31T23:59:59.999999999Z'. 229 * This could be used by an application as a "far future" instant. 230 * <p> 231 * This is one year later than the maximum {@code LocalDateTime}. 232 * This provides sufficient values to handle the range of {@code ZoneOffset} 233 * which affect the instant in addition to the local date-time. 234 * The value is also chosen such that the value of the year fits in 235 * an {@code int}. 236 */ 237 public static final Instant MAX = Instant.ofEpochSecond(MAX_SECOND, 999_999_999); 238 239 /** 240 * Serialization version. 241 */ 242 private static final long serialVersionUID = -665713676816604388L; 243 244 /** 245 * The number of seconds from the epoch of 1970-01-01T00:00:00Z. 246 */ 247 private final long seconds; 248 /** 249 * The number of nanoseconds, later along the time-line, from the seconds field. 250 * This is always positive, and never exceeds 999,999,999. 251 */ 252 private final int nanos; 253 254 //----------------------------------------------------------------------- 255 /** 256 * Obtains the current instant from the system clock. 257 * <p> 258 * This will query the {@link Clock#systemUTC() system UTC clock} to 259 * obtain the current instant. 260 * <p> 261 * Using this method will prevent the ability to use an alternate time-source for 262 * testing because the clock is effectively hard-coded. 263 * 264 * @return the current instant using the system clock, not null 265 */ now()266 public static Instant now() { 267 return Clock.systemUTC().instant(); 268 } 269 270 /** 271 * Obtains the current instant from the specified clock. 272 * <p> 273 * This will query the specified clock to obtain the current time. 274 * <p> 275 * Using this method allows the use of an alternate clock for testing. 276 * The alternate clock may be introduced using {@link Clock dependency injection}. 277 * 278 * @param clock the clock to use, not null 279 * @return the current instant, not null 280 */ now(Clock clock)281 public static Instant now(Clock clock) { 282 Objects.requireNonNull(clock, "clock"); 283 return clock.instant(); 284 } 285 286 //----------------------------------------------------------------------- 287 /** 288 * Obtains an instance of {@code Instant} using seconds from the 289 * epoch of 1970-01-01T00:00:00Z. 290 * <p> 291 * The nanosecond field is set to zero. 292 * 293 * @param epochSecond the number of seconds from 1970-01-01T00:00:00Z 294 * @return an instant, not null 295 * @throws DateTimeException if the instant exceeds the maximum or minimum instant 296 */ ofEpochSecond(long epochSecond)297 public static Instant ofEpochSecond(long epochSecond) { 298 return create(epochSecond, 0); 299 } 300 301 /** 302 * Obtains an instance of {@code Instant} using seconds from the 303 * epoch of 1970-01-01T00:00:00Z and nanosecond fraction of second. 304 * <p> 305 * This method allows an arbitrary number of nanoseconds to be passed in. 306 * The factory will alter the values of the second and nanosecond in order 307 * to ensure that the stored nanosecond is in the range 0 to 999,999,999. 308 * For example, the following will result in the exactly the same instant: 309 * <pre> 310 * Instant.ofEpochSecond(3, 1); 311 * Instant.ofEpochSecond(4, -999_999_999); 312 * Instant.ofEpochSecond(2, 1000_000_001); 313 * </pre> 314 * 315 * @param epochSecond the number of seconds from 1970-01-01T00:00:00Z 316 * @param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative 317 * @return an instant, not null 318 * @throws DateTimeException if the instant exceeds the maximum or minimum instant 319 * @throws ArithmeticException if numeric overflow occurs 320 */ ofEpochSecond(long epochSecond, long nanoAdjustment)321 public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment) { 322 long secs = Math.addExact(epochSecond, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND)); 323 int nos = (int)Math.floorMod(nanoAdjustment, NANOS_PER_SECOND); 324 return create(secs, nos); 325 } 326 327 /** 328 * Obtains an instance of {@code Instant} using milliseconds from the 329 * epoch of 1970-01-01T00:00:00Z. 330 * <p> 331 * The seconds and nanoseconds are extracted from the specified milliseconds. 332 * 333 * @param epochMilli the number of milliseconds from 1970-01-01T00:00:00Z 334 * @return an instant, not null 335 * @throws DateTimeException if the instant exceeds the maximum or minimum instant 336 */ ofEpochMilli(long epochMilli)337 public static Instant ofEpochMilli(long epochMilli) { 338 long secs = Math.floorDiv(epochMilli, 1000); 339 int mos = (int)Math.floorMod(epochMilli, 1000); 340 return create(secs, mos * 1000_000); 341 } 342 343 //----------------------------------------------------------------------- 344 /** 345 * Obtains an instance of {@code Instant} from a temporal object. 346 * <p> 347 * This obtains an instant based on the specified temporal. 348 * A {@code TemporalAccessor} represents an arbitrary set of date and time information, 349 * which this factory converts to an instance of {@code Instant}. 350 * <p> 351 * The conversion extracts the {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS} 352 * and {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} fields. 353 * <p> 354 * This method matches the signature of the functional interface {@link TemporalQuery} 355 * allowing it to be used as a query via method reference, {@code Instant::from}. 356 * 357 * @param temporal the temporal object to convert, not null 358 * @return the instant, not null 359 * @throws DateTimeException if unable to convert to an {@code Instant} 360 */ from(TemporalAccessor temporal)361 public static Instant from(TemporalAccessor temporal) { 362 if (temporal instanceof Instant) { 363 return (Instant) temporal; 364 } 365 Objects.requireNonNull(temporal, "temporal"); 366 try { 367 long instantSecs = temporal.getLong(INSTANT_SECONDS); 368 int nanoOfSecond = temporal.get(NANO_OF_SECOND); 369 return Instant.ofEpochSecond(instantSecs, nanoOfSecond); 370 } catch (DateTimeException ex) { 371 throw new DateTimeException("Unable to obtain Instant from TemporalAccessor: " + 372 temporal + " of type " + temporal.getClass().getName(), ex); 373 } 374 } 375 376 //----------------------------------------------------------------------- 377 /** 378 * Obtains an instance of {@code Instant} from a text string such as 379 * {@code 2007-12-03T10:15:30.00Z}. 380 * <p> 381 * The string must represent a valid instant in UTC and is parsed using 382 * {@link DateTimeFormatter#ISO_INSTANT}. 383 * 384 * @param text the text to parse, not null 385 * @return the parsed instant, not null 386 * @throws DateTimeParseException if the text cannot be parsed 387 */ parse(final CharSequence text)388 public static Instant parse(final CharSequence text) { 389 return DateTimeFormatter.ISO_INSTANT.parse(text, Instant::from); 390 } 391 392 //----------------------------------------------------------------------- 393 /** 394 * Obtains an instance of {@code Instant} using seconds and nanoseconds. 395 * 396 * @param seconds the length of the duration in seconds 397 * @param nanoOfSecond the nano-of-second, from 0 to 999,999,999 398 * @throws DateTimeException if the instant exceeds the maximum or minimum instant 399 */ create(long seconds, int nanoOfSecond)400 private static Instant create(long seconds, int nanoOfSecond) { 401 if ((seconds | nanoOfSecond) == 0) { 402 return EPOCH; 403 } 404 if (seconds < MIN_SECOND || seconds > MAX_SECOND) { 405 throw new DateTimeException("Instant exceeds minimum or maximum instant"); 406 } 407 return new Instant(seconds, nanoOfSecond); 408 } 409 410 /** 411 * Constructs an instance of {@code Instant} using seconds from the epoch of 412 * 1970-01-01T00:00:00Z and nanosecond fraction of second. 413 * 414 * @param epochSecond the number of seconds from 1970-01-01T00:00:00Z 415 * @param nanos the nanoseconds within the second, must be positive 416 */ Instant(long epochSecond, int nanos)417 private Instant(long epochSecond, int nanos) { 418 super(); 419 this.seconds = epochSecond; 420 this.nanos = nanos; 421 } 422 423 //----------------------------------------------------------------------- 424 /** 425 * Checks if the specified field is supported. 426 * <p> 427 * This checks if this instant can be queried for the specified field. 428 * If false, then calling the {@link #range(TemporalField) range}, 429 * {@link #get(TemporalField) get} and {@link #with(TemporalField, long)} 430 * methods will throw an exception. 431 * <p> 432 * If the field is a {@link ChronoField} then the query is implemented here. 433 * The supported fields are: 434 * <ul> 435 * <li>{@code NANO_OF_SECOND} 436 * <li>{@code MICRO_OF_SECOND} 437 * <li>{@code MILLI_OF_SECOND} 438 * <li>{@code INSTANT_SECONDS} 439 * </ul> 440 * All other {@code ChronoField} instances will return false. 441 * <p> 442 * If the field is not a {@code ChronoField}, then the result of this method 443 * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)} 444 * passing {@code this} as the argument. 445 * Whether the field is supported is determined by the field. 446 * 447 * @param field the field to check, null returns false 448 * @return true if the field is supported on this instant, false if not 449 */ 450 @Override isSupported(TemporalField field)451 public boolean isSupported(TemporalField field) { 452 if (field instanceof ChronoField) { 453 return field == INSTANT_SECONDS || field == NANO_OF_SECOND || field == MICRO_OF_SECOND || field == MILLI_OF_SECOND; 454 } 455 return field != null && field.isSupportedBy(this); 456 } 457 458 /** 459 * Checks if the specified unit is supported. 460 * <p> 461 * This checks if the specified unit can be added to, or subtracted from, this date-time. 462 * If false, then calling the {@link #plus(long, TemporalUnit)} and 463 * {@link #minus(long, TemporalUnit) minus} methods will throw an exception. 464 * <p> 465 * If the unit is a {@link ChronoUnit} then the query is implemented here. 466 * The supported units are: 467 * <ul> 468 * <li>{@code NANOS} 469 * <li>{@code MICROS} 470 * <li>{@code MILLIS} 471 * <li>{@code SECONDS} 472 * <li>{@code MINUTES} 473 * <li>{@code HOURS} 474 * <li>{@code HALF_DAYS} 475 * <li>{@code DAYS} 476 * </ul> 477 * All other {@code ChronoUnit} instances will return false. 478 * <p> 479 * If the unit is not a {@code ChronoUnit}, then the result of this method 480 * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)} 481 * passing {@code this} as the argument. 482 * Whether the unit is supported is determined by the unit. 483 * 484 * @param unit the unit to check, null returns false 485 * @return true if the unit can be added/subtracted, false if not 486 */ 487 @Override isSupported(TemporalUnit unit)488 public boolean isSupported(TemporalUnit unit) { 489 if (unit instanceof ChronoUnit) { 490 return unit.isTimeBased() || unit == DAYS; 491 } 492 return unit != null && unit.isSupportedBy(this); 493 } 494 495 //----------------------------------------------------------------------- 496 /** 497 * Gets the range of valid values for the specified field. 498 * <p> 499 * The range object expresses the minimum and maximum valid values for a field. 500 * This instant is used to enhance the accuracy of the returned range. 501 * If it is not possible to return the range, because the field is not supported 502 * or for some other reason, an exception is thrown. 503 * <p> 504 * If the field is a {@link ChronoField} then the query is implemented here. 505 * The {@link #isSupported(TemporalField) supported fields} will return 506 * appropriate range instances. 507 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. 508 * <p> 509 * If the field is not a {@code ChronoField}, then the result of this method 510 * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)} 511 * passing {@code this} as the argument. 512 * Whether the range can be obtained is determined by the field. 513 * 514 * @param field the field to query the range for, not null 515 * @return the range of valid values for the field, not null 516 * @throws DateTimeException if the range for the field cannot be obtained 517 * @throws UnsupportedTemporalTypeException if the field is not supported 518 */ 519 @Override // override for Javadoc range(TemporalField field)520 public ValueRange range(TemporalField field) { 521 return Temporal.super.range(field); 522 } 523 524 /** 525 * Gets the value of the specified field from this instant as an {@code int}. 526 * <p> 527 * This queries this instant for the value of the specified field. 528 * The returned value will always be within the valid range of values for the field. 529 * If it is not possible to return the value, because the field is not supported 530 * or for some other reason, an exception is thrown. 531 * <p> 532 * If the field is a {@link ChronoField} then the query is implemented here. 533 * The {@link #isSupported(TemporalField) supported fields} will return valid 534 * values based on this date-time, except {@code INSTANT_SECONDS} which is too 535 * large to fit in an {@code int} and throws a {@code DateTimeException}. 536 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. 537 * <p> 538 * If the field is not a {@code ChronoField}, then the result of this method 539 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} 540 * passing {@code this} as the argument. Whether the value can be obtained, 541 * and what the value represents, is determined by the field. 542 * 543 * @param field the field to get, not null 544 * @return the value for the field 545 * @throws DateTimeException if a value for the field cannot be obtained or 546 * the value is outside the range of valid values for the field 547 * @throws UnsupportedTemporalTypeException if the field is not supported or 548 * the range of values exceeds an {@code int} 549 * @throws ArithmeticException if numeric overflow occurs 550 */ 551 @Override // override for Javadoc and performance get(TemporalField field)552 public int get(TemporalField field) { 553 if (field instanceof ChronoField) { 554 switch ((ChronoField) field) { 555 case NANO_OF_SECOND: return nanos; 556 case MICRO_OF_SECOND: return nanos / 1000; 557 case MILLI_OF_SECOND: return nanos / 1000_000; 558 case INSTANT_SECONDS: INSTANT_SECONDS.checkValidIntValue(seconds); 559 } 560 throw new UnsupportedTemporalTypeException("Unsupported field: " + field); 561 } 562 return range(field).checkValidIntValue(field.getFrom(this), field); 563 } 564 565 /** 566 * Gets the value of the specified field from this instant as a {@code long}. 567 * <p> 568 * This queries this instant for the value of the specified field. 569 * If it is not possible to return the value, because the field is not supported 570 * or for some other reason, an exception is thrown. 571 * <p> 572 * If the field is a {@link ChronoField} then the query is implemented here. 573 * The {@link #isSupported(TemporalField) supported fields} will return valid 574 * values based on this date-time. 575 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. 576 * <p> 577 * If the field is not a {@code ChronoField}, then the result of this method 578 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} 579 * passing {@code this} as the argument. Whether the value can be obtained, 580 * and what the value represents, is determined by the field. 581 * 582 * @param field the field to get, not null 583 * @return the value for the field 584 * @throws DateTimeException if a value for the field cannot be obtained 585 * @throws UnsupportedTemporalTypeException if the field is not supported 586 * @throws ArithmeticException if numeric overflow occurs 587 */ 588 @Override getLong(TemporalField field)589 public long getLong(TemporalField field) { 590 if (field instanceof ChronoField) { 591 switch ((ChronoField) field) { 592 case NANO_OF_SECOND: return nanos; 593 case MICRO_OF_SECOND: return nanos / 1000; 594 case MILLI_OF_SECOND: return nanos / 1000_000; 595 case INSTANT_SECONDS: return seconds; 596 } 597 throw new UnsupportedTemporalTypeException("Unsupported field: " + field); 598 } 599 return field.getFrom(this); 600 } 601 602 //----------------------------------------------------------------------- 603 /** 604 * Gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z. 605 * <p> 606 * The epoch second count is a simple incrementing count of seconds where 607 * second 0 is 1970-01-01T00:00:00Z. 608 * The nanosecond part of the day is returned by {@code getNanosOfSecond}. 609 * 610 * @return the seconds from the epoch of 1970-01-01T00:00:00Z 611 */ getEpochSecond()612 public long getEpochSecond() { 613 return seconds; 614 } 615 616 /** 617 * Gets the number of nanoseconds, later along the time-line, from the start 618 * of the second. 619 * <p> 620 * The nanosecond-of-second value measures the total number of nanoseconds from 621 * the second returned by {@code getEpochSecond}. 622 * 623 * @return the nanoseconds within the second, always positive, never exceeds 999,999,999 624 */ getNano()625 public int getNano() { 626 return nanos; 627 } 628 629 //------------------------------------------------------------------------- 630 /** 631 * Returns an adjusted copy of this instant. 632 * <p> 633 * This returns an {@code Instant}, based on this one, with the instant adjusted. 634 * The adjustment takes place using the specified adjuster strategy object. 635 * Read the documentation of the adjuster to understand what adjustment will be made. 636 * <p> 637 * The result of this method is obtained by invoking the 638 * {@link TemporalAdjuster#adjustInto(Temporal)} method on the 639 * specified adjuster passing {@code this} as the argument. 640 * <p> 641 * This instance is immutable and unaffected by this method call. 642 * 643 * @param adjuster the adjuster to use, not null 644 * @return an {@code Instant} based on {@code this} with the adjustment made, not null 645 * @throws DateTimeException if the adjustment cannot be made 646 * @throws ArithmeticException if numeric overflow occurs 647 */ 648 @Override with(TemporalAdjuster adjuster)649 public Instant with(TemporalAdjuster adjuster) { 650 return (Instant) adjuster.adjustInto(this); 651 } 652 653 /** 654 * Returns a copy of this instant with the specified field set to a new value. 655 * <p> 656 * This returns an {@code Instant}, based on this one, with the value 657 * for the specified field changed. 658 * If it is not possible to set the value, because the field is not supported or for 659 * some other reason, an exception is thrown. 660 * <p> 661 * If the field is a {@link ChronoField} then the adjustment is implemented here. 662 * The supported fields behave as follows: 663 * <ul> 664 * <li>{@code NANO_OF_SECOND} - 665 * Returns an {@code Instant} with the specified nano-of-second. 666 * The epoch-second will be unchanged. 667 * <li>{@code MICRO_OF_SECOND} - 668 * Returns an {@code Instant} with the nano-of-second replaced by the specified 669 * micro-of-second multiplied by 1,000. The epoch-second will be unchanged. 670 * <li>{@code MILLI_OF_SECOND} - 671 * Returns an {@code Instant} with the nano-of-second replaced by the specified 672 * milli-of-second multiplied by 1,000,000. The epoch-second will be unchanged. 673 * <li>{@code INSTANT_SECONDS} - 674 * Returns an {@code Instant} with the specified epoch-second. 675 * The nano-of-second will be unchanged. 676 * </ul> 677 * <p> 678 * In all cases, if the new value is outside the valid range of values for the field 679 * then a {@code DateTimeException} will be thrown. 680 * <p> 681 * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. 682 * <p> 683 * If the field is not a {@code ChronoField}, then the result of this method 684 * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)} 685 * passing {@code this} as the argument. In this case, the field determines 686 * whether and how to adjust the instant. 687 * <p> 688 * This instance is immutable and unaffected by this method call. 689 * 690 * @param field the field to set in the result, not null 691 * @param newValue the new value of the field in the result 692 * @return an {@code Instant} based on {@code this} with the specified field set, not null 693 * @throws DateTimeException if the field cannot be set 694 * @throws UnsupportedTemporalTypeException if the field is not supported 695 * @throws ArithmeticException if numeric overflow occurs 696 */ 697 @Override with(TemporalField field, long newValue)698 public Instant with(TemporalField field, long newValue) { 699 if (field instanceof ChronoField) { 700 ChronoField f = (ChronoField) field; 701 f.checkValidValue(newValue); 702 switch (f) { 703 case MILLI_OF_SECOND: { 704 int nval = (int) newValue * 1000_000; 705 return (nval != nanos ? create(seconds, nval) : this); 706 } 707 case MICRO_OF_SECOND: { 708 int nval = (int) newValue * 1000; 709 return (nval != nanos ? create(seconds, nval) : this); 710 } 711 case NANO_OF_SECOND: return (newValue != nanos ? create(seconds, (int) newValue) : this); 712 case INSTANT_SECONDS: return (newValue != seconds ? create(newValue, nanos) : this); 713 } 714 throw new UnsupportedTemporalTypeException("Unsupported field: " + field); 715 } 716 return field.adjustInto(this, newValue); 717 } 718 719 //----------------------------------------------------------------------- 720 /** 721 * Returns a copy of this {@code Instant} truncated to the specified unit. 722 * <p> 723 * Truncating the instant returns a copy of the original with fields 724 * smaller than the specified unit set to zero. 725 * The fields are calculated on the basis of using a UTC offset as seen 726 * in {@code toString}. 727 * For example, truncating with the {@link ChronoUnit#MINUTES MINUTES} unit will 728 * round down to the nearest minute, setting the seconds and nanoseconds to zero. 729 * <p> 730 * The unit must have a {@linkplain TemporalUnit#getDuration() duration} 731 * that divides into the length of a standard day without remainder. 732 * This includes all supplied time units on {@link ChronoUnit} and 733 * {@link ChronoUnit#DAYS DAYS}. Other units throw an exception. 734 * <p> 735 * This instance is immutable and unaffected by this method call. 736 * 737 * @param unit the unit to truncate to, not null 738 * @return an {@code Instant} based on this instant with the time truncated, not null 739 * @throws DateTimeException if the unit is invalid for truncation 740 * @throws UnsupportedTemporalTypeException if the unit is not supported 741 */ truncatedTo(TemporalUnit unit)742 public Instant truncatedTo(TemporalUnit unit) { 743 if (unit == ChronoUnit.NANOS) { 744 return this; 745 } 746 Duration unitDur = unit.getDuration(); 747 if (unitDur.getSeconds() > LocalTime.SECONDS_PER_DAY) { 748 throw new UnsupportedTemporalTypeException("Unit is too large to be used for truncation"); 749 } 750 long dur = unitDur.toNanos(); 751 if ((LocalTime.NANOS_PER_DAY % dur) != 0) { 752 throw new UnsupportedTemporalTypeException("Unit must divide into a standard day without remainder"); 753 } 754 long nod = (seconds % LocalTime.SECONDS_PER_DAY) * LocalTime.NANOS_PER_SECOND + nanos; 755 long result = (nod / dur) * dur; 756 return plusNanos(result - nod); 757 } 758 759 //----------------------------------------------------------------------- 760 /** 761 * Returns a copy of this instant with the specified amount added. 762 * <p> 763 * This returns an {@code Instant}, based on this one, with the specified amount added. 764 * The amount is typically {@link Duration} but may be any other type implementing 765 * the {@link TemporalAmount} interface. 766 * <p> 767 * The calculation is delegated to the amount object by calling 768 * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free 769 * to implement the addition in any way it wishes, however it typically 770 * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation 771 * of the amount implementation to determine if it can be successfully added. 772 * <p> 773 * This instance is immutable and unaffected by this method call. 774 * 775 * @param amountToAdd the amount to add, not null 776 * @return an {@code Instant} based on this instant with the addition made, not null 777 * @throws DateTimeException if the addition cannot be made 778 * @throws ArithmeticException if numeric overflow occurs 779 */ 780 @Override plus(TemporalAmount amountToAdd)781 public Instant plus(TemporalAmount amountToAdd) { 782 return (Instant) amountToAdd.addTo(this); 783 } 784 785 /** 786 * Returns a copy of this instant with the specified amount added. 787 * <p> 788 * This returns an {@code Instant}, based on this one, with the amount 789 * in terms of the unit added. If it is not possible to add the amount, because the 790 * unit is not supported or for some other reason, an exception is thrown. 791 * <p> 792 * If the field is a {@link ChronoUnit} then the addition is implemented here. 793 * The supported fields behave as follows: 794 * <ul> 795 * <li>{@code NANOS} - 796 * Returns a {@code Instant} with the specified number of nanoseconds added. 797 * This is equivalent to {@link #plusNanos(long)}. 798 * <li>{@code MICROS} - 799 * Returns a {@code Instant} with the specified number of microseconds added. 800 * This is equivalent to {@link #plusNanos(long)} with the amount 801 * multiplied by 1,000. 802 * <li>{@code MILLIS} - 803 * Returns a {@code Instant} with the specified number of milliseconds added. 804 * This is equivalent to {@link #plusNanos(long)} with the amount 805 * multiplied by 1,000,000. 806 * <li>{@code SECONDS} - 807 * Returns a {@code Instant} with the specified number of seconds added. 808 * This is equivalent to {@link #plusSeconds(long)}. 809 * <li>{@code MINUTES} - 810 * Returns a {@code Instant} with the specified number of minutes added. 811 * This is equivalent to {@link #plusSeconds(long)} with the amount 812 * multiplied by 60. 813 * <li>{@code HOURS} - 814 * Returns a {@code Instant} with the specified number of hours added. 815 * This is equivalent to {@link #plusSeconds(long)} with the amount 816 * multiplied by 3,600. 817 * <li>{@code HALF_DAYS} - 818 * Returns a {@code Instant} with the specified number of half-days added. 819 * This is equivalent to {@link #plusSeconds(long)} with the amount 820 * multiplied by 43,200 (12 hours). 821 * <li>{@code DAYS} - 822 * Returns a {@code Instant} with the specified number of days added. 823 * This is equivalent to {@link #plusSeconds(long)} with the amount 824 * multiplied by 86,400 (24 hours). 825 * </ul> 826 * <p> 827 * All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}. 828 * <p> 829 * If the field is not a {@code ChronoUnit}, then the result of this method 830 * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)} 831 * passing {@code this} as the argument. In this case, the unit determines 832 * whether and how to perform the addition. 833 * <p> 834 * This instance is immutable and unaffected by this method call. 835 * 836 * @param amountToAdd the amount of the unit to add to the result, may be negative 837 * @param unit the unit of the amount to add, not null 838 * @return an {@code Instant} based on this instant with the specified amount added, not null 839 * @throws DateTimeException if the addition cannot be made 840 * @throws UnsupportedTemporalTypeException if the unit is not supported 841 * @throws ArithmeticException if numeric overflow occurs 842 */ 843 @Override plus(long amountToAdd, TemporalUnit unit)844 public Instant plus(long amountToAdd, TemporalUnit unit) { 845 if (unit instanceof ChronoUnit) { 846 switch ((ChronoUnit) unit) { 847 case NANOS: return plusNanos(amountToAdd); 848 case MICROS: return plus(amountToAdd / 1000_000, (amountToAdd % 1000_000) * 1000); 849 case MILLIS: return plusMillis(amountToAdd); 850 case SECONDS: return plusSeconds(amountToAdd); 851 case MINUTES: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_MINUTE)); 852 case HOURS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_HOUR)); 853 case HALF_DAYS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY / 2)); 854 case DAYS: return plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY)); 855 } 856 throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); 857 } 858 return unit.addTo(this, amountToAdd); 859 } 860 861 //----------------------------------------------------------------------- 862 /** 863 * Returns a copy of this instant with the specified duration in seconds added. 864 * <p> 865 * This instance is immutable and unaffected by this method call. 866 * 867 * @param secondsToAdd the seconds to add, positive or negative 868 * @return an {@code Instant} based on this instant with the specified seconds added, not null 869 * @throws DateTimeException if the result exceeds the maximum or minimum instant 870 * @throws ArithmeticException if numeric overflow occurs 871 */ plusSeconds(long secondsToAdd)872 public Instant plusSeconds(long secondsToAdd) { 873 return plus(secondsToAdd, 0); 874 } 875 876 /** 877 * Returns a copy of this instant with the specified duration in milliseconds added. 878 * <p> 879 * This instance is immutable and unaffected by this method call. 880 * 881 * @param millisToAdd the milliseconds to add, positive or negative 882 * @return an {@code Instant} based on this instant with the specified milliseconds added, not null 883 * @throws DateTimeException if the result exceeds the maximum or minimum instant 884 * @throws ArithmeticException if numeric overflow occurs 885 */ plusMillis(long millisToAdd)886 public Instant plusMillis(long millisToAdd) { 887 return plus(millisToAdd / 1000, (millisToAdd % 1000) * 1000_000); 888 } 889 890 /** 891 * Returns a copy of this instant with the specified duration in nanoseconds added. 892 * <p> 893 * This instance is immutable and unaffected by this method call. 894 * 895 * @param nanosToAdd the nanoseconds to add, positive or negative 896 * @return an {@code Instant} based on this instant with the specified nanoseconds added, not null 897 * @throws DateTimeException if the result exceeds the maximum or minimum instant 898 * @throws ArithmeticException if numeric overflow occurs 899 */ plusNanos(long nanosToAdd)900 public Instant plusNanos(long nanosToAdd) { 901 return plus(0, nanosToAdd); 902 } 903 904 /** 905 * Returns a copy of this instant with the specified duration added. 906 * <p> 907 * This instance is immutable and unaffected by this method call. 908 * 909 * @param secondsToAdd the seconds to add, positive or negative 910 * @param nanosToAdd the nanos to add, positive or negative 911 * @return an {@code Instant} based on this instant with the specified seconds added, not null 912 * @throws DateTimeException if the result exceeds the maximum or minimum instant 913 * @throws ArithmeticException if numeric overflow occurs 914 */ plus(long secondsToAdd, long nanosToAdd)915 private Instant plus(long secondsToAdd, long nanosToAdd) { 916 if ((secondsToAdd | nanosToAdd) == 0) { 917 return this; 918 } 919 long epochSec = Math.addExact(seconds, secondsToAdd); 920 epochSec = Math.addExact(epochSec, nanosToAdd / NANOS_PER_SECOND); 921 nanosToAdd = nanosToAdd % NANOS_PER_SECOND; 922 long nanoAdjustment = nanos + nanosToAdd; // safe int+NANOS_PER_SECOND 923 return ofEpochSecond(epochSec, nanoAdjustment); 924 } 925 926 //----------------------------------------------------------------------- 927 /** 928 * Returns a copy of this instant with the specified amount subtracted. 929 * <p> 930 * This returns an {@code Instant}, based on this one, with the specified amount subtracted. 931 * The amount is typically {@link Duration} but may be any other type implementing 932 * the {@link TemporalAmount} interface. 933 * <p> 934 * The calculation is delegated to the amount object by calling 935 * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free 936 * to implement the subtraction in any way it wishes, however it typically 937 * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation 938 * of the amount implementation to determine if it can be successfully subtracted. 939 * <p> 940 * This instance is immutable and unaffected by this method call. 941 * 942 * @param amountToSubtract the amount to subtract, not null 943 * @return an {@code Instant} based on this instant with the subtraction made, not null 944 * @throws DateTimeException if the subtraction cannot be made 945 * @throws ArithmeticException if numeric overflow occurs 946 */ 947 @Override minus(TemporalAmount amountToSubtract)948 public Instant minus(TemporalAmount amountToSubtract) { 949 return (Instant) amountToSubtract.subtractFrom(this); 950 } 951 952 /** 953 * Returns a copy of this instant with the specified amount subtracted. 954 * <p> 955 * This returns a {@code Instant}, based on this one, with the amount 956 * in terms of the unit subtracted. If it is not possible to subtract the amount, 957 * because the unit is not supported or for some other reason, an exception is thrown. 958 * <p> 959 * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated. 960 * See that method for a full description of how addition, and thus subtraction, works. 961 * <p> 962 * This instance is immutable and unaffected by this method call. 963 * 964 * @param amountToSubtract the amount of the unit to subtract from the result, may be negative 965 * @param unit the unit of the amount to subtract, not null 966 * @return an {@code Instant} based on this instant with the specified amount subtracted, not null 967 * @throws DateTimeException if the subtraction cannot be made 968 * @throws UnsupportedTemporalTypeException if the unit is not supported 969 * @throws ArithmeticException if numeric overflow occurs 970 */ 971 @Override minus(long amountToSubtract, TemporalUnit unit)972 public Instant minus(long amountToSubtract, TemporalUnit unit) { 973 return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit)); 974 } 975 976 //----------------------------------------------------------------------- 977 /** 978 * Returns a copy of this instant with the specified duration in seconds subtracted. 979 * <p> 980 * This instance is immutable and unaffected by this method call. 981 * 982 * @param secondsToSubtract the seconds to subtract, positive or negative 983 * @return an {@code Instant} based on this instant with the specified seconds subtracted, not null 984 * @throws DateTimeException if the result exceeds the maximum or minimum instant 985 * @throws ArithmeticException if numeric overflow occurs 986 */ minusSeconds(long secondsToSubtract)987 public Instant minusSeconds(long secondsToSubtract) { 988 if (secondsToSubtract == Long.MIN_VALUE) { 989 return plusSeconds(Long.MAX_VALUE).plusSeconds(1); 990 } 991 return plusSeconds(-secondsToSubtract); 992 } 993 994 /** 995 * Returns a copy of this instant with the specified duration in milliseconds subtracted. 996 * <p> 997 * This instance is immutable and unaffected by this method call. 998 * 999 * @param millisToSubtract the milliseconds to subtract, positive or negative 1000 * @return an {@code Instant} based on this instant with the specified milliseconds subtracted, not null 1001 * @throws DateTimeException if the result exceeds the maximum or minimum instant 1002 * @throws ArithmeticException if numeric overflow occurs 1003 */ minusMillis(long millisToSubtract)1004 public Instant minusMillis(long millisToSubtract) { 1005 if (millisToSubtract == Long.MIN_VALUE) { 1006 return plusMillis(Long.MAX_VALUE).plusMillis(1); 1007 } 1008 return plusMillis(-millisToSubtract); 1009 } 1010 1011 /** 1012 * Returns a copy of this instant with the specified duration in nanoseconds subtracted. 1013 * <p> 1014 * This instance is immutable and unaffected by this method call. 1015 * 1016 * @param nanosToSubtract the nanoseconds to subtract, positive or negative 1017 * @return an {@code Instant} based on this instant with the specified nanoseconds subtracted, not null 1018 * @throws DateTimeException if the result exceeds the maximum or minimum instant 1019 * @throws ArithmeticException if numeric overflow occurs 1020 */ minusNanos(long nanosToSubtract)1021 public Instant minusNanos(long nanosToSubtract) { 1022 if (nanosToSubtract == Long.MIN_VALUE) { 1023 return plusNanos(Long.MAX_VALUE).plusNanos(1); 1024 } 1025 return plusNanos(-nanosToSubtract); 1026 } 1027 1028 //------------------------------------------------------------------------- 1029 /** 1030 * Queries this instant using the specified query. 1031 * <p> 1032 * This queries this instant using the specified query strategy object. 1033 * The {@code TemporalQuery} object defines the logic to be used to 1034 * obtain the result. Read the documentation of the query to understand 1035 * what the result of this method will be. 1036 * <p> 1037 * The result of this method is obtained by invoking the 1038 * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the 1039 * specified query passing {@code this} as the argument. 1040 * 1041 * @param <R> the type of the result 1042 * @param query the query to invoke, not null 1043 * @return the query result, null may be returned (defined by the query) 1044 * @throws DateTimeException if unable to query (defined by the query) 1045 * @throws ArithmeticException if numeric overflow occurs (defined by the query) 1046 */ 1047 @SuppressWarnings("unchecked") 1048 @Override query(TemporalQuery<R> query)1049 public <R> R query(TemporalQuery<R> query) { 1050 if (query == TemporalQueries.precision()) { 1051 return (R) NANOS; 1052 } 1053 // inline TemporalAccessor.super.query(query) as an optimization 1054 if (query == TemporalQueries.chronology() || query == TemporalQueries.zoneId() || 1055 query == TemporalQueries.zone() || query == TemporalQueries.offset() || 1056 query == TemporalQueries.localDate() || query == TemporalQueries.localTime()) { 1057 return null; 1058 } 1059 return query.queryFrom(this); 1060 } 1061 1062 /** 1063 * Adjusts the specified temporal object to have this instant. 1064 * <p> 1065 * This returns a temporal object of the same observable type as the input 1066 * with the instant changed to be the same as this. 1067 * <p> 1068 * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)} 1069 * twice, passing {@link ChronoField#INSTANT_SECONDS} and 1070 * {@link ChronoField#NANO_OF_SECOND} as the fields. 1071 * <p> 1072 * In most cases, it is clearer to reverse the calling pattern by using 1073 * {@link Temporal#with(TemporalAdjuster)}: 1074 * <pre> 1075 * // these two lines are equivalent, but the second approach is recommended 1076 * temporal = thisInstant.adjustInto(temporal); 1077 * temporal = temporal.with(thisInstant); 1078 * </pre> 1079 * <p> 1080 * This instance is immutable and unaffected by this method call. 1081 * 1082 * @param temporal the target object to be adjusted, not null 1083 * @return the adjusted object, not null 1084 * @throws DateTimeException if unable to make the adjustment 1085 * @throws ArithmeticException if numeric overflow occurs 1086 */ 1087 @Override adjustInto(Temporal temporal)1088 public Temporal adjustInto(Temporal temporal) { 1089 return temporal.with(INSTANT_SECONDS, seconds).with(NANO_OF_SECOND, nanos); 1090 } 1091 1092 /** 1093 * Calculates the amount of time until another instant in terms of the specified unit. 1094 * <p> 1095 * This calculates the amount of time between two {@code Instant} 1096 * objects in terms of a single {@code TemporalUnit}. 1097 * The start and end points are {@code this} and the specified instant. 1098 * The result will be negative if the end is before the start. 1099 * The calculation returns a whole number, representing the number of 1100 * complete units between the two instants. 1101 * The {@code Temporal} passed to this method is converted to a 1102 * {@code Instant} using {@link #from(TemporalAccessor)}. 1103 * For example, the amount in days between two dates can be calculated 1104 * using {@code startInstant.until(endInstant, SECONDS)}. 1105 * <p> 1106 * There are two equivalent ways of using this method. 1107 * The first is to invoke this method. 1108 * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}: 1109 * <pre> 1110 * // these two lines are equivalent 1111 * amount = start.until(end, SECONDS); 1112 * amount = SECONDS.between(start, end); 1113 * </pre> 1114 * The choice should be made based on which makes the code more readable. 1115 * <p> 1116 * The calculation is implemented in this method for {@link ChronoUnit}. 1117 * The units {@code NANOS}, {@code MICROS}, {@code MILLIS}, {@code SECONDS}, 1118 * {@code MINUTES}, {@code HOURS}, {@code HALF_DAYS} and {@code DAYS} 1119 * are supported. Other {@code ChronoUnit} values will throw an exception. 1120 * <p> 1121 * If the unit is not a {@code ChronoUnit}, then the result of this method 1122 * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)} 1123 * passing {@code this} as the first argument and the converted input temporal 1124 * as the second argument. 1125 * <p> 1126 * This instance is immutable and unaffected by this method call. 1127 * 1128 * @param endExclusive the end date, exclusive, which is converted to an {@code Instant}, not null 1129 * @param unit the unit to measure the amount in, not null 1130 * @return the amount of time between this instant and the end instant 1131 * @throws DateTimeException if the amount cannot be calculated, or the end 1132 * temporal cannot be converted to an {@code Instant} 1133 * @throws UnsupportedTemporalTypeException if the unit is not supported 1134 * @throws ArithmeticException if numeric overflow occurs 1135 */ 1136 @Override until(Temporal endExclusive, TemporalUnit unit)1137 public long until(Temporal endExclusive, TemporalUnit unit) { 1138 Instant end = Instant.from(endExclusive); 1139 if (unit instanceof ChronoUnit) { 1140 ChronoUnit f = (ChronoUnit) unit; 1141 switch (f) { 1142 case NANOS: return nanosUntil(end); 1143 case MICROS: return nanosUntil(end) / 1000; 1144 case MILLIS: return Math.subtractExact(end.toEpochMilli(), toEpochMilli()); 1145 case SECONDS: return secondsUntil(end); 1146 case MINUTES: return secondsUntil(end) / SECONDS_PER_MINUTE; 1147 case HOURS: return secondsUntil(end) / SECONDS_PER_HOUR; 1148 case HALF_DAYS: return secondsUntil(end) / (12 * SECONDS_PER_HOUR); 1149 case DAYS: return secondsUntil(end) / (SECONDS_PER_DAY); 1150 } 1151 throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); 1152 } 1153 return unit.between(this, end); 1154 } 1155 nanosUntil(Instant end)1156 private long nanosUntil(Instant end) { 1157 long secsDiff = Math.subtractExact(end.seconds, seconds); 1158 long totalNanos = Math.multiplyExact(secsDiff, NANOS_PER_SECOND); 1159 return Math.addExact(totalNanos, end.nanos - nanos); 1160 } 1161 secondsUntil(Instant end)1162 private long secondsUntil(Instant end) { 1163 long secsDiff = Math.subtractExact(end.seconds, seconds); 1164 long nanosDiff = end.nanos - nanos; 1165 if (secsDiff > 0 && nanosDiff < 0) { 1166 secsDiff--; 1167 } else if (secsDiff < 0 && nanosDiff > 0) { 1168 secsDiff++; 1169 } 1170 return secsDiff; 1171 } 1172 1173 //----------------------------------------------------------------------- 1174 /** 1175 * Combines this instant with an offset to create an {@code OffsetDateTime}. 1176 * <p> 1177 * This returns an {@code OffsetDateTime} formed from this instant at the 1178 * specified offset from UTC/Greenwich. An exception will be thrown if the 1179 * instant is too large to fit into an offset date-time. 1180 * <p> 1181 * This method is equivalent to 1182 * {@link OffsetDateTime#ofInstant(Instant, ZoneId) OffsetDateTime.ofInstant(this, offset)}. 1183 * 1184 * @param offset the offset to combine with, not null 1185 * @return the offset date-time formed from this instant and the specified offset, not null 1186 * @throws DateTimeException if the result exceeds the supported range 1187 */ atOffset(ZoneOffset offset)1188 public OffsetDateTime atOffset(ZoneOffset offset) { 1189 return OffsetDateTime.ofInstant(this, offset); 1190 } 1191 1192 /** 1193 * Combines this instant with a time-zone to create a {@code ZonedDateTime}. 1194 * <p> 1195 * This returns an {@code ZonedDateTime} formed from this instant at the 1196 * specified time-zone. An exception will be thrown if the instant is too 1197 * large to fit into a zoned date-time. 1198 * <p> 1199 * This method is equivalent to 1200 * {@link ZonedDateTime#ofInstant(Instant, ZoneId) ZonedDateTime.ofInstant(this, zone)}. 1201 * 1202 * @param zone the zone to combine with, not null 1203 * @return the zoned date-time formed from this instant and the specified zone, not null 1204 * @throws DateTimeException if the result exceeds the supported range 1205 */ atZone(ZoneId zone)1206 public ZonedDateTime atZone(ZoneId zone) { 1207 return ZonedDateTime.ofInstant(this, zone); 1208 } 1209 1210 //----------------------------------------------------------------------- 1211 /** 1212 * Converts this instant to the number of milliseconds from the epoch 1213 * of 1970-01-01T00:00:00Z. 1214 * <p> 1215 * If this instant represents a point on the time-line too far in the future 1216 * or past to fit in a {@code long} milliseconds, then an exception is thrown. 1217 * <p> 1218 * If this instant has greater than millisecond precision, then the conversion 1219 * will drop any excess precision information as though the amount in nanoseconds 1220 * was subject to integer division by one million. 1221 * 1222 * @return the number of milliseconds since the epoch of 1970-01-01T00:00:00Z 1223 * @throws ArithmeticException if numeric overflow occurs 1224 */ toEpochMilli()1225 public long toEpochMilli() { 1226 if (seconds < 0 && nanos > 0) { 1227 long millis = Math.multiplyExact(seconds+1, 1000); 1228 long adjustment = nanos / 1000_000 - 1000; 1229 return Math.addExact(millis, adjustment); 1230 } else { 1231 long millis = Math.multiplyExact(seconds, 1000); 1232 return Math.addExact(millis, nanos / 1000_000); 1233 } 1234 } 1235 1236 //----------------------------------------------------------------------- 1237 /** 1238 * Compares this instant to the specified instant. 1239 * <p> 1240 * The comparison is based on the time-line position of the instants. 1241 * It is "consistent with equals", as defined by {@link Comparable}. 1242 * 1243 * @param otherInstant the other instant to compare to, not null 1244 * @return the comparator value, negative if less, positive if greater 1245 * @throws NullPointerException if otherInstant is null 1246 */ 1247 @Override compareTo(Instant otherInstant)1248 public int compareTo(Instant otherInstant) { 1249 int cmp = Long.compare(seconds, otherInstant.seconds); 1250 if (cmp != 0) { 1251 return cmp; 1252 } 1253 return nanos - otherInstant.nanos; 1254 } 1255 1256 /** 1257 * Checks if this instant is after the specified instant. 1258 * <p> 1259 * The comparison is based on the time-line position of the instants. 1260 * 1261 * @param otherInstant the other instant to compare to, not null 1262 * @return true if this instant is after the specified instant 1263 * @throws NullPointerException if otherInstant is null 1264 */ isAfter(Instant otherInstant)1265 public boolean isAfter(Instant otherInstant) { 1266 return compareTo(otherInstant) > 0; 1267 } 1268 1269 /** 1270 * Checks if this instant is before the specified instant. 1271 * <p> 1272 * The comparison is based on the time-line position of the instants. 1273 * 1274 * @param otherInstant the other instant to compare to, not null 1275 * @return true if this instant is before the specified instant 1276 * @throws NullPointerException if otherInstant is null 1277 */ isBefore(Instant otherInstant)1278 public boolean isBefore(Instant otherInstant) { 1279 return compareTo(otherInstant) < 0; 1280 } 1281 1282 //----------------------------------------------------------------------- 1283 /** 1284 * Checks if this instant is equal to the specified instant. 1285 * <p> 1286 * The comparison is based on the time-line position of the instants. 1287 * 1288 * @param otherInstant the other instant, null returns false 1289 * @return true if the other instant is equal to this one 1290 */ 1291 @Override equals(Object otherInstant)1292 public boolean equals(Object otherInstant) { 1293 if (this == otherInstant) { 1294 return true; 1295 } 1296 if (otherInstant instanceof Instant) { 1297 Instant other = (Instant) otherInstant; 1298 return this.seconds == other.seconds && 1299 this.nanos == other.nanos; 1300 } 1301 return false; 1302 } 1303 1304 /** 1305 * Returns a hash code for this instant. 1306 * 1307 * @return a suitable hash code 1308 */ 1309 @Override hashCode()1310 public int hashCode() { 1311 return ((int) (seconds ^ (seconds >>> 32))) + 51 * nanos; 1312 } 1313 1314 //----------------------------------------------------------------------- 1315 /** 1316 * A string representation of this instant using ISO-8601 representation. 1317 * <p> 1318 * The format used is the same as {@link DateTimeFormatter#ISO_INSTANT}. 1319 * 1320 * @return an ISO-8601 representation of this instant, not null 1321 */ 1322 @Override toString()1323 public String toString() { 1324 return DateTimeFormatter.ISO_INSTANT.format(this); 1325 } 1326 1327 // ----------------------------------------------------------------------- 1328 /** 1329 * Writes the object using a 1330 * <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>. 1331 * @serialData 1332 * <pre> 1333 * out.writeByte(2); // identifies an Instant 1334 * out.writeLong(seconds); 1335 * out.writeInt(nanos); 1336 * </pre> 1337 * 1338 * @return the instance of {@code Ser}, not null 1339 */ writeReplace()1340 private Object writeReplace() { 1341 return new Ser(Ser.INSTANT_TYPE, this); 1342 } 1343 1344 /** 1345 * Defend against malicious streams. 1346 * 1347 * @param s the stream to read 1348 * @throws InvalidObjectException always 1349 */ readObject(ObjectInputStream s)1350 private void readObject(ObjectInputStream s) throws InvalidObjectException { 1351 throw new InvalidObjectException("Deserialization via serialization delegate"); 1352 } 1353 writeExternal(DataOutput out)1354 void writeExternal(DataOutput out) throws IOException { 1355 out.writeLong(seconds); 1356 out.writeInt(nanos); 1357 } 1358 readExternal(DataInput in)1359 static Instant readExternal(DataInput in) throws IOException { 1360 long seconds = in.readLong(); 1361 int nanos = in.readInt(); 1362 return Instant.ofEpochSecond(seconds, nanos); 1363 } 1364 1365 } 1366