author | mduigou |
Tue, 05 Nov 2013 19:44:41 -0800 | |
changeset 21615 | 0231a565a5b7 |
parent 21331 | 8ee181e7e48b |
child 22081 | 86eb26ff8f2b |
permissions | -rw-r--r-- |
15289 | 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 |
||
15658 | 64 |
import static java.time.LocalTime.NANOS_PER_SECOND; |
15289 | 65 |
import static java.time.LocalTime.SECONDS_PER_DAY; |
15658 | 66 |
import static java.time.LocalTime.SECONDS_PER_HOUR; |
67 |
import static java.time.LocalTime.SECONDS_PER_MINUTE; |
|
15289 | 68 |
import static java.time.temporal.ChronoField.NANO_OF_SECOND; |
69 |
import static java.time.temporal.ChronoUnit.DAYS; |
|
15658 | 70 |
import static java.time.temporal.ChronoUnit.NANOS; |
71 |
import static java.time.temporal.ChronoUnit.SECONDS; |
|
15289 | 72 |
|
73 |
import java.io.DataInput; |
|
74 |
import java.io.DataOutput; |
|
75 |
import java.io.IOException; |
|
76 |
import java.io.InvalidObjectException; |
|
19841
15c8e97d6a14
8024164: JSR310 serialization should be described in details
rriggs
parents:
19030
diff
changeset
|
77 |
import java.io.InvalidObjectException; |
15289 | 78 |
import java.io.Serializable; |
79 |
import java.math.BigDecimal; |
|
80 |
import java.math.BigInteger; |
|
81 |
import java.math.RoundingMode; |
|
82 |
import java.time.format.DateTimeParseException; |
|
83 |
import java.time.temporal.ChronoField; |
|
84 |
import java.time.temporal.ChronoUnit; |
|
85 |
import java.time.temporal.Temporal; |
|
15658 | 86 |
import java.time.temporal.TemporalAmount; |
15289 | 87 |
import java.time.temporal.TemporalUnit; |
16852 | 88 |
import java.time.temporal.UnsupportedTemporalTypeException; |
15658 | 89 |
import java.util.Arrays; |
90 |
import java.util.Collections; |
|
91 |
import java.util.List; |
|
15289 | 92 |
import java.util.Objects; |
15658 | 93 |
import java.util.regex.Matcher; |
94 |
import java.util.regex.Pattern; |
|
15289 | 95 |
|
96 |
/** |
|
15658 | 97 |
* A time-based amount of time, such as '34.5 seconds'. |
15289 | 98 |
* <p> |
15658 | 99 |
* This class models a quantity or amount of time in terms of seconds and nanoseconds. |
100 |
* It can be accessed using other duration-based units, such as minutes and hours. |
|
101 |
* In addition, the {@link ChronoUnit#DAYS DAYS} unit can be used and is treated as |
|
102 |
* exactly equal to 24 hours, thus ignoring daylight savings effects. |
|
103 |
* See {@link Period} for the date-based equivalent to this class. |
|
15289 | 104 |
* <p> |
105 |
* A physical duration could be of infinite length. |
|
106 |
* For practicality, the duration is stored with constraints similar to {@link Instant}. |
|
107 |
* The duration uses nanosecond resolution with a maximum value of the seconds that can |
|
108 |
* be held in a {@code long}. This is greater than the current estimated age of the universe. |
|
109 |
* <p> |
|
110 |
* The range of a duration requires the storage of a number larger than a {@code long}. |
|
111 |
* To achieve this, the class stores a {@code long} representing seconds and an {@code int} |
|
112 |
* representing nanosecond-of-second, which will always be between 0 and 999,999,999. |
|
15658 | 113 |
* The model is of a directed duration, meaning that the duration may be negative. |
15289 | 114 |
* <p> |
115 |
* The duration is measured in "seconds", but these are not necessarily identical to |
|
116 |
* the scientific "SI second" definition based on atomic clocks. |
|
117 |
* This difference only impacts durations measured near a leap-second and should not affect |
|
118 |
* most applications. |
|
119 |
* See {@link Instant} for a discussion as to the meaning of the second and time-scales. |
|
120 |
* |
|
17474 | 121 |
* @implSpec |
15289 | 122 |
* This class is immutable and thread-safe. |
123 |
* |
|
124 |
* @since 1.8 |
|
125 |
*/ |
|
126 |
public final class Duration |
|
15658 | 127 |
implements TemporalAmount, Comparable<Duration>, Serializable { |
15289 | 128 |
|
129 |
/** |
|
130 |
* Constant for a duration of zero. |
|
131 |
*/ |
|
132 |
public static final Duration ZERO = new Duration(0, 0); |
|
133 |
/** |
|
134 |
* Serialization version. |
|
135 |
*/ |
|
136 |
private static final long serialVersionUID = 3078945930695997490L; |
|
137 |
/** |
|
138 |
* Constant for nanos per second. |
|
139 |
*/ |
|
15658 | 140 |
private static final BigInteger BI_NANOS_PER_SECOND = BigInteger.valueOf(NANOS_PER_SECOND); |
15289 | 141 |
/** |
15658 | 142 |
* The pattern for parsing. |
15289 | 143 |
*/ |
21331
8ee181e7e48b
8024686: Cleanup of java.time serialization source
rriggs
parents:
20520
diff
changeset
|
144 |
private static final Pattern PATTERN = |
15658 | 145 |
Pattern.compile("([-+]?)P(?:([-+]?[0-9]+)D)?" + |
146 |
"(T(?:([-+]?[0-9]+)H)?(?:([-+]?[0-9]+)M)?(?:([-+]?[0-9]+)(?:[.,]([0-9]{0,9}))?S)?)?", |
|
147 |
Pattern.CASE_INSENSITIVE); |
|
15289 | 148 |
|
149 |
/** |
|
150 |
* The number of seconds in the duration. |
|
151 |
*/ |
|
152 |
private final long seconds; |
|
153 |
/** |
|
154 |
* The number of nanoseconds in the duration, expressed as a fraction of the |
|
155 |
* number of seconds. This is always positive, and never exceeds 999,999,999. |
|
156 |
*/ |
|
157 |
private final int nanos; |
|
158 |
||
159 |
//----------------------------------------------------------------------- |
|
160 |
/** |
|
15658 | 161 |
* Obtains a {@code Duration} representing a number of standard 24 hour days. |
162 |
* <p> |
|
163 |
* The seconds are calculated based on the standard definition of a day, |
|
164 |
* where each day is 86400 seconds which implies a 24 hour day. |
|
165 |
* The nanosecond in second field is set to zero. |
|
166 |
* |
|
167 |
* @param days the number of days, positive or negative |
|
168 |
* @return a {@code Duration}, not null |
|
169 |
* @throws ArithmeticException if the input days exceeds the capacity of {@code Duration} |
|
170 |
*/ |
|
171 |
public static Duration ofDays(long days) { |
|
172 |
return create(Math.multiplyExact(days, SECONDS_PER_DAY), 0); |
|
173 |
} |
|
174 |
||
175 |
/** |
|
176 |
* Obtains a {@code Duration} representing a number of standard hours. |
|
177 |
* <p> |
|
178 |
* The seconds are calculated based on the standard definition of an hour, |
|
179 |
* where each hour is 3600 seconds. |
|
180 |
* The nanosecond in second field is set to zero. |
|
181 |
* |
|
182 |
* @param hours the number of hours, positive or negative |
|
183 |
* @return a {@code Duration}, not null |
|
184 |
* @throws ArithmeticException if the input hours exceeds the capacity of {@code Duration} |
|
185 |
*/ |
|
186 |
public static Duration ofHours(long hours) { |
|
187 |
return create(Math.multiplyExact(hours, SECONDS_PER_HOUR), 0); |
|
188 |
} |
|
189 |
||
190 |
/** |
|
191 |
* Obtains a {@code Duration} representing a number of standard minutes. |
|
192 |
* <p> |
|
193 |
* The seconds are calculated based on the standard definition of a minute, |
|
194 |
* where each minute is 60 seconds. |
|
195 |
* The nanosecond in second field is set to zero. |
|
196 |
* |
|
197 |
* @param minutes the number of minutes, positive or negative |
|
198 |
* @return a {@code Duration}, not null |
|
199 |
* @throws ArithmeticException if the input minutes exceeds the capacity of {@code Duration} |
|
200 |
*/ |
|
201 |
public static Duration ofMinutes(long minutes) { |
|
202 |
return create(Math.multiplyExact(minutes, SECONDS_PER_MINUTE), 0); |
|
203 |
} |
|
204 |
||
205 |
//----------------------------------------------------------------------- |
|
206 |
/** |
|
207 |
* Obtains a {@code Duration} representing a number of seconds. |
|
15289 | 208 |
* <p> |
209 |
* The nanosecond in second field is set to zero. |
|
210 |
* |
|
211 |
* @param seconds the number of seconds, positive or negative |
|
212 |
* @return a {@code Duration}, not null |
|
213 |
*/ |
|
214 |
public static Duration ofSeconds(long seconds) { |
|
215 |
return create(seconds, 0); |
|
216 |
} |
|
217 |
||
218 |
/** |
|
15658 | 219 |
* Obtains a {@code Duration} representing a number of seconds and an |
220 |
* adjustment in nanoseconds. |
|
15289 | 221 |
* <p> |
222 |
* This method allows an arbitrary number of nanoseconds to be passed in. |
|
223 |
* The factory will alter the values of the second and nanosecond in order |
|
224 |
* to ensure that the stored nanosecond is in the range 0 to 999,999,999. |
|
225 |
* For example, the following will result in the exactly the same duration: |
|
226 |
* <pre> |
|
227 |
* Duration.ofSeconds(3, 1); |
|
228 |
* Duration.ofSeconds(4, -999_999_999); |
|
229 |
* Duration.ofSeconds(2, 1000_000_001); |
|
230 |
* </pre> |
|
231 |
* |
|
232 |
* @param seconds the number of seconds, positive or negative |
|
233 |
* @param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative |
|
234 |
* @return a {@code Duration}, not null |
|
235 |
* @throws ArithmeticException if the adjustment causes the seconds to exceed the capacity of {@code Duration} |
|
236 |
*/ |
|
237 |
public static Duration ofSeconds(long seconds, long nanoAdjustment) { |
|
238 |
long secs = Math.addExact(seconds, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND)); |
|
15658 | 239 |
int nos = (int) Math.floorMod(nanoAdjustment, NANOS_PER_SECOND); |
15289 | 240 |
return create(secs, nos); |
241 |
} |
|
242 |
||
243 |
//----------------------------------------------------------------------- |
|
244 |
/** |
|
15658 | 245 |
* Obtains a {@code Duration} representing a number of milliseconds. |
15289 | 246 |
* <p> |
247 |
* The seconds and nanoseconds are extracted from the specified milliseconds. |
|
248 |
* |
|
249 |
* @param millis the number of milliseconds, positive or negative |
|
250 |
* @return a {@code Duration}, not null |
|
251 |
*/ |
|
252 |
public static Duration ofMillis(long millis) { |
|
253 |
long secs = millis / 1000; |
|
254 |
int mos = (int) (millis % 1000); |
|
255 |
if (mos < 0) { |
|
256 |
mos += 1000; |
|
257 |
secs--; |
|
258 |
} |
|
259 |
return create(secs, mos * 1000_000); |
|
260 |
} |
|
261 |
||
262 |
//----------------------------------------------------------------------- |
|
263 |
/** |
|
15658 | 264 |
* Obtains a {@code Duration} representing a number of nanoseconds. |
15289 | 265 |
* <p> |
266 |
* The seconds and nanoseconds are extracted from the specified nanoseconds. |
|
267 |
* |
|
268 |
* @param nanos the number of nanoseconds, positive or negative |
|
269 |
* @return a {@code Duration}, not null |
|
270 |
*/ |
|
271 |
public static Duration ofNanos(long nanos) { |
|
272 |
long secs = nanos / NANOS_PER_SECOND; |
|
273 |
int nos = (int) (nanos % NANOS_PER_SECOND); |
|
274 |
if (nos < 0) { |
|
275 |
nos += NANOS_PER_SECOND; |
|
276 |
secs--; |
|
277 |
} |
|
278 |
return create(secs, nos); |
|
279 |
} |
|
280 |
||
281 |
//----------------------------------------------------------------------- |
|
282 |
/** |
|
15658 | 283 |
* Obtains a {@code Duration} representing an amount in the specified unit. |
15289 | 284 |
* <p> |
285 |
* The parameters represent the two parts of a phrase like '6 Hours'. For example: |
|
286 |
* <pre> |
|
287 |
* Duration.of(3, SECONDS); |
|
288 |
* Duration.of(465, HOURS); |
|
289 |
* </pre> |
|
290 |
* Only a subset of units are accepted by this method. |
|
291 |
* The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or |
|
292 |
* be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception. |
|
293 |
* |
|
294 |
* @param amount the amount of the duration, measured in terms of the unit, positive or negative |
|
295 |
* @param unit the unit that the duration is measured in, must have an exact duration, not null |
|
296 |
* @return a {@code Duration}, not null |
|
297 |
* @throws DateTimeException if the period unit has an estimated duration |
|
298 |
* @throws ArithmeticException if a numeric overflow occurs |
|
299 |
*/ |
|
300 |
public static Duration of(long amount, TemporalUnit unit) { |
|
301 |
return ZERO.plus(amount, unit); |
|
302 |
} |
|
303 |
||
304 |
//----------------------------------------------------------------------- |
|
305 |
/** |
|
16852 | 306 |
* Obtains an instance of {@code Duration} from a temporal amount. |
307 |
* <p> |
|
308 |
* This obtains a duration based on the specified amount. |
|
309 |
* A {@code TemporalAmount} represents an amount of time, which may be |
|
310 |
* date-based or time-based, which this factory extracts to a duration. |
|
15289 | 311 |
* <p> |
16852 | 312 |
* The conversion loops around the set of units from the amount and uses |
313 |
* the {@linkplain TemporalUnit#getDuration() duration} of the unit to |
|
314 |
* calculate the total {@code Duration}. |
|
315 |
* Only a subset of units are accepted by this method. The unit must either |
|
316 |
* have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} |
|
317 |
* or be {@link ChronoUnit#DAYS} which is treated as 24 hours. |
|
318 |
* If any other units are found then an exception is thrown. |
|
15289 | 319 |
* |
16852 | 320 |
* @param amount the temporal amount to convert, not null |
321 |
* @return the equivalent duration, not null |
|
322 |
* @throws DateTimeException if unable to convert to a {@code Duration} |
|
323 |
* @throws ArithmeticException if numeric overflow occurs |
|
15289 | 324 |
*/ |
16852 | 325 |
public static Duration from(TemporalAmount amount) { |
326 |
Objects.requireNonNull(amount, "amount"); |
|
327 |
Duration duration = ZERO; |
|
328 |
for (TemporalUnit unit : amount.getUnits()) { |
|
329 |
duration = duration.plus(amount.get(unit), unit); |
|
15658 | 330 |
} |
16852 | 331 |
return duration; |
15289 | 332 |
} |
333 |
||
334 |
//----------------------------------------------------------------------- |
|
335 |
/** |
|
15658 | 336 |
* Obtains a {@code Duration} from a text string such as {@code PnDTnHnMn.nS}. |
337 |
* <p> |
|
338 |
* This will parse a textual representation of a duration, including the |
|
339 |
* string produced by {@code toString()}. The formats accepted are based |
|
340 |
* on the ISO-8601 duration format {@code PnDTnHnMn.nS} with days |
|
341 |
* considered to be exactly 24 hours. |
|
15289 | 342 |
* <p> |
15658 | 343 |
* The string starts with an optional sign, denoted by the ASCII negative |
344 |
* or positive symbol. If negative, the whole period is negated. |
|
345 |
* The ASCII letter "P" is next in upper or lower case. |
|
346 |
* There are then four sections, each consisting of a number and a suffix. |
|
347 |
* The sections have suffixes in ASCII of "D", "H", "M" and "S" for |
|
348 |
* days, hours, minutes and seconds, accepted in upper or lower case. |
|
349 |
* The suffixes must occur in order. The ASCII letter "T" must occur before |
|
350 |
* the first occurrence, if any, of an hour, minute or second section. |
|
351 |
* At least one of the four sections must be present, and if "T" is present |
|
352 |
* there must be at least one section after the "T". |
|
353 |
* The number part of each section must consist of one or more ASCII digits. |
|
354 |
* The number may be prefixed by the ASCII negative or positive symbol. |
|
355 |
* The number of days, hours and minutes must parse to an {@code long}. |
|
356 |
* The number of seconds must parse to an {@code long} with optional fraction. |
|
15289 | 357 |
* The decimal point may be either a dot or a comma. |
15658 | 358 |
* The fractional part may have from zero to 9 digits. |
359 |
* <p> |
|
360 |
* The leading plus/minus sign, and negative values for other units are |
|
361 |
* not part of the ISO-8601 standard. |
|
362 |
* <p> |
|
363 |
* Examples: |
|
364 |
* <pre> |
|
16852 | 365 |
* "PT20.345S" -- parses as "20.345 seconds" |
366 |
* "PT15M" -- parses as "15 minutes" (where a minute is 60 seconds) |
|
367 |
* "PT10H" -- parses as "10 hours" (where an hour is 3600 seconds) |
|
368 |
* "P2D" -- parses as "2 days" (where a day is 24 hours or 86400 seconds) |
|
369 |
* "P2DT3H4M" -- parses as "2 days, 3 hours and 4 minutes" |
|
370 |
* "P-6H3M" -- parses as "-6 hours and +3 minutes" |
|
371 |
* "-P6H3M" -- parses as "-6 hours and -3 minutes" |
|
372 |
* "-P-6H+3M" -- parses as "+6 hours and -3 minutes" |
|
15658 | 373 |
* </pre> |
15289 | 374 |
* |
375 |
* @param text the text to parse, not null |
|
15658 | 376 |
* @return the parsed duration, not null |
377 |
* @throws DateTimeParseException if the text cannot be parsed to a duration |
|
15289 | 378 |
*/ |
15658 | 379 |
public static Duration parse(CharSequence text) { |
15289 | 380 |
Objects.requireNonNull(text, "text"); |
15658 | 381 |
Matcher matcher = PATTERN.matcher(text); |
382 |
if (matcher.matches()) { |
|
383 |
// check for letter T but no time sections |
|
384 |
if ("T".equals(matcher.group(3)) == false) { |
|
385 |
boolean negate = "-".equals(matcher.group(1)); |
|
386 |
String dayMatch = matcher.group(2); |
|
387 |
String hourMatch = matcher.group(4); |
|
388 |
String minuteMatch = matcher.group(5); |
|
389 |
String secondMatch = matcher.group(6); |
|
390 |
String fractionMatch = matcher.group(7); |
|
391 |
if (dayMatch != null || hourMatch != null || minuteMatch != null || secondMatch != null) { |
|
392 |
long daysAsSecs = parseNumber(text, dayMatch, SECONDS_PER_DAY, "days"); |
|
393 |
long hoursAsSecs = parseNumber(text, hourMatch, SECONDS_PER_HOUR, "hours"); |
|
394 |
long minsAsSecs = parseNumber(text, minuteMatch, SECONDS_PER_MINUTE, "minutes"); |
|
395 |
long seconds = parseNumber(text, secondMatch, 1, "seconds"); |
|
396 |
int nanos = parseFraction(text, fractionMatch, seconds < 0 ? -1 : 1); |
|
397 |
try { |
|
398 |
return create(negate, daysAsSecs, hoursAsSecs, minsAsSecs, seconds, nanos); |
|
399 |
} catch (ArithmeticException ex) { |
|
400 |
throw (DateTimeParseException) new DateTimeParseException("Text cannot be parsed to a Duration: overflow", text, 0).initCause(ex); |
|
401 |
} |
|
15289 | 402 |
} |
403 |
} |
|
15658 | 404 |
} |
405 |
throw new DateTimeParseException("Text cannot be parsed to a Duration", text, 0); |
|
406 |
} |
|
407 |
||
408 |
private static long parseNumber(CharSequence text, String parsed, int multiplier, String errorText) { |
|
409 |
// regex limits to [-+]?[0-9]+ |
|
410 |
if (parsed == null) { |
|
411 |
return 0; |
|
412 |
} |
|
413 |
try { |
|
414 |
long val = Long.parseLong(parsed); |
|
415 |
return Math.multiplyExact(val, multiplier); |
|
416 |
} catch (NumberFormatException | ArithmeticException ex) { |
|
417 |
throw (DateTimeParseException) new DateTimeParseException("Text cannot be parsed to a Duration: " + errorText, text, 0).initCause(ex); |
|
418 |
} |
|
419 |
} |
|
15289 | 420 |
|
15658 | 421 |
private static int parseFraction(CharSequence text, String parsed, int negate) { |
422 |
// regex limits to [0-9]{0,9} |
|
423 |
if (parsed == null || parsed.length() == 0) { |
|
424 |
return 0; |
|
15289 | 425 |
} |
15658 | 426 |
try { |
427 |
parsed = (parsed + "000000000").substring(0, 9); |
|
428 |
return Integer.parseInt(parsed) * negate; |
|
429 |
} catch (NumberFormatException | ArithmeticException ex) { |
|
430 |
throw (DateTimeParseException) new DateTimeParseException("Text cannot be parsed to a Duration: fraction", text, 0).initCause(ex); |
|
431 |
} |
|
432 |
} |
|
433 |
||
434 |
private static Duration create(boolean negate, long daysAsSecs, long hoursAsSecs, long minsAsSecs, long secs, int nanos) { |
|
435 |
long seconds = Math.addExact(daysAsSecs, Math.addExact(hoursAsSecs, Math.addExact(minsAsSecs, secs))); |
|
436 |
if (negate) { |
|
437 |
return ofSeconds(seconds, nanos).negated(); |
|
438 |
} |
|
439 |
return ofSeconds(seconds, nanos); |
|
15289 | 440 |
} |
441 |
||
442 |
//----------------------------------------------------------------------- |
|
443 |
/** |
|
20520
0952771e3e25
8024835: Change until() to accept any compatible temporal
rriggs
parents:
19841
diff
changeset
|
444 |
* Obtains a {@code Duration} representing the duration between two temporal objects. |
16852 | 445 |
* <p> |
20520
0952771e3e25
8024835: Change until() to accept any compatible temporal
rriggs
parents:
19841
diff
changeset
|
446 |
* This calculates the duration between two temporal objects. If the objects |
0952771e3e25
8024835: Change until() to accept any compatible temporal
rriggs
parents:
19841
diff
changeset
|
447 |
* are of different types, then the duration is calculated based on the type |
0952771e3e25
8024835: Change until() to accept any compatible temporal
rriggs
parents:
19841
diff
changeset
|
448 |
* of the first object. For example, if the first argument is a {@code LocalTime} |
0952771e3e25
8024835: Change until() to accept any compatible temporal
rriggs
parents:
19841
diff
changeset
|
449 |
* then the second argument is converted to a {@code LocalTime}. |
0952771e3e25
8024835: Change until() to accept any compatible temporal
rriggs
parents:
19841
diff
changeset
|
450 |
* <p> |
16852 | 451 |
* The specified temporal objects must support the {@link ChronoUnit#SECONDS SECONDS} unit. |
452 |
* For full accuracy, either the {@link ChronoUnit#NANOS NANOS} unit or the |
|
453 |
* {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} field should be supported. |
|
454 |
* <p> |
|
455 |
* The result of this method can be a negative period if the end is before the start. |
|
456 |
* To guarantee to obtain a positive duration call {@link #abs()} on the result. |
|
457 |
* |
|
458 |
* @param startInclusive the start instant, inclusive, not null |
|
459 |
* @param endExclusive the end instant, exclusive, not null |
|
460 |
* @return a {@code Duration}, not null |
|
461 |
* @throws DateTimeException if the seconds between the temporals cannot be obtained |
|
462 |
* @throws ArithmeticException if the calculation exceeds the capacity of {@code Duration} |
|
463 |
*/ |
|
464 |
public static Duration between(Temporal startInclusive, Temporal endExclusive) { |
|
465 |
try { |
|
19030 | 466 |
return ofNanos(startInclusive.until(endExclusive, NANOS)); |
16852 | 467 |
} catch (DateTimeException | ArithmeticException ex) { |
19030 | 468 |
long secs = startInclusive.until(endExclusive, SECONDS); |
16852 | 469 |
long nanos; |
470 |
try { |
|
471 |
nanos = endExclusive.getLong(NANO_OF_SECOND) - startInclusive.getLong(NANO_OF_SECOND); |
|
472 |
if (secs > 0 && nanos < 0) { |
|
473 |
secs++; |
|
474 |
} else if (secs < 0 && nanos > 0) { |
|
475 |
secs--; |
|
476 |
} |
|
477 |
} catch (DateTimeException ex2) { |
|
478 |
nanos = 0; |
|
479 |
} |
|
480 |
return ofSeconds(secs, nanos); |
|
481 |
} |
|
482 |
} |
|
483 |
||
484 |
//----------------------------------------------------------------------- |
|
485 |
/** |
|
15289 | 486 |
* Obtains an instance of {@code Duration} using seconds and nanoseconds. |
487 |
* |
|
488 |
* @param seconds the length of the duration in seconds, positive or negative |
|
489 |
* @param nanoAdjustment the nanosecond adjustment within the second, from 0 to 999,999,999 |
|
490 |
*/ |
|
491 |
private static Duration create(long seconds, int nanoAdjustment) { |
|
492 |
if ((seconds | nanoAdjustment) == 0) { |
|
493 |
return ZERO; |
|
494 |
} |
|
495 |
return new Duration(seconds, nanoAdjustment); |
|
496 |
} |
|
497 |
||
498 |
/** |
|
499 |
* Constructs an instance of {@code Duration} using seconds and nanoseconds. |
|
500 |
* |
|
501 |
* @param seconds the length of the duration in seconds, positive or negative |
|
502 |
* @param nanos the nanoseconds within the second, from 0 to 999,999,999 |
|
503 |
*/ |
|
504 |
private Duration(long seconds, int nanos) { |
|
505 |
super(); |
|
506 |
this.seconds = seconds; |
|
507 |
this.nanos = nanos; |
|
508 |
} |
|
509 |
||
510 |
//----------------------------------------------------------------------- |
|
511 |
/** |
|
15658 | 512 |
* Gets the value of the requested unit. |
513 |
* <p> |
|
514 |
* This returns a value for each of the two supported units, |
|
515 |
* {@link ChronoUnit#SECONDS SECONDS} and {@link ChronoUnit#NANOS NANOS}. |
|
516 |
* All other units throw an exception. |
|
517 |
* |
|
518 |
* @param unit the {@code TemporalUnit} for which to return the value |
|
519 |
* @return the long value of the unit |
|
520 |
* @throws DateTimeException if the unit is not supported |
|
16852 | 521 |
* @throws UnsupportedTemporalTypeException if the unit is not supported |
15658 | 522 |
*/ |
523 |
@Override |
|
524 |
public long get(TemporalUnit unit) { |
|
525 |
if (unit == SECONDS) { |
|
526 |
return seconds; |
|
527 |
} else if (unit == NANOS) { |
|
528 |
return nanos; |
|
529 |
} else { |
|
19030 | 530 |
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); |
15658 | 531 |
} |
532 |
} |
|
533 |
||
534 |
/** |
|
535 |
* Gets the set of units supported by this duration. |
|
536 |
* <p> |
|
537 |
* The supported units are {@link ChronoUnit#SECONDS SECONDS}, |
|
538 |
* and {@link ChronoUnit#NANOS NANOS}. |
|
539 |
* They are returned in the order seconds, nanos. |
|
540 |
* <p> |
|
541 |
* This set can be used in conjunction with {@link #get(TemporalUnit)} |
|
542 |
* to access the entire state of the period. |
|
543 |
* |
|
544 |
* @return a list containing the seconds and nanos units, not null |
|
545 |
*/ |
|
546 |
@Override |
|
547 |
public List<TemporalUnit> getUnits() { |
|
548 |
return DurationUnits.UNITS; |
|
549 |
} |
|
550 |
||
551 |
/** |
|
552 |
* Private class to delay initialization of this list until needed. |
|
553 |
* The circular dependency between Duration and ChronoUnit prevents |
|
554 |
* the simple initialization in Duration. |
|
555 |
*/ |
|
556 |
private static class DurationUnits { |
|
21331
8ee181e7e48b
8024686: Cleanup of java.time serialization source
rriggs
parents:
20520
diff
changeset
|
557 |
static final List<TemporalUnit> UNITS = |
15658 | 558 |
Collections.unmodifiableList(Arrays.<TemporalUnit>asList(SECONDS, NANOS)); |
559 |
} |
|
560 |
||
561 |
//----------------------------------------------------------------------- |
|
562 |
/** |
|
15289 | 563 |
* Checks if this duration is zero length. |
564 |
* <p> |
|
565 |
* A {@code Duration} represents a directed distance between two points on |
|
566 |
* the time-line and can therefore be positive, zero or negative. |
|
567 |
* This method checks whether the length is zero. |
|
568 |
* |
|
569 |
* @return true if this duration has a total length equal to zero |
|
570 |
*/ |
|
571 |
public boolean isZero() { |
|
572 |
return (seconds | nanos) == 0; |
|
573 |
} |
|
574 |
||
575 |
/** |
|
576 |
* Checks if this duration is negative, excluding zero. |
|
577 |
* <p> |
|
578 |
* A {@code Duration} represents a directed distance between two points on |
|
579 |
* the time-line and can therefore be positive, zero or negative. |
|
580 |
* This method checks whether the length is less than zero. |
|
581 |
* |
|
582 |
* @return true if this duration has a total length less than zero |
|
583 |
*/ |
|
584 |
public boolean isNegative() { |
|
585 |
return seconds < 0; |
|
586 |
} |
|
587 |
||
588 |
//----------------------------------------------------------------------- |
|
589 |
/** |
|
590 |
* Gets the number of seconds in this duration. |
|
591 |
* <p> |
|
592 |
* The length of the duration is stored using two fields - seconds and nanoseconds. |
|
593 |
* The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to |
|
594 |
* the length in seconds. |
|
595 |
* The total duration is defined by calling this method and {@link #getNano()}. |
|
596 |
* <p> |
|
597 |
* A {@code Duration} represents a directed distance between two points on the time-line. |
|
598 |
* A negative duration is expressed by the negative sign of the seconds part. |
|
599 |
* A duration of -1 nanosecond is stored as -1 seconds plus 999,999,999 nanoseconds. |
|
600 |
* |
|
601 |
* @return the whole seconds part of the length of the duration, positive or negative |
|
602 |
*/ |
|
603 |
public long getSeconds() { |
|
604 |
return seconds; |
|
605 |
} |
|
606 |
||
607 |
/** |
|
608 |
* Gets the number of nanoseconds within the second in this duration. |
|
609 |
* <p> |
|
610 |
* The length of the duration is stored using two fields - seconds and nanoseconds. |
|
611 |
* The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to |
|
612 |
* the length in seconds. |
|
613 |
* The total duration is defined by calling this method and {@link #getSeconds()}. |
|
614 |
* <p> |
|
615 |
* A {@code Duration} represents a directed distance between two points on the time-line. |
|
616 |
* A negative duration is expressed by the negative sign of the seconds part. |
|
617 |
* A duration of -1 nanosecond is stored as -1 seconds plus 999,999,999 nanoseconds. |
|
618 |
* |
|
619 |
* @return the nanoseconds within the second part of the length of the duration, from 0 to 999,999,999 |
|
620 |
*/ |
|
621 |
public int getNano() { |
|
622 |
return nanos; |
|
623 |
} |
|
624 |
||
625 |
//----------------------------------------------------------------------- |
|
626 |
/** |
|
15658 | 627 |
* Returns a copy of this duration with the specified amount of seconds. |
628 |
* <p> |
|
629 |
* This returns a duration with the specified seconds, retaining the |
|
630 |
* nano-of-second part of this duration. |
|
631 |
* <p> |
|
632 |
* This instance is immutable and unaffected by this method call. |
|
633 |
* |
|
634 |
* @param seconds the seconds to represent, may be negative |
|
635 |
* @return a {@code Duration} based on this period with the requested seconds, not null |
|
636 |
*/ |
|
637 |
public Duration withSeconds(long seconds) { |
|
638 |
return create(seconds, nanos); |
|
639 |
} |
|
640 |
||
641 |
/** |
|
642 |
* Returns a copy of this duration with the specified nano-of-second. |
|
643 |
* <p> |
|
644 |
* This returns a duration with the specified nano-of-second, retaining the |
|
645 |
* seconds part of this duration. |
|
646 |
* <p> |
|
647 |
* This instance is immutable and unaffected by this method call. |
|
648 |
* |
|
649 |
* @param nanoOfSecond the nano-of-second to represent, from 0 to 999,999,999 |
|
650 |
* @return a {@code Duration} based on this period with the requested nano-of-second, not null |
|
651 |
* @throws DateTimeException if the nano-of-second is invalid |
|
652 |
*/ |
|
653 |
public Duration withNanos(int nanoOfSecond) { |
|
654 |
NANO_OF_SECOND.checkValidIntValue(nanoOfSecond); |
|
655 |
return create(seconds, nanoOfSecond); |
|
656 |
} |
|
657 |
||
658 |
//----------------------------------------------------------------------- |
|
659 |
/** |
|
15289 | 660 |
* Returns a copy of this duration with the specified duration added. |
661 |
* <p> |
|
662 |
* This instance is immutable and unaffected by this method call. |
|
663 |
* |
|
664 |
* @param duration the duration to add, positive or negative, not null |
|
665 |
* @return a {@code Duration} based on this duration with the specified duration added, not null |
|
666 |
* @throws ArithmeticException if numeric overflow occurs |
|
667 |
*/ |
|
668 |
public Duration plus(Duration duration) { |
|
669 |
return plus(duration.getSeconds(), duration.getNano()); |
|
670 |
} |
|
671 |
||
672 |
/** |
|
673 |
* Returns a copy of this duration with the specified duration added. |
|
674 |
* <p> |
|
675 |
* The duration amount is measured in terms of the specified unit. |
|
676 |
* Only a subset of units are accepted by this method. |
|
677 |
* The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or |
|
678 |
* be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception. |
|
679 |
* <p> |
|
680 |
* This instance is immutable and unaffected by this method call. |
|
681 |
* |
|
682 |
* @param amountToAdd the amount of the period, measured in terms of the unit, positive or negative |
|
683 |
* @param unit the unit that the period is measured in, must have an exact duration, not null |
|
684 |
* @return a {@code Duration} based on this duration with the specified duration added, not null |
|
16852 | 685 |
* @throws UnsupportedTemporalTypeException if the unit is not supported |
15289 | 686 |
* @throws ArithmeticException if numeric overflow occurs |
687 |
*/ |
|
688 |
public Duration plus(long amountToAdd, TemporalUnit unit) { |
|
689 |
Objects.requireNonNull(unit, "unit"); |
|
690 |
if (unit == DAYS) { |
|
691 |
return plus(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY), 0); |
|
692 |
} |
|
693 |
if (unit.isDurationEstimated()) { |
|
16852 | 694 |
throw new UnsupportedTemporalTypeException("Unit must not have an estimated duration"); |
15289 | 695 |
} |
696 |
if (amountToAdd == 0) { |
|
697 |
return this; |
|
698 |
} |
|
699 |
if (unit instanceof ChronoUnit) { |
|
700 |
switch ((ChronoUnit) unit) { |
|
701 |
case NANOS: return plusNanos(amountToAdd); |
|
702 |
case MICROS: return plusSeconds((amountToAdd / (1000_000L * 1000)) * 1000).plusNanos((amountToAdd % (1000_000L * 1000)) * 1000); |
|
703 |
case MILLIS: return plusMillis(amountToAdd); |
|
704 |
case SECONDS: return plusSeconds(amountToAdd); |
|
705 |
} |
|
706 |
return plusSeconds(Math.multiplyExact(unit.getDuration().seconds, amountToAdd)); |
|
707 |
} |
|
708 |
Duration duration = unit.getDuration().multipliedBy(amountToAdd); |
|
709 |
return plusSeconds(duration.getSeconds()).plusNanos(duration.getNano()); |
|
710 |
} |
|
711 |
||
712 |
//----------------------------------------------------------------------- |
|
713 |
/** |
|
15658 | 714 |
* Returns a copy of this duration with the specified duration in standard 24 hour days added. |
715 |
* <p> |
|
716 |
* The number of days is multiplied by 86400 to obtain the number of seconds to add. |
|
717 |
* This is based on the standard definition of a day as 24 hours. |
|
718 |
* <p> |
|
719 |
* This instance is immutable and unaffected by this method call. |
|
720 |
* |
|
721 |
* @param daysToAdd the days to add, positive or negative |
|
722 |
* @return a {@code Duration} based on this duration with the specified days added, not null |
|
723 |
* @throws ArithmeticException if numeric overflow occurs |
|
724 |
*/ |
|
725 |
public Duration plusDays(long daysToAdd) { |
|
726 |
return plus(Math.multiplyExact(daysToAdd, SECONDS_PER_DAY), 0); |
|
727 |
} |
|
728 |
||
729 |
/** |
|
730 |
* Returns a copy of this duration with the specified duration in hours added. |
|
731 |
* <p> |
|
732 |
* This instance is immutable and unaffected by this method call. |
|
733 |
* |
|
734 |
* @param hoursToAdd the hours to add, positive or negative |
|
735 |
* @return a {@code Duration} based on this duration with the specified hours added, not null |
|
736 |
* @throws ArithmeticException if numeric overflow occurs |
|
737 |
*/ |
|
738 |
public Duration plusHours(long hoursToAdd) { |
|
739 |
return plus(Math.multiplyExact(hoursToAdd, SECONDS_PER_HOUR), 0); |
|
740 |
} |
|
741 |
||
742 |
/** |
|
743 |
* Returns a copy of this duration with the specified duration in minutes added. |
|
744 |
* <p> |
|
745 |
* This instance is immutable and unaffected by this method call. |
|
746 |
* |
|
747 |
* @param minutesToAdd the minutes to add, positive or negative |
|
748 |
* @return a {@code Duration} based on this duration with the specified minutes added, not null |
|
749 |
* @throws ArithmeticException if numeric overflow occurs |
|
750 |
*/ |
|
751 |
public Duration plusMinutes(long minutesToAdd) { |
|
752 |
return plus(Math.multiplyExact(minutesToAdd, SECONDS_PER_MINUTE), 0); |
|
753 |
} |
|
754 |
||
755 |
/** |
|
15289 | 756 |
* Returns a copy of this duration with the specified duration in seconds added. |
757 |
* <p> |
|
758 |
* This instance is immutable and unaffected by this method call. |
|
759 |
* |
|
760 |
* @param secondsToAdd the seconds to add, positive or negative |
|
761 |
* @return a {@code Duration} based on this duration with the specified seconds added, not null |
|
762 |
* @throws ArithmeticException if numeric overflow occurs |
|
763 |
*/ |
|
764 |
public Duration plusSeconds(long secondsToAdd) { |
|
765 |
return plus(secondsToAdd, 0); |
|
766 |
} |
|
767 |
||
768 |
/** |
|
769 |
* Returns a copy of this duration with the specified duration in milliseconds added. |
|
770 |
* <p> |
|
771 |
* This instance is immutable and unaffected by this method call. |
|
772 |
* |
|
773 |
* @param millisToAdd the milliseconds to add, positive or negative |
|
774 |
* @return a {@code Duration} based on this duration with the specified milliseconds added, not null |
|
775 |
* @throws ArithmeticException if numeric overflow occurs |
|
776 |
*/ |
|
777 |
public Duration plusMillis(long millisToAdd) { |
|
778 |
return plus(millisToAdd / 1000, (millisToAdd % 1000) * 1000_000); |
|
779 |
} |
|
780 |
||
781 |
/** |
|
782 |
* Returns a copy of this duration with the specified duration in nanoseconds added. |
|
783 |
* <p> |
|
784 |
* This instance is immutable and unaffected by this method call. |
|
785 |
* |
|
786 |
* @param nanosToAdd the nanoseconds to add, positive or negative |
|
787 |
* @return a {@code Duration} based on this duration with the specified nanoseconds added, not null |
|
788 |
* @throws ArithmeticException if numeric overflow occurs |
|
789 |
*/ |
|
790 |
public Duration plusNanos(long nanosToAdd) { |
|
791 |
return plus(0, nanosToAdd); |
|
792 |
} |
|
793 |
||
794 |
/** |
|
795 |
* Returns a copy of this duration with the specified duration added. |
|
796 |
* <p> |
|
797 |
* This instance is immutable and unaffected by this method call. |
|
798 |
* |
|
799 |
* @param secondsToAdd the seconds to add, positive or negative |
|
800 |
* @param nanosToAdd the nanos to add, positive or negative |
|
801 |
* @return a {@code Duration} based on this duration with the specified seconds added, not null |
|
802 |
* @throws ArithmeticException if numeric overflow occurs |
|
803 |
*/ |
|
804 |
private Duration plus(long secondsToAdd, long nanosToAdd) { |
|
805 |
if ((secondsToAdd | nanosToAdd) == 0) { |
|
806 |
return this; |
|
807 |
} |
|
808 |
long epochSec = Math.addExact(seconds, secondsToAdd); |
|
809 |
epochSec = Math.addExact(epochSec, nanosToAdd / NANOS_PER_SECOND); |
|
810 |
nanosToAdd = nanosToAdd % NANOS_PER_SECOND; |
|
811 |
long nanoAdjustment = nanos + nanosToAdd; // safe int+NANOS_PER_SECOND |
|
812 |
return ofSeconds(epochSec, nanoAdjustment); |
|
813 |
} |
|
814 |
||
815 |
//----------------------------------------------------------------------- |
|
816 |
/** |
|
817 |
* Returns a copy of this duration with the specified duration subtracted. |
|
818 |
* <p> |
|
819 |
* This instance is immutable and unaffected by this method call. |
|
820 |
* |
|
821 |
* @param duration the duration to subtract, positive or negative, not null |
|
822 |
* @return a {@code Duration} based on this duration with the specified duration subtracted, not null |
|
823 |
* @throws ArithmeticException if numeric overflow occurs |
|
824 |
*/ |
|
825 |
public Duration minus(Duration duration) { |
|
826 |
long secsToSubtract = duration.getSeconds(); |
|
827 |
int nanosToSubtract = duration.getNano(); |
|
828 |
if (secsToSubtract == Long.MIN_VALUE) { |
|
829 |
return plus(Long.MAX_VALUE, -nanosToSubtract).plus(1, 0); |
|
830 |
} |
|
831 |
return plus(-secsToSubtract, -nanosToSubtract); |
|
832 |
} |
|
833 |
||
834 |
/** |
|
835 |
* Returns a copy of this duration with the specified duration subtracted. |
|
836 |
* <p> |
|
837 |
* The duration amount is measured in terms of the specified unit. |
|
838 |
* Only a subset of units are accepted by this method. |
|
839 |
* The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or |
|
840 |
* be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception. |
|
841 |
* <p> |
|
842 |
* This instance is immutable and unaffected by this method call. |
|
843 |
* |
|
844 |
* @param amountToSubtract the amount of the period, measured in terms of the unit, positive or negative |
|
845 |
* @param unit the unit that the period is measured in, must have an exact duration, not null |
|
846 |
* @return a {@code Duration} based on this duration with the specified duration subtracted, not null |
|
847 |
* @throws ArithmeticException if numeric overflow occurs |
|
848 |
*/ |
|
849 |
public Duration minus(long amountToSubtract, TemporalUnit unit) { |
|
850 |
return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit)); |
|
851 |
} |
|
852 |
||
853 |
//----------------------------------------------------------------------- |
|
854 |
/** |
|
15658 | 855 |
* Returns a copy of this duration with the specified duration in standard 24 hour days subtracted. |
856 |
* <p> |
|
857 |
* The number of days is multiplied by 86400 to obtain the number of seconds to subtract. |
|
858 |
* This is based on the standard definition of a day as 24 hours. |
|
859 |
* <p> |
|
860 |
* This instance is immutable and unaffected by this method call. |
|
861 |
* |
|
862 |
* @param daysToSubtract the days to subtract, positive or negative |
|
863 |
* @return a {@code Duration} based on this duration with the specified days subtracted, not null |
|
864 |
* @throws ArithmeticException if numeric overflow occurs |
|
865 |
*/ |
|
866 |
public Duration minusDays(long daysToSubtract) { |
|
867 |
return (daysToSubtract == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-daysToSubtract)); |
|
868 |
} |
|
869 |
||
870 |
/** |
|
871 |
* Returns a copy of this duration with the specified duration in hours subtracted. |
|
872 |
* <p> |
|
873 |
* The number of hours is multiplied by 3600 to obtain the number of seconds to subtract. |
|
874 |
* <p> |
|
875 |
* This instance is immutable and unaffected by this method call. |
|
876 |
* |
|
877 |
* @param hoursToSubtract the hours to subtract, positive or negative |
|
878 |
* @return a {@code Duration} based on this duration with the specified hours subtracted, not null |
|
879 |
* @throws ArithmeticException if numeric overflow occurs |
|
880 |
*/ |
|
881 |
public Duration minusHours(long hoursToSubtract) { |
|
882 |
return (hoursToSubtract == Long.MIN_VALUE ? plusHours(Long.MAX_VALUE).plusHours(1) : plusHours(-hoursToSubtract)); |
|
883 |
} |
|
884 |
||
885 |
/** |
|
886 |
* Returns a copy of this duration with the specified duration in minutes subtracted. |
|
887 |
* <p> |
|
888 |
* The number of hours is multiplied by 60 to obtain the number of seconds to subtract. |
|
889 |
* <p> |
|
890 |
* This instance is immutable and unaffected by this method call. |
|
891 |
* |
|
892 |
* @param minutesToSubtract the minutes to subtract, positive or negative |
|
893 |
* @return a {@code Duration} based on this duration with the specified minutes subtracted, not null |
|
894 |
* @throws ArithmeticException if numeric overflow occurs |
|
895 |
*/ |
|
896 |
public Duration minusMinutes(long minutesToSubtract) { |
|
897 |
return (minutesToSubtract == Long.MIN_VALUE ? plusMinutes(Long.MAX_VALUE).plusMinutes(1) : plusMinutes(-minutesToSubtract)); |
|
898 |
} |
|
899 |
||
900 |
/** |
|
15289 | 901 |
* Returns a copy of this duration with the specified duration in seconds subtracted. |
902 |
* <p> |
|
903 |
* This instance is immutable and unaffected by this method call. |
|
904 |
* |
|
905 |
* @param secondsToSubtract the seconds to subtract, positive or negative |
|
906 |
* @return a {@code Duration} based on this duration with the specified seconds subtracted, not null |
|
907 |
* @throws ArithmeticException if numeric overflow occurs |
|
908 |
*/ |
|
909 |
public Duration minusSeconds(long secondsToSubtract) { |
|
910 |
return (secondsToSubtract == Long.MIN_VALUE ? plusSeconds(Long.MAX_VALUE).plusSeconds(1) : plusSeconds(-secondsToSubtract)); |
|
911 |
} |
|
912 |
||
913 |
/** |
|
914 |
* Returns a copy of this duration with the specified duration in milliseconds subtracted. |
|
915 |
* <p> |
|
916 |
* This instance is immutable and unaffected by this method call. |
|
917 |
* |
|
918 |
* @param millisToSubtract the milliseconds to subtract, positive or negative |
|
919 |
* @return a {@code Duration} based on this duration with the specified milliseconds subtracted, not null |
|
920 |
* @throws ArithmeticException if numeric overflow occurs |
|
921 |
*/ |
|
922 |
public Duration minusMillis(long millisToSubtract) { |
|
923 |
return (millisToSubtract == Long.MIN_VALUE ? plusMillis(Long.MAX_VALUE).plusMillis(1) : plusMillis(-millisToSubtract)); |
|
924 |
} |
|
925 |
||
926 |
/** |
|
927 |
* Returns a copy of this duration with the specified duration in nanoseconds subtracted. |
|
928 |
* <p> |
|
929 |
* This instance is immutable and unaffected by this method call. |
|
930 |
* |
|
931 |
* @param nanosToSubtract the nanoseconds to subtract, positive or negative |
|
932 |
* @return a {@code Duration} based on this duration with the specified nanoseconds subtracted, not null |
|
933 |
* @throws ArithmeticException if numeric overflow occurs |
|
934 |
*/ |
|
935 |
public Duration minusNanos(long nanosToSubtract) { |
|
936 |
return (nanosToSubtract == Long.MIN_VALUE ? plusNanos(Long.MAX_VALUE).plusNanos(1) : plusNanos(-nanosToSubtract)); |
|
937 |
} |
|
938 |
||
939 |
//----------------------------------------------------------------------- |
|
940 |
/** |
|
941 |
* Returns a copy of this duration multiplied by the scalar. |
|
942 |
* <p> |
|
943 |
* This instance is immutable and unaffected by this method call. |
|
944 |
* |
|
945 |
* @param multiplicand the value to multiply the duration by, positive or negative |
|
946 |
* @return a {@code Duration} based on this duration multiplied by the specified scalar, not null |
|
947 |
* @throws ArithmeticException if numeric overflow occurs |
|
948 |
*/ |
|
949 |
public Duration multipliedBy(long multiplicand) { |
|
950 |
if (multiplicand == 0) { |
|
951 |
return ZERO; |
|
952 |
} |
|
953 |
if (multiplicand == 1) { |
|
954 |
return this; |
|
955 |
} |
|
956 |
return create(toSeconds().multiply(BigDecimal.valueOf(multiplicand))); |
|
957 |
} |
|
958 |
||
959 |
/** |
|
960 |
* Returns a copy of this duration divided by the specified value. |
|
961 |
* <p> |
|
962 |
* This instance is immutable and unaffected by this method call. |
|
963 |
* |
|
964 |
* @param divisor the value to divide the duration by, positive or negative, not zero |
|
965 |
* @return a {@code Duration} based on this duration divided by the specified divisor, not null |
|
15658 | 966 |
* @throws ArithmeticException if the divisor is zero or if numeric overflow occurs |
15289 | 967 |
*/ |
968 |
public Duration dividedBy(long divisor) { |
|
969 |
if (divisor == 0) { |
|
970 |
throw new ArithmeticException("Cannot divide by zero"); |
|
971 |
} |
|
972 |
if (divisor == 1) { |
|
973 |
return this; |
|
974 |
} |
|
975 |
return create(toSeconds().divide(BigDecimal.valueOf(divisor), RoundingMode.DOWN)); |
|
976 |
} |
|
977 |
||
978 |
/** |
|
979 |
* Converts this duration to the total length in seconds and |
|
980 |
* fractional nanoseconds expressed as a {@code BigDecimal}. |
|
981 |
* |
|
982 |
* @return the total length of the duration in seconds, with a scale of 9, not null |
|
983 |
*/ |
|
984 |
private BigDecimal toSeconds() { |
|
985 |
return BigDecimal.valueOf(seconds).add(BigDecimal.valueOf(nanos, 9)); |
|
986 |
} |
|
987 |
||
988 |
/** |
|
989 |
* Creates an instance of {@code Duration} from a number of seconds. |
|
990 |
* |
|
991 |
* @param seconds the number of seconds, up to scale 9, positive or negative |
|
992 |
* @return a {@code Duration}, not null |
|
993 |
* @throws ArithmeticException if numeric overflow occurs |
|
994 |
*/ |
|
995 |
private static Duration create(BigDecimal seconds) { |
|
996 |
BigInteger nanos = seconds.movePointRight(9).toBigIntegerExact(); |
|
997 |
BigInteger[] divRem = nanos.divideAndRemainder(BI_NANOS_PER_SECOND); |
|
998 |
if (divRem[0].bitLength() > 63) { |
|
999 |
throw new ArithmeticException("Exceeds capacity of Duration: " + nanos); |
|
1000 |
} |
|
1001 |
return ofSeconds(divRem[0].longValue(), divRem[1].intValue()); |
|
1002 |
} |
|
1003 |
||
1004 |
//----------------------------------------------------------------------- |
|
1005 |
/** |
|
1006 |
* Returns a copy of this duration with the length negated. |
|
1007 |
* <p> |
|
1008 |
* This method swaps the sign of the total length of this duration. |
|
1009 |
* For example, {@code PT1.3S} will be returned as {@code PT-1.3S}. |
|
1010 |
* <p> |
|
1011 |
* This instance is immutable and unaffected by this method call. |
|
1012 |
* |
|
1013 |
* @return a {@code Duration} based on this duration with the amount negated, not null |
|
1014 |
* @throws ArithmeticException if numeric overflow occurs |
|
1015 |
*/ |
|
1016 |
public Duration negated() { |
|
1017 |
return multipliedBy(-1); |
|
1018 |
} |
|
1019 |
||
1020 |
/** |
|
1021 |
* Returns a copy of this duration with a positive length. |
|
1022 |
* <p> |
|
1023 |
* This method returns a positive duration by effectively removing the sign from any negative total length. |
|
1024 |
* For example, {@code PT-1.3S} will be returned as {@code PT1.3S}. |
|
1025 |
* <p> |
|
1026 |
* This instance is immutable and unaffected by this method call. |
|
1027 |
* |
|
1028 |
* @return a {@code Duration} based on this duration with an absolute length, not null |
|
1029 |
* @throws ArithmeticException if numeric overflow occurs |
|
1030 |
*/ |
|
1031 |
public Duration abs() { |
|
1032 |
return isNegative() ? negated() : this; |
|
1033 |
} |
|
1034 |
||
1035 |
//------------------------------------------------------------------------- |
|
1036 |
/** |
|
1037 |
* Adds this duration to the specified temporal object. |
|
1038 |
* <p> |
|
1039 |
* This returns a temporal object of the same observable type as the input |
|
1040 |
* with this duration added. |
|
1041 |
* <p> |
|
1042 |
* In most cases, it is clearer to reverse the calling pattern by using |
|
15658 | 1043 |
* {@link Temporal#plus(TemporalAmount)}. |
15289 | 1044 |
* <pre> |
1045 |
* // these two lines are equivalent, but the second approach is recommended |
|
1046 |
* dateTime = thisDuration.addTo(dateTime); |
|
1047 |
* dateTime = dateTime.plus(thisDuration); |
|
1048 |
* </pre> |
|
1049 |
* <p> |
|
15658 | 1050 |
* The calculation will add the seconds, then nanos. |
1051 |
* Only non-zero amounts will be added. |
|
15289 | 1052 |
* <p> |
1053 |
* This instance is immutable and unaffected by this method call. |
|
1054 |
* |
|
1055 |
* @param temporal the temporal object to adjust, not null |
|
1056 |
* @return an object of the same type with the adjustment made, not null |
|
1057 |
* @throws DateTimeException if unable to add |
|
1058 |
* @throws ArithmeticException if numeric overflow occurs |
|
1059 |
*/ |
|
1060 |
@Override |
|
1061 |
public Temporal addTo(Temporal temporal) { |
|
15658 | 1062 |
if (seconds != 0) { |
1063 |
temporal = temporal.plus(seconds, SECONDS); |
|
1064 |
} |
|
1065 |
if (nanos != 0) { |
|
1066 |
temporal = temporal.plus(nanos, NANOS); |
|
1067 |
} |
|
1068 |
return temporal; |
|
15289 | 1069 |
} |
1070 |
||
1071 |
/** |
|
1072 |
* Subtracts this duration from the specified temporal object. |
|
1073 |
* <p> |
|
1074 |
* This returns a temporal object of the same observable type as the input |
|
1075 |
* with this duration subtracted. |
|
1076 |
* <p> |
|
1077 |
* In most cases, it is clearer to reverse the calling pattern by using |
|
15658 | 1078 |
* {@link Temporal#minus(TemporalAmount)}. |
15289 | 1079 |
* <pre> |
1080 |
* // these two lines are equivalent, but the second approach is recommended |
|
1081 |
* dateTime = thisDuration.subtractFrom(dateTime); |
|
1082 |
* dateTime = dateTime.minus(thisDuration); |
|
1083 |
* </pre> |
|
1084 |
* <p> |
|
15658 | 1085 |
* The calculation will subtract the seconds, then nanos. |
1086 |
* Only non-zero amounts will be added. |
|
15289 | 1087 |
* <p> |
1088 |
* This instance is immutable and unaffected by this method call. |
|
1089 |
* |
|
1090 |
* @param temporal the temporal object to adjust, not null |
|
1091 |
* @return an object of the same type with the adjustment made, not null |
|
1092 |
* @throws DateTimeException if unable to subtract |
|
1093 |
* @throws ArithmeticException if numeric overflow occurs |
|
1094 |
*/ |
|
1095 |
@Override |
|
1096 |
public Temporal subtractFrom(Temporal temporal) { |
|
15658 | 1097 |
if (seconds != 0) { |
1098 |
temporal = temporal.minus(seconds, SECONDS); |
|
1099 |
} |
|
1100 |
if (nanos != 0) { |
|
1101 |
temporal = temporal.minus(nanos, NANOS); |
|
1102 |
} |
|
1103 |
return temporal; |
|
15289 | 1104 |
} |
1105 |
||
1106 |
//----------------------------------------------------------------------- |
|
1107 |
/** |
|
15658 | 1108 |
* Gets the number of minutes in this duration. |
1109 |
* <p> |
|
1110 |
* This returns the total number of minutes in the duration by dividing the |
|
1111 |
* number of seconds by 86400. |
|
1112 |
* This is based on the standard definition of a day as 24 hours. |
|
1113 |
* <p> |
|
1114 |
* This instance is immutable and unaffected by this method call. |
|
1115 |
* |
|
1116 |
* @return the number of minutes in the duration, may be negative |
|
1117 |
*/ |
|
1118 |
public long toDays() { |
|
1119 |
return seconds / SECONDS_PER_DAY; |
|
1120 |
} |
|
1121 |
||
1122 |
/** |
|
1123 |
* Gets the number of minutes in this duration. |
|
1124 |
* <p> |
|
1125 |
* This returns the total number of minutes in the duration by dividing the |
|
1126 |
* number of seconds by 3600. |
|
1127 |
* <p> |
|
1128 |
* This instance is immutable and unaffected by this method call. |
|
1129 |
* |
|
1130 |
* @return the number of minutes in the duration, may be negative |
|
1131 |
*/ |
|
1132 |
public long toHours() { |
|
1133 |
return seconds / SECONDS_PER_HOUR; |
|
1134 |
} |
|
1135 |
||
1136 |
/** |
|
1137 |
* Gets the number of minutes in this duration. |
|
1138 |
* <p> |
|
1139 |
* This returns the total number of minutes in the duration by dividing the |
|
1140 |
* number of seconds by 60. |
|
1141 |
* <p> |
|
1142 |
* This instance is immutable and unaffected by this method call. |
|
1143 |
* |
|
1144 |
* @return the number of minutes in the duration, may be negative |
|
1145 |
*/ |
|
1146 |
public long toMinutes() { |
|
1147 |
return seconds / SECONDS_PER_MINUTE; |
|
1148 |
} |
|
1149 |
||
1150 |
/** |
|
15289 | 1151 |
* Converts this duration to the total length in milliseconds. |
1152 |
* <p> |
|
1153 |
* If this duration is too large to fit in a {@code long} milliseconds, then an |
|
1154 |
* exception is thrown. |
|
1155 |
* <p> |
|
1156 |
* If this duration has greater than millisecond precision, then the conversion |
|
1157 |
* will drop any excess precision information as though the amount in nanoseconds |
|
1158 |
* was subject to integer division by one million. |
|
1159 |
* |
|
1160 |
* @return the total length of the duration in milliseconds |
|
1161 |
* @throws ArithmeticException if numeric overflow occurs |
|
1162 |
*/ |
|
1163 |
public long toMillis() { |
|
1164 |
long millis = Math.multiplyExact(seconds, 1000); |
|
1165 |
millis = Math.addExact(millis, nanos / 1000_000); |
|
1166 |
return millis; |
|
1167 |
} |
|
1168 |
||
1169 |
/** |
|
1170 |
* Converts this duration to the total length in nanoseconds expressed as a {@code long}. |
|
1171 |
* <p> |
|
1172 |
* If this duration is too large to fit in a {@code long} nanoseconds, then an |
|
1173 |
* exception is thrown. |
|
1174 |
* |
|
1175 |
* @return the total length of the duration in nanoseconds |
|
1176 |
* @throws ArithmeticException if numeric overflow occurs |
|
1177 |
*/ |
|
1178 |
public long toNanos() { |
|
16852 | 1179 |
long totalNanos = Math.multiplyExact(seconds, NANOS_PER_SECOND); |
1180 |
totalNanos = Math.addExact(totalNanos, nanos); |
|
1181 |
return totalNanos; |
|
15289 | 1182 |
} |
1183 |
||
1184 |
//----------------------------------------------------------------------- |
|
1185 |
/** |
|
1186 |
* Compares this duration to the specified {@code Duration}. |
|
1187 |
* <p> |
|
1188 |
* The comparison is based on the total length of the durations. |
|
1189 |
* It is "consistent with equals", as defined by {@link Comparable}. |
|
1190 |
* |
|
1191 |
* @param otherDuration the other duration to compare to, not null |
|
1192 |
* @return the comparator value, negative if less, positive if greater |
|
1193 |
*/ |
|
1194 |
@Override |
|
1195 |
public int compareTo(Duration otherDuration) { |
|
1196 |
int cmp = Long.compare(seconds, otherDuration.seconds); |
|
1197 |
if (cmp != 0) { |
|
1198 |
return cmp; |
|
1199 |
} |
|
1200 |
return nanos - otherDuration.nanos; |
|
1201 |
} |
|
1202 |
||
1203 |
//----------------------------------------------------------------------- |
|
1204 |
/** |
|
1205 |
* Checks if this duration is equal to the specified {@code Duration}. |
|
1206 |
* <p> |
|
1207 |
* The comparison is based on the total length of the durations. |
|
1208 |
* |
|
1209 |
* @param otherDuration the other duration, null returns false |
|
1210 |
* @return true if the other duration is equal to this one |
|
1211 |
*/ |
|
1212 |
@Override |
|
1213 |
public boolean equals(Object otherDuration) { |
|
1214 |
if (this == otherDuration) { |
|
1215 |
return true; |
|
1216 |
} |
|
1217 |
if (otherDuration instanceof Duration) { |
|
1218 |
Duration other = (Duration) otherDuration; |
|
1219 |
return this.seconds == other.seconds && |
|
1220 |
this.nanos == other.nanos; |
|
1221 |
} |
|
1222 |
return false; |
|
1223 |
} |
|
1224 |
||
1225 |
/** |
|
1226 |
* A hash code for this duration. |
|
1227 |
* |
|
1228 |
* @return a suitable hash code |
|
1229 |
*/ |
|
1230 |
@Override |
|
1231 |
public int hashCode() { |
|
1232 |
return ((int) (seconds ^ (seconds >>> 32))) + (51 * nanos); |
|
1233 |
} |
|
1234 |
||
1235 |
//----------------------------------------------------------------------- |
|
1236 |
/** |
|
1237 |
* A string representation of this duration using ISO-8601 seconds |
|
15658 | 1238 |
* based representation, such as {@code PT8H6M12.345S}. |
1239 |
* <p> |
|
1240 |
* The format of the returned string will be {@code PTnHnMnS}, where n is |
|
1241 |
* the relevant hours, minutes or seconds part of the duration. |
|
1242 |
* Any fractional seconds are placed after a decimal point i the seconds section. |
|
1243 |
* If a section has a zero value, it is omitted. |
|
1244 |
* The hours, minutes and seconds will all have the same sign. |
|
15289 | 1245 |
* <p> |
15658 | 1246 |
* Examples: |
1247 |
* <pre> |
|
16852 | 1248 |
* "20.345 seconds" -- "PT20.345S |
1249 |
* "15 minutes" (15 * 60 seconds) -- "PT15M" |
|
1250 |
* "10 hours" (10 * 3600 seconds) -- "PT10H" |
|
1251 |
* "2 days" (2 * 86400 seconds) -- "PT48H" |
|
15658 | 1252 |
* </pre> |
1253 |
* Note that multiples of 24 hours are not output as days to avoid confusion |
|
1254 |
* with {@code Period}. |
|
15289 | 1255 |
* |
1256 |
* @return an ISO-8601 representation of this duration, not null |
|
1257 |
*/ |
|
1258 |
@Override |
|
1259 |
public String toString() { |
|
15658 | 1260 |
if (this == ZERO) { |
1261 |
return "PT0S"; |
|
1262 |
} |
|
1263 |
long hours = seconds / SECONDS_PER_HOUR; |
|
1264 |
int minutes = (int) ((seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE); |
|
1265 |
int secs = (int) (seconds % SECONDS_PER_MINUTE); |
|
15289 | 1266 |
StringBuilder buf = new StringBuilder(24); |
1267 |
buf.append("PT"); |
|
15658 | 1268 |
if (hours != 0) { |
1269 |
buf.append(hours).append('H'); |
|
1270 |
} |
|
1271 |
if (minutes != 0) { |
|
1272 |
buf.append(minutes).append('M'); |
|
1273 |
} |
|
1274 |
if (secs == 0 && nanos == 0 && buf.length() > 2) { |
|
1275 |
return buf.toString(); |
|
1276 |
} |
|
1277 |
if (secs < 0 && nanos > 0) { |
|
1278 |
if (secs == -1) { |
|
15289 | 1279 |
buf.append("-0"); |
1280 |
} else { |
|
15658 | 1281 |
buf.append(secs + 1); |
15289 | 1282 |
} |
1283 |
} else { |
|
15658 | 1284 |
buf.append(secs); |
15289 | 1285 |
} |
1286 |
if (nanos > 0) { |
|
1287 |
int pos = buf.length(); |
|
15658 | 1288 |
if (secs < 0) { |
15289 | 1289 |
buf.append(2 * NANOS_PER_SECOND - nanos); |
1290 |
} else { |
|
1291 |
buf.append(nanos + NANOS_PER_SECOND); |
|
1292 |
} |
|
1293 |
while (buf.charAt(buf.length() - 1) == '0') { |
|
1294 |
buf.setLength(buf.length() - 1); |
|
1295 |
} |
|
1296 |
buf.setCharAt(pos, '.'); |
|
1297 |
} |
|
1298 |
buf.append('S'); |
|
1299 |
return buf.toString(); |
|
1300 |
} |
|
1301 |
||
1302 |
//----------------------------------------------------------------------- |
|
1303 |
/** |
|
1304 |
* Writes the object using a |
|
1305 |
* <a href="../../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
|
1306 |
* @serialData |
15289 | 1307 |
* <pre> |
19841
15c8e97d6a14
8024164: JSR310 serialization should be described in details
rriggs
parents:
19030
diff
changeset
|
1308 |
* out.writeByte(1); // identifies a Duration |
15289 | 1309 |
* out.writeLong(seconds); |
1310 |
* out.writeInt(nanos); |
|
1311 |
* </pre> |
|
1312 |
* |
|
1313 |
* @return the instance of {@code Ser}, not null |
|
1314 |
*/ |
|
1315 |
private Object writeReplace() { |
|
1316 |
return new Ser(Ser.DURATION_TYPE, this); |
|
1317 |
} |
|
1318 |
||
1319 |
/** |
|
1320 |
* Defend against malicious streams. |
|
1321 |
* @return never |
|
1322 |
* @throws InvalidObjectException always |
|
1323 |
*/ |
|
19841
15c8e97d6a14
8024164: JSR310 serialization should be described in details
rriggs
parents:
19030
diff
changeset
|
1324 |
private Object readResolve() throws InvalidObjectException { |
15289 | 1325 |
throw new InvalidObjectException("Deserialization via serialization delegate"); |
1326 |
} |
|
1327 |
||
1328 |
void writeExternal(DataOutput out) throws IOException { |
|
1329 |
out.writeLong(seconds); |
|
1330 |
out.writeInt(nanos); |
|
1331 |
} |
|
1332 |
||
1333 |
static Duration readExternal(DataInput in) throws IOException { |
|
1334 |
long seconds = in.readLong(); |
|
1335 |
int nanos = in.readInt(); |
|
1336 |
return Duration.ofSeconds(seconds, nanos); |
|
1337 |
} |
|
1338 |
||
1339 |
} |