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