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