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