1 /*
2 * Copyright (c) 2012, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 /*
27 * This file is available under and governed by the GNU General Public
28 * License version 2 only, as published by the Free Software Foundation.
29 * However, the following notice accompanied the original version of this
30 * file:
31 *
32 * Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos
33 *
34 * All rights reserved.
35 *
36 * Redistribution and use in source and binary forms, with or without
37 * modification, are permitted provided that the following conditions are met:
38 *
39 * * Redistributions of source code must retain the above copyright notice,
40 * this list of conditions and the following disclaimer.
41 *
42 * * Redistributions in binary form must reproduce the above copyright notice,
43 * this list of conditions and the following disclaimer in the documentation
44 * and/or other materials provided with the distribution.
45 *
46 * * Neither the name of JSR-310 nor the names of its contributors
47 * may be used to endorse or promote products derived from this software
48 * without specific prior written permission.
49 *
50 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
51 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
52 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
53 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
54 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
55 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
56 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
57 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
58 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
59 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
60 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
61 */
62 package java.time;
63
64 import static java.time.LocalTime.MINUTES_PER_HOUR;
65 import static java.time.LocalTime.NANOS_PER_MILLI;
66 import static java.time.LocalTime.NANOS_PER_SECOND;
67 import static java.time.LocalTime.SECONDS_PER_DAY;
68 import static java.time.LocalTime.SECONDS_PER_HOUR;
69 import static java.time.LocalTime.SECONDS_PER_MINUTE;
70 import static java.time.temporal.ChronoField.NANO_OF_SECOND;
71 import static java.time.temporal.ChronoUnit.DAYS;
72 import static java.time.temporal.ChronoUnit.NANOS;
73 import static java.time.temporal.ChronoUnit.SECONDS;
74
75 import java.io.DataInput;
76 import java.io.DataOutput;
77 import java.io.IOException;
78 import java.io.InvalidObjectException;
79 import java.io.ObjectInputStream;
80 import java.io.Serializable;
81 import java.math.BigDecimal;
82 import java.math.BigInteger;
83 import java.math.RoundingMode;
84 import java.time.format.DateTimeParseException;
85 import java.time.temporal.ChronoField;
86 import java.time.temporal.ChronoUnit;
87 import java.time.temporal.Temporal;
88 import java.time.temporal.TemporalAmount;
89 import java.time.temporal.TemporalUnit;
90 import java.time.temporal.UnsupportedTemporalTypeException;
91 import java.util.List;
92 import java.util.Objects;
93 import java.util.regex.Matcher;
94 import java.util.regex.Pattern;
95
96 /**
97 * A time-based amount of time, such as '34.5 seconds'.
98 * <p>
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.
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.
113 * The model is of a directed duration, meaning that the duration may be negative.
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 * <p>
121 * This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
122 * class; programmers should treat instances that are {@linkplain #equals(Object) equal}
123 * as interchangeable and should not use instances for synchronization, mutexes, or
124 * with {@linkplain java.lang.ref.Reference object references}.
125 *
126 * <div class="preview-block">
127 * <div class="preview-comment">
128 * When preview features are enabled, {@code Duration} is a {@linkplain Class#isValue value class}.
129 * Use of value class instances for synchronization, mutexes, or with
130 * {@linkplain java.lang.ref.Reference object references} result in
131 * {@link IdentityException}.
132 * </div>
133 * </div>
134 *
135 * @implSpec
136 * This class is immutable and thread-safe.
137 *
138 * @since 1.8
139 */
140 @jdk.internal.ValueBased
141 @jdk.internal.MigratedValueClass
142 public final class Duration
143 implements TemporalAmount, Comparable<Duration>, Serializable {
144
145 /**
146 * Constant for a duration of zero.
147 */
148 public static final Duration ZERO = new Duration(0, 0);
149 /**
150 * The minimum supported {@code Duration}, which is {@link Long#MIN_VALUE}
151 * seconds.
152 *
153 * @apiNote This constant represents the smallest possible instance of
154 * {@code Duration}. Since {@code Duration} is directed, the smallest
155 * possible duration is negative.
156 *
157 * The constant is intended to be used as a sentinel value or in tests.
158 * Care should be taken when performing arithmetic on {@code MIN} as there
159 * is a high risk that {@link ArithmeticException} or {@link DateTimeException}
160 * will be thrown.
161 *
162 * @since 26
163 */
164 public static final Duration MIN = new Duration(Long.MIN_VALUE, 0);
165 /**
166 * The maximum supported {@code Duration}, which is {@link Long#MAX_VALUE}
167 * seconds and {@code 999,999,999} nanoseconds.
168 *
169 * @apiNote This constant represents the largest possible instance of
170 * {@code Duration}.
171 *
172 * The constant is intended to be used as a sentinel value or in tests.
173 * Care should be taken when performing arithmetic on {@code MAX} as there
174 * is a high risk that {@link ArithmeticException} or {@link DateTimeException}
175 * will be thrown.
176 *
177 * @since 26
178 */
179 public static final Duration MAX = new Duration(Long.MAX_VALUE, 999_999_999);
180 /**
181 * Serialization version.
182 */
183 @java.io.Serial
184 private static final long serialVersionUID = 3078945930695997490L;
185 /**
186 * Constant for nanos per second.
187 */
188 private static final BigInteger BI_NANOS_PER_SECOND = BigInteger.valueOf(NANOS_PER_SECOND);
189 /**
190 * The pattern for parsing.
191 */
192 private static class Lazy {
193 static final Pattern PATTERN =
194 Pattern.compile("([-+]?)P(?:([-+]?[0-9]+)D)?" +
195 "(T(?:([-+]?[0-9]+)H)?(?:([-+]?[0-9]+)M)?(?:([-+]?[0-9]+)(?:[.,]([0-9]{0,9}))?S)?)?",
196 Pattern.CASE_INSENSITIVE);
197 }
198
199 /**
200 * @serial The number of seconds in the duration.
201 */
202 private final long seconds;
203 /**
204 * @serial The number of nanoseconds in the duration, expressed as a fraction of the
205 * number of seconds. This is always positive, and never exceeds 999,999,999.
206 */
207 private final int nanos;
208
209 //-----------------------------------------------------------------------
210 /**
211 * Obtains a {@code Duration} representing a number of standard 24 hour days.
212 * <p>
213 * The seconds are calculated based on the standard definition of a day,
214 * where each day is 86,400 seconds which implies a 24 hour day.
215 * The nanosecond in second field is set to zero.
216 *
217 * @param days the number of days, positive or negative
218 * @return a {@code Duration}, not null
219 * @throws ArithmeticException if the input days exceeds the capacity of {@code Duration}
220 */
221 public static Duration ofDays(long days) {
222 return create(Math.multiplyExact(days, SECONDS_PER_DAY), 0);
223 }
224
225 /**
226 * Obtains a {@code Duration} representing a number of standard hours.
227 * <p>
228 * The seconds are calculated based on the standard definition of an hour,
229 * where each hour is 3,600 seconds.
230 * The nanosecond in second field is set to zero.
231 *
232 * @param hours the number of hours, positive or negative
233 * @return a {@code Duration}, not null
234 * @throws ArithmeticException if the input hours exceeds the capacity of {@code Duration}
235 */
236 public static Duration ofHours(long hours) {
237 return create(Math.multiplyExact(hours, SECONDS_PER_HOUR), 0);
238 }
239
240 /**
241 * Obtains a {@code Duration} representing a number of standard minutes.
242 * <p>
243 * The seconds are calculated based on the standard definition of a minute,
244 * where each minute is 60 seconds.
245 * The nanosecond in second field is set to zero.
246 *
247 * @param minutes the number of minutes, positive or negative
248 * @return a {@code Duration}, not null
249 * @throws ArithmeticException if the input minutes exceeds the capacity of {@code Duration}
250 */
251 public static Duration ofMinutes(long minutes) {
252 return create(Math.multiplyExact(minutes, SECONDS_PER_MINUTE), 0);
253 }
254
255 //-----------------------------------------------------------------------
256 /**
257 * Obtains a {@code Duration} representing a number of seconds.
258 * <p>
259 * The nanosecond in second field is set to zero.
260 *
261 * @param seconds the number of seconds, positive or negative
262 * @return a {@code Duration}, not null
263 */
264 public static Duration ofSeconds(long seconds) {
265 return create(seconds, 0);
266 }
267
268 /**
269 * Obtains a {@code Duration} representing a number of seconds and an
270 * adjustment in nanoseconds.
271 * <p>
272 * This method allows an arbitrary number of nanoseconds to be passed in.
273 * The factory will alter the values of the second and nanosecond in order
274 * to ensure that the stored nanosecond is in the range 0 to 999,999,999.
275 * For example, the following will result in exactly the same duration:
276 * <pre>
277 * Duration.ofSeconds(3, 1);
278 * Duration.ofSeconds(4, -999_999_999);
279 * Duration.ofSeconds(2, 1000_000_001);
280 * </pre>
281 *
282 * @param seconds the number of seconds, positive or negative
283 * @param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative
284 * @return a {@code Duration}, not null
285 * @throws ArithmeticException if the adjustment causes the seconds to exceed the capacity of {@code Duration}
286 */
287 public static Duration ofSeconds(long seconds, long nanoAdjustment) {
288 long secs = Math.addExact(seconds, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND));
289 int nos = (int) Math.floorMod(nanoAdjustment, NANOS_PER_SECOND);
290 return create(secs, nos);
291 }
292
293 //-----------------------------------------------------------------------
294 /**
295 * Obtains a {@code Duration} representing a number of milliseconds.
296 * <p>
297 * The seconds and nanoseconds are extracted from the specified milliseconds.
298 *
299 * @param millis the number of milliseconds, positive or negative
300 * @return a {@code Duration}, not null
301 */
302 public static Duration ofMillis(long millis) {
303 long secs = millis / 1000;
304 int mos = (int) (millis % 1000);
305 if (mos < 0) {
306 mos += 1000;
307 secs--;
308 }
309 return create(secs, mos * 1000_000);
310 }
311
312 //-----------------------------------------------------------------------
313 /**
314 * Obtains a {@code Duration} representing a number of nanoseconds.
315 * <p>
316 * The seconds and nanoseconds are extracted from the specified nanoseconds.
317 *
318 * @param nanos the number of nanoseconds, positive or negative
319 * @return a {@code Duration}, not null
320 */
321 public static Duration ofNanos(long nanos) {
322 long secs = nanos / NANOS_PER_SECOND;
323 int nos = (int) (nanos % NANOS_PER_SECOND);
324 if (nos < 0) {
325 nos += (int) NANOS_PER_SECOND;
326 secs--;
327 }
328 return create(secs, nos);
329 }
330
331 //-----------------------------------------------------------------------
332 /**
333 * Obtains a {@code Duration} representing an amount in the specified unit.
334 * <p>
335 * The parameters represent the two parts of a phrase like '6 Hours'. For example:
336 * <pre>
337 * Duration.of(3, SECONDS);
338 * Duration.of(465, HOURS);
339 * </pre>
340 * Only a subset of units are accepted by this method.
341 * The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or
342 * be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception.
343 *
344 * @param amount the amount of the duration, measured in terms of the unit, positive or negative
345 * @param unit the unit that the duration is measured in, must have an exact duration, not null
346 * @return a {@code Duration}, not null
347 * @throws DateTimeException if the unit has an estimated duration
348 * @throws ArithmeticException if a numeric overflow occurs
349 */
350 public static Duration of(long amount, TemporalUnit unit) {
351 return ZERO.plus(amount, unit);
352 }
353
354 //-----------------------------------------------------------------------
355 /**
356 * Obtains an instance of {@code Duration} from a temporal amount.
357 * <p>
358 * This obtains a duration based on the specified amount.
359 * A {@code TemporalAmount} represents an amount of time, which may be
360 * date-based or time-based, which this factory extracts to a duration.
361 * <p>
362 * The conversion loops around the set of units from the amount and uses
363 * the {@linkplain TemporalUnit#getDuration() duration} of the unit to
364 * calculate the total {@code Duration}.
365 * Only a subset of units are accepted by this method. The unit must either
366 * have an {@linkplain TemporalUnit#isDurationEstimated() exact duration}
367 * or be {@link ChronoUnit#DAYS} which is treated as 24 hours.
368 * If any other units are found then an exception is thrown.
369 *
370 * @param amount the temporal amount to convert, not null
371 * @return the equivalent duration, not null
372 * @throws DateTimeException if unable to convert to a {@code Duration}
373 * @throws ArithmeticException if numeric overflow occurs
374 */
375 public static Duration from(TemporalAmount amount) {
376 Objects.requireNonNull(amount, "amount");
377 Duration duration = ZERO;
378 for (TemporalUnit unit : amount.getUnits()) {
379 duration = duration.plus(amount.get(unit), unit);
380 }
381 return duration;
382 }
383
384 //-----------------------------------------------------------------------
385 /**
386 * Obtains a {@code Duration} from a text string such as {@code PnDTnHnMn.nS}.
387 * <p>
388 * This will parse a textual representation of a duration, including the
389 * string produced by {@code toString()}. The formats accepted are based
390 * on the ISO-8601 duration format {@code PnDTnHnMn.nS} with days
391 * considered to be exactly 24 hours.
392 * <p>
393 * The string starts with an optional sign, denoted by the ASCII negative
394 * or positive symbol. If negative, the whole duration is negated.
395 * The ASCII letter "P" is next in upper or lower case.
396 * There are then four sections, each consisting of a number and a suffix.
397 * The sections have suffixes in ASCII of "D", "H", "M" and "S" for
398 * days, hours, minutes and seconds, accepted in upper or lower case.
399 * The suffixes must occur in order. The ASCII letter "T" must occur before
400 * the first occurrence, if any, of an hour, minute or second section.
401 * At least one of the four sections must be present, and if "T" is present
402 * there must be at least one section after the "T".
403 * The number part of each section must consist of one or more ASCII digits.
404 * The number may be prefixed by the ASCII negative or positive symbol.
405 * The number of days, hours and minutes must parse to a {@code long}.
406 * The number of seconds must parse to a {@code long} with optional fraction.
407 * The decimal point may be either a dot or a comma.
408 * The fractional part may have from zero to 9 digits.
409 * <p>
410 * The leading plus/minus sign, and negative values for other units are
411 * not part of the ISO-8601 standard.
412 * <p>
413 * Examples:
414 * <pre>
415 * "PT20.345S" -- parses as "20.345 seconds"
416 * "PT15M" -- parses as "15 minutes" (where a minute is 60 seconds)
417 * "PT10H" -- parses as "10 hours" (where an hour is 3,600 seconds)
418 * "P2D" -- parses as "2 days" (where a day is 24 hours or 86,400 seconds)
419 * "P2DT3H4M" -- parses as "2 days, 3 hours and 4 minutes"
420 * "PT-6H3M" -- parses as "-6 hours and +3 minutes"
421 * "-PT6H3M" -- parses as "-6 hours and -3 minutes"
422 * "-PT-6H+3M" -- parses as "+6 hours and -3 minutes"
423 * </pre>
424 *
425 * @param text the text to parse, not null
426 * @return the parsed duration, not null
427 * @throws DateTimeParseException if the text cannot be parsed to a duration
428 */
429 public static Duration parse(CharSequence text) {
430 Objects.requireNonNull(text, "text");
431 Matcher matcher = Lazy.PATTERN.matcher(text);
432 if (matcher.matches()) {
433 // check for letter T but no time sections
434 if (!charMatch(text, matcher.start(3), matcher.end(3), 'T')) {
435 boolean negate = charMatch(text, matcher.start(1), matcher.end(1), '-');
436
437 int dayStart = matcher.start(2), dayEnd = matcher.end(2);
438 int hourStart = matcher.start(4), hourEnd = matcher.end(4);
439 int minuteStart = matcher.start(5), minuteEnd = matcher.end(5);
440 int secondStart = matcher.start(6), secondEnd = matcher.end(6);
441 int fractionStart = matcher.start(7), fractionEnd = matcher.end(7);
442
443 if (dayStart >= 0 || hourStart >= 0 || minuteStart >= 0 || secondStart >= 0) {
444 long daysAsSecs = parseNumber(text, dayStart, dayEnd, SECONDS_PER_DAY, "days");
445 long hoursAsSecs = parseNumber(text, hourStart, hourEnd, SECONDS_PER_HOUR, "hours");
446 long minsAsSecs = parseNumber(text, minuteStart, minuteEnd, SECONDS_PER_MINUTE, "minutes");
447 long seconds = parseNumber(text, secondStart, secondEnd, 1, "seconds");
448 boolean negativeSecs = secondStart >= 0 && text.charAt(secondStart) == '-';
449 int nanos = parseFraction(text, fractionStart, fractionEnd, negativeSecs ? -1 : 1);
450 try {
451 return create(negate, daysAsSecs, hoursAsSecs, minsAsSecs, seconds, nanos);
452 } catch (ArithmeticException ex) {
453 throw new DateTimeParseException("Text cannot be parsed to a Duration: overflow", text, 0, ex);
454 }
455 }
456 }
457 }
458 throw new DateTimeParseException("Text cannot be parsed to a Duration", text, 0);
459 }
460
461 private static boolean charMatch(CharSequence text, int start, int end, char c) {
462 return (start >= 0 && end == start + 1 && text.charAt(start) == c);
463 }
464
465 private static long parseNumber(CharSequence text, int start, int end, int multiplier, String errorText) {
466 // regex limits to [-+]?[0-9]+
467 if (start < 0 || end < 0) {
468 return 0;
469 }
470 try {
471 long val = Long.parseLong(text, start, end, 10);
472 return Math.multiplyExact(val, multiplier);
473 } catch (NumberFormatException | ArithmeticException ex) {
474 throw new DateTimeParseException("Text cannot be parsed to a Duration: " + errorText, text, 0, ex);
475 }
476 }
477
478 private static int parseFraction(CharSequence text, int start, int end, int negate) {
479 // regex limits to [0-9]{0,9}
480 if (start < 0 || end < 0 || end - start == 0) {
481 return 0;
482 }
483 try {
484 int fraction = Integer.parseInt(text, start, end, 10);
485
486 // for number strings smaller than 9 digits, interpret as if there
487 // were trailing zeros
488 for (int i = end - start; i < 9; i++) {
489 fraction *= 10;
490 }
491 return fraction * negate;
492 } catch (NumberFormatException | ArithmeticException ex) {
493 throw new DateTimeParseException("Text cannot be parsed to a Duration: fraction", text, 0, ex);
494 }
495 }
496
497 private static Duration create(boolean negate, long daysAsSecs, long hoursAsSecs, long minsAsSecs, long secs, int nanos) {
498 long seconds = Math.addExact(daysAsSecs, Math.addExact(hoursAsSecs, Math.addExact(minsAsSecs, secs)));
499 if (negate) {
500 return ofSeconds(seconds, nanos).negated();
501 }
502 return ofSeconds(seconds, nanos);
503 }
504
505 //-----------------------------------------------------------------------
506 /**
507 * Obtains a {@code Duration} representing the duration between two temporal objects.
508 * <p>
509 * This calculates the duration between two temporal objects. If the objects
510 * are of different types, then the duration is calculated based on the type
511 * of the first object. For example, if the first argument is a {@code LocalTime}
512 * then the second argument is converted to a {@code LocalTime}.
513 * <p>
514 * The specified temporal objects must support the {@link ChronoUnit#SECONDS SECONDS} unit.
515 * For full accuracy, either the {@link ChronoUnit#NANOS NANOS} unit or the
516 * {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} field should be supported.
517 * <p>
518 * The result of this method can be a negative duration if the end is before the start.
519 * To guarantee a positive duration, call {@link #abs()} on the result.
520 *
521 * @param startInclusive the start instant, inclusive, not null
522 * @param endExclusive the end instant, exclusive, not null
523 * @return a {@code Duration}, not null
524 * @throws DateTimeException if the seconds between the temporals cannot be obtained
525 * @throws ArithmeticException if the calculation exceeds the capacity of {@code Duration}
526 */
527 public static Duration between(Temporal startInclusive, Temporal endExclusive) {
528 long secs = startInclusive.until(endExclusive, SECONDS);
529 if (secs == 0) {
530 // We don't know which Temporal is earlier, so the adjustment below would not work.
531 // But we do know that there's no danger of until(NANOS) overflowing in that case.
532 return ofNanos(startInclusive.until(endExclusive, NANOS));
533 }
534 long nanos;
535 try {
536 nanos = endExclusive.getLong(NANO_OF_SECOND) - startInclusive.getLong(NANO_OF_SECOND);
537 } catch (DateTimeException ex2) {
538 nanos = 0;
539 }
540 if (nanos < 0 && secs > 0) {
541 // ofSeconds will subtract one even though until(SECONDS) already gave the correct
542 // number of seconds. So compensate. Similarly for the secs < 0 case below.
543 secs++;
544 } else if (nanos > 0 && secs < 0) {
545 secs--;
546 }
547 return ofSeconds(secs, nanos);
548 }
549
550 //-----------------------------------------------------------------------
551 /**
552 * Obtains an instance of {@code Duration} using seconds and nanoseconds.
553 *
554 * @param seconds the length of the duration in seconds, positive or negative
555 * @param nanoAdjustment the nanosecond adjustment within the second, from 0 to 999,999,999
556 */
557 private static Duration create(long seconds, int nanoAdjustment) {
558 if ((seconds | nanoAdjustment) == 0) {
559 return ZERO;
560 }
561 return new Duration(seconds, nanoAdjustment);
562 }
563
564 /**
565 * Constructs an instance of {@code Duration} using seconds and nanoseconds.
566 *
567 * @param seconds the length of the duration in seconds, positive or negative
568 * @param nanos the nanoseconds within the second, from 0 to 999,999,999
569 */
570 private Duration(long seconds, int nanos) {
571 this.seconds = seconds;
572 this.nanos = nanos;
573 }
574
575 //-----------------------------------------------------------------------
576 /**
577 * Gets the value of the requested unit.
578 * <p>
579 * This returns a value for each of the two supported units,
580 * {@link ChronoUnit#SECONDS SECONDS} and {@link ChronoUnit#NANOS NANOS}.
581 * All other units throw an exception.
582 *
583 * @param unit the {@code TemporalUnit} for which to return the value
584 * @return the long value of the unit
585 * @throws DateTimeException if the unit is not supported
586 * @throws UnsupportedTemporalTypeException if the unit is not supported
587 */
588 @Override
589 public long get(TemporalUnit unit) {
590 if (unit == SECONDS) {
591 return seconds;
592 } else if (unit == NANOS) {
593 return nanos;
594 } else {
595 throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
596 }
597 }
598
599 /**
600 * Gets the set of units supported by this duration.
601 * <p>
602 * The supported units are {@link ChronoUnit#SECONDS SECONDS},
603 * and {@link ChronoUnit#NANOS NANOS}.
604 * They are returned in the order seconds, nanos.
605 * <p>
606 * This set can be used in conjunction with {@link #get(TemporalUnit)}
607 * to access the entire state of the duration.
608 *
609 * @return a list containing the seconds and nanos units, not null
610 */
611 @Override
612 public List<TemporalUnit> getUnits() {
613 return DurationUnits.UNITS;
614 }
615
616 /**
617 * Private class to delay initialization of this list until needed.
618 * The circular dependency between Duration and ChronoUnit prevents
619 * the simple initialization in Duration.
620 */
621 private static class DurationUnits {
622 static final List<TemporalUnit> UNITS = List.of(SECONDS, NANOS);
623 }
624
625 //-----------------------------------------------------------------------
626 /**
627 * Checks if this duration is positive, excluding zero.
628 * <p>
629 * A {@code Duration} represents a directed distance between two points on
630 * the time-line and can therefore be positive, zero or negative.
631 * This method checks whether the length is greater than zero.
632 *
633 * @return true if this duration has a total length greater than zero
634 * @since 18
635 */
636 public boolean isPositive() {
637 return (seconds | nanos) > 0;
638 }
639
640 /**
641 * Checks if this duration is zero length.
642 * <p>
643 * A {@code Duration} represents a directed distance between two points on
644 * the time-line and can therefore be positive, zero or negative.
645 * This method checks whether the length is zero.
646 *
647 * @return true if this duration has a total length equal to zero
648 */
649 public boolean isZero() {
650 return (seconds | nanos) == 0;
651 }
652
653 /**
654 * Checks if this duration is negative, excluding zero.
655 * <p>
656 * A {@code Duration} represents a directed distance between two points on
657 * the time-line and can therefore be positive, zero or negative.
658 * This method checks whether the length is less than zero.
659 *
660 * @return true if this duration has a total length less than zero
661 */
662 public boolean isNegative() {
663 return seconds < 0;
664 }
665
666 //-----------------------------------------------------------------------
667 /**
668 * Gets the number of seconds in this duration.
669 * <p>
670 * The length of the duration is stored using two fields - seconds and nanoseconds.
671 * The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to
672 * the length in seconds.
673 * The total duration is defined by calling this method and {@link #getNano()}.
674 * <p>
675 * A {@code Duration} represents a directed distance between two points on the time-line.
676 * A negative duration is expressed by the negative sign of the seconds part.
677 * A duration of -1 nanosecond is stored as -1 seconds plus 999,999,999 nanoseconds.
678 *
679 * @return the whole seconds part of the length of the duration, positive or negative
680 */
681 public long getSeconds() {
682 return seconds;
683 }
684
685 /**
686 * Gets the number of nanoseconds within the second in this duration.
687 * <p>
688 * The length of the duration is stored using two fields - seconds and nanoseconds.
689 * The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to
690 * the length in seconds.
691 * The total duration is defined by calling this method and {@link #getSeconds()}.
692 * <p>
693 * A {@code Duration} represents a directed distance between two points on the time-line.
694 * A negative duration is expressed by the negative sign of the seconds part.
695 * A duration of -1 nanosecond is stored as -1 seconds plus 999,999,999 nanoseconds.
696 *
697 * @return the nanoseconds within the second part of the length of the duration, from 0 to 999,999,999
698 */
699 public int getNano() {
700 return nanos;
701 }
702
703 //-----------------------------------------------------------------------
704 /**
705 * Returns a copy of this duration with the specified amount of seconds.
706 * <p>
707 * This returns a duration with the specified seconds, retaining the
708 * nano-of-second part of this duration.
709 * <p>
710 * This instance is immutable and unaffected by this method call.
711 *
712 * @param seconds the seconds to represent, may be negative
713 * @return a {@code Duration} based on this duration with the requested seconds, not null
714 */
715 public Duration withSeconds(long seconds) {
716 return create(seconds, nanos);
717 }
718
719 /**
720 * Returns a copy of this duration with the specified nano-of-second.
721 * <p>
722 * This returns a duration with the specified nano-of-second, retaining the
723 * seconds part of this duration.
724 * <p>
725 * This instance is immutable and unaffected by this method call.
726 *
727 * @param nanoOfSecond the nano-of-second to represent, from 0 to 999,999,999
728 * @return a {@code Duration} based on this duration with the requested nano-of-second, not null
729 * @throws DateTimeException if the nano-of-second is invalid
730 */
731 public Duration withNanos(int nanoOfSecond) {
732 NANO_OF_SECOND.checkValidIntValue(nanoOfSecond);
733 return create(seconds, nanoOfSecond);
734 }
735
736 //-----------------------------------------------------------------------
737 /**
738 * Returns a copy of this duration with the specified duration added.
739 * <p>
740 * This instance is immutable and unaffected by this method call.
741 *
742 * @param duration the duration to add, positive or negative, not null
743 * @return a {@code Duration} based on this duration with the specified duration added, not null
744 * @throws ArithmeticException if numeric overflow occurs
745 */
746 public Duration plus(Duration duration) {
747 return plus(duration.getSeconds(), duration.getNano());
748 }
749
750 /**
751 * Returns a copy of this duration with the specified duration added.
752 * <p>
753 * The duration amount is measured in terms of the specified unit.
754 * Only a subset of units are accepted by this method.
755 * The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or
756 * be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception.
757 * <p>
758 * This instance is immutable and unaffected by this method call.
759 *
760 * @param amountToAdd the amount to add, measured in terms of the unit, positive or negative
761 * @param unit the unit that the amount is measured in, must have an exact duration, not null
762 * @return a {@code Duration} based on this duration with the specified duration added, not null
763 * @throws UnsupportedTemporalTypeException if the unit is not supported
764 * @throws ArithmeticException if numeric overflow occurs
765 */
766 public Duration plus(long amountToAdd, TemporalUnit unit) {
767 Objects.requireNonNull(unit, "unit");
768 if (unit == DAYS) {
769 return plus(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY), 0);
770 }
771 if (unit.isDurationEstimated()) {
772 throw new UnsupportedTemporalTypeException("Unit must not have an estimated duration");
773 }
774 if (amountToAdd == 0) {
775 return this;
776 }
777 if (unit instanceof ChronoUnit chronoUnit) {
778 return switch (chronoUnit) {
779 case NANOS -> plusNanos(amountToAdd);
780 case MICROS -> plusSeconds((amountToAdd / (1000_000L * 1000)) * 1000).plusNanos((amountToAdd % (1000_000L * 1000)) * 1000);
781 case MILLIS -> plusMillis(amountToAdd);
782 case SECONDS -> plusSeconds(amountToAdd);
783 default -> plusSeconds(Math.multiplyExact(unit.getDuration().seconds, amountToAdd));
784 };
785 }
786 Duration duration = unit.getDuration().multipliedBy(amountToAdd);
787 return plusSeconds(duration.getSeconds()).plusNanos(duration.getNano());
788 }
789
790 //-----------------------------------------------------------------------
791 /**
792 * Returns a copy of this duration with the specified duration in standard 24 hour days added.
793 * <p>
794 * The number of days is multiplied by 86,400 to obtain the number of seconds to add.
795 * This is based on the standard definition of a day as 24 hours.
796 * <p>
797 * This instance is immutable and unaffected by this method call.
798 *
799 * @param daysToAdd the days to add, positive or negative
800 * @return a {@code Duration} based on this duration with the specified days added, not null
801 * @throws ArithmeticException if numeric overflow occurs
802 */
803 public Duration plusDays(long daysToAdd) {
804 return plus(Math.multiplyExact(daysToAdd, SECONDS_PER_DAY), 0);
805 }
806
807 /**
808 * Returns a copy of this duration with the specified duration in hours added.
809 * <p>
810 * This instance is immutable and unaffected by this method call.
811 *
812 * @param hoursToAdd the hours to add, positive or negative
813 * @return a {@code Duration} based on this duration with the specified hours added, not null
814 * @throws ArithmeticException if numeric overflow occurs
815 */
816 public Duration plusHours(long hoursToAdd) {
817 return plus(Math.multiplyExact(hoursToAdd, SECONDS_PER_HOUR), 0);
818 }
819
820 /**
821 * Returns a copy of this duration with the specified duration in minutes added.
822 * <p>
823 * This instance is immutable and unaffected by this method call.
824 *
825 * @param minutesToAdd the minutes to add, positive or negative
826 * @return a {@code Duration} based on this duration with the specified minutes added, not null
827 * @throws ArithmeticException if numeric overflow occurs
828 */
829 public Duration plusMinutes(long minutesToAdd) {
830 return plus(Math.multiplyExact(minutesToAdd, SECONDS_PER_MINUTE), 0);
831 }
832
833 /**
834 * Returns a copy of this duration with the specified duration in seconds added.
835 * <p>
836 * This instance is immutable and unaffected by this method call.
837 *
838 * @param secondsToAdd the seconds to add, positive or negative
839 * @return a {@code Duration} based on this duration with the specified seconds added, not null
840 * @throws ArithmeticException if numeric overflow occurs
841 */
842 public Duration plusSeconds(long secondsToAdd) {
843 return plus(secondsToAdd, 0);
844 }
845
846 /**
847 * Returns a copy of this duration with the specified duration in milliseconds added.
848 * <p>
849 * This instance is immutable and unaffected by this method call.
850 *
851 * @param millisToAdd the milliseconds to add, positive or negative
852 * @return a {@code Duration} based on this duration with the specified milliseconds added, not null
853 * @throws ArithmeticException if numeric overflow occurs
854 */
855 public Duration plusMillis(long millisToAdd) {
856 return plus(millisToAdd / 1000, (millisToAdd % 1000) * 1000_000);
857 }
858
859 /**
860 * Returns a copy of this duration with the specified duration in nanoseconds added.
861 * <p>
862 * This instance is immutable and unaffected by this method call.
863 *
864 * @param nanosToAdd the nanoseconds to add, positive or negative
865 * @return a {@code Duration} based on this duration with the specified nanoseconds added, not null
866 * @throws ArithmeticException if numeric overflow occurs
867 */
868 public Duration plusNanos(long nanosToAdd) {
869 return plus(0, nanosToAdd);
870 }
871
872 /**
873 * Returns a copy of this duration with the specified duration added.
874 * <p>
875 * This instance is immutable and unaffected by this method call.
876 *
877 * @param secondsToAdd the seconds to add, positive or negative
878 * @param nanosToAdd the nanos to add, positive or negative
879 * @return a {@code Duration} based on this duration with the specified seconds added, not null
880 * @throws ArithmeticException if numeric overflow occurs
881 */
882 private Duration plus(long secondsToAdd, long nanosToAdd) {
883 if ((secondsToAdd | nanosToAdd) == 0) {
884 return this;
885 }
886 long epochSec = Math.addExact(seconds, secondsToAdd);
887 epochSec = Math.addExact(epochSec, nanosToAdd / NANOS_PER_SECOND);
888 nanosToAdd = nanosToAdd % NANOS_PER_SECOND;
889 long nanoAdjustment = nanos + nanosToAdd; // safe int+NANOS_PER_SECOND
890 return ofSeconds(epochSec, nanoAdjustment);
891 }
892
893 //-----------------------------------------------------------------------
894 /**
895 * Returns a copy of this duration with the specified duration subtracted.
896 * <p>
897 * This instance is immutable and unaffected by this method call.
898 *
899 * @param duration the duration to subtract, positive or negative, not null
900 * @return a {@code Duration} based on this duration with the specified duration subtracted, not null
901 * @throws ArithmeticException if numeric overflow occurs
902 */
903 public Duration minus(Duration duration) {
904 long secsToSubtract = duration.getSeconds();
905 int nanosToSubtract = duration.getNano();
906 if (secsToSubtract == Long.MIN_VALUE) {
907 return plus(Long.MAX_VALUE, -nanosToSubtract).plus(1, 0);
908 }
909 return plus(-secsToSubtract, -nanosToSubtract);
910 }
911
912 /**
913 * Returns a copy of this duration with the specified duration subtracted.
914 * <p>
915 * The duration amount is measured in terms of the specified unit.
916 * Only a subset of units are accepted by this method.
917 * The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or
918 * be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception.
919 * <p>
920 * This instance is immutable and unaffected by this method call.
921 *
922 * @param amountToSubtract the amount to subtract, measured in terms of the unit, positive or negative
923 * @param unit the unit that the amount is measured in, must have an exact duration, not null
924 * @return a {@code Duration} based on this duration with the specified duration subtracted, not null
925 * @throws ArithmeticException if numeric overflow occurs
926 */
927 public Duration minus(long amountToSubtract, TemporalUnit unit) {
928 return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
929 }
930
931 //-----------------------------------------------------------------------
932 /**
933 * Returns a copy of this duration with the specified duration in standard 24 hour days subtracted.
934 * <p>
935 * The number of days is multiplied by 86,400 to obtain the number of seconds to subtract.
936 * This is based on the standard definition of a day as 24 hours.
937 * <p>
938 * This instance is immutable and unaffected by this method call.
939 *
940 * @param daysToSubtract the days to subtract, positive or negative
941 * @return a {@code Duration} based on this duration with the specified days subtracted, not null
942 * @throws ArithmeticException if numeric overflow occurs
943 */
944 public Duration minusDays(long daysToSubtract) {
945 return (daysToSubtract == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-daysToSubtract));
946 }
947
948 /**
949 * Returns a copy of this duration with the specified duration in hours subtracted.
950 * <p>
951 * The number of hours is multiplied by 3,600 to obtain the number of seconds to subtract.
952 * <p>
953 * This instance is immutable and unaffected by this method call.
954 *
955 * @param hoursToSubtract the hours to subtract, positive or negative
956 * @return a {@code Duration} based on this duration with the specified hours subtracted, not null
957 * @throws ArithmeticException if numeric overflow occurs
958 */
959 public Duration minusHours(long hoursToSubtract) {
960 return (hoursToSubtract == Long.MIN_VALUE ? plusHours(Long.MAX_VALUE).plusHours(1) : plusHours(-hoursToSubtract));
961 }
962
963 /**
964 * Returns a copy of this duration with the specified duration in minutes subtracted.
965 * <p>
966 * The number of minutes is multiplied by 60 to obtain the number of seconds to subtract.
967 * <p>
968 * This instance is immutable and unaffected by this method call.
969 *
970 * @param minutesToSubtract the minutes to subtract, positive or negative
971 * @return a {@code Duration} based on this duration with the specified minutes subtracted, not null
972 * @throws ArithmeticException if numeric overflow occurs
973 */
974 public Duration minusMinutes(long minutesToSubtract) {
975 return (minutesToSubtract == Long.MIN_VALUE ? plusMinutes(Long.MAX_VALUE).plusMinutes(1) : plusMinutes(-minutesToSubtract));
976 }
977
978 /**
979 * Returns a copy of this duration with the specified duration in seconds subtracted.
980 * <p>
981 * This instance is immutable and unaffected by this method call.
982 *
983 * @param secondsToSubtract the seconds to subtract, positive or negative
984 * @return a {@code Duration} based on this duration with the specified seconds subtracted, not null
985 * @throws ArithmeticException if numeric overflow occurs
986 */
987 public Duration minusSeconds(long secondsToSubtract) {
988 return (secondsToSubtract == Long.MIN_VALUE ? plusSeconds(Long.MAX_VALUE).plusSeconds(1) : plusSeconds(-secondsToSubtract));
989 }
990
991 /**
992 * Returns a copy of this duration with the specified duration in milliseconds subtracted.
993 * <p>
994 * This instance is immutable and unaffected by this method call.
995 *
996 * @param millisToSubtract the milliseconds to subtract, positive or negative
997 * @return a {@code Duration} based on this duration with the specified milliseconds subtracted, not null
998 * @throws ArithmeticException if numeric overflow occurs
999 */
1000 public Duration minusMillis(long millisToSubtract) {
1001 return (millisToSubtract == Long.MIN_VALUE ? plusMillis(Long.MAX_VALUE).plusMillis(1) : plusMillis(-millisToSubtract));
1002 }
1003
1004 /**
1005 * Returns a copy of this duration with the specified duration in nanoseconds subtracted.
1006 * <p>
1007 * This instance is immutable and unaffected by this method call.
1008 *
1009 * @param nanosToSubtract the nanoseconds to subtract, positive or negative
1010 * @return a {@code Duration} based on this duration with the specified nanoseconds subtracted, not null
1011 * @throws ArithmeticException if numeric overflow occurs
1012 */
1013 public Duration minusNanos(long nanosToSubtract) {
1014 return (nanosToSubtract == Long.MIN_VALUE ? plusNanos(Long.MAX_VALUE).plusNanos(1) : plusNanos(-nanosToSubtract));
1015 }
1016
1017 //-----------------------------------------------------------------------
1018 /**
1019 * Returns a copy of this duration multiplied by the scalar.
1020 * <p>
1021 * This instance is immutable and unaffected by this method call.
1022 *
1023 * @param multiplicand the value to multiply the duration by, positive or negative
1024 * @return a {@code Duration} based on this duration multiplied by the specified scalar, not null
1025 * @throws ArithmeticException if numeric overflow occurs
1026 */
1027 public Duration multipliedBy(long multiplicand) {
1028 if (multiplicand == 0) {
1029 return ZERO;
1030 }
1031 if (multiplicand == 1) {
1032 return this;
1033 }
1034 return create(toBigDecimalSeconds().multiply(BigDecimal.valueOf(multiplicand)));
1035 }
1036
1037 /**
1038 * Returns a copy of this duration divided by the specified value.
1039 * <p>
1040 * This instance is immutable and unaffected by this method call.
1041 *
1042 * @param divisor the value to divide the duration by, positive or negative, not zero
1043 * @return a {@code Duration} based on this duration divided by the specified divisor, not null
1044 * @throws ArithmeticException if the divisor is zero or if numeric overflow occurs
1045 */
1046 public Duration dividedBy(long divisor) {
1047 if (divisor == 0) {
1048 throw new ArithmeticException("Cannot divide by zero");
1049 }
1050 if (divisor == 1) {
1051 return this;
1052 }
1053 return create(toBigDecimalSeconds().divide(BigDecimal.valueOf(divisor), RoundingMode.DOWN));
1054 }
1055
1056 /**
1057 * Returns number of whole times a specified Duration occurs within this Duration.
1058 * <p>
1059 * This instance is immutable and unaffected by this method call.
1060 *
1061 * @param divisor the value to divide the duration by, positive or negative, not null
1062 * @return number of whole times, rounded toward zero, a specified
1063 * {@code Duration} occurs within this Duration, may be negative
1064 * @throws ArithmeticException if the divisor is zero, or if numeric overflow occurs
1065 * @since 9
1066 */
1067 public long dividedBy(Duration divisor) {
1068 Objects.requireNonNull(divisor, "divisor");
1069 BigDecimal dividendBigD = toBigDecimalSeconds();
1070 BigDecimal divisorBigD = divisor.toBigDecimalSeconds();
1071 return dividendBigD.divideToIntegralValue(divisorBigD).longValueExact();
1072 }
1073
1074 /**
1075 * Converts this duration to the total length in seconds and
1076 * fractional nanoseconds expressed as a {@code BigDecimal}.
1077 *
1078 * @return the total length of the duration in seconds, with a scale of 9, not null
1079 */
1080 private BigDecimal toBigDecimalSeconds() {
1081 return BigDecimal.valueOf(seconds).add(BigDecimal.valueOf(nanos, 9));
1082 }
1083
1084 /**
1085 * Creates an instance of {@code Duration} from a number of seconds.
1086 *
1087 * @param seconds the number of seconds, up to scale 9, positive or negative
1088 * @return a {@code Duration}, not null
1089 * @throws ArithmeticException if numeric overflow occurs
1090 */
1091 private static Duration create(BigDecimal seconds) {
1092 BigInteger nanos = seconds.movePointRight(9).toBigIntegerExact();
1093 BigInteger[] divRem = nanos.divideAndRemainder(BI_NANOS_PER_SECOND);
1094 if (divRem[0].bitLength() > 63) {
1095 throw new ArithmeticException("Exceeds capacity of Duration: " + nanos);
1096 }
1097 return ofSeconds(divRem[0].longValue(), divRem[1].intValue());
1098 }
1099
1100 //-----------------------------------------------------------------------
1101 /**
1102 * Returns a copy of this duration with the length negated.
1103 * <p>
1104 * This method swaps the sign of the total length of this duration.
1105 * For example, {@code PT1.3S} will be returned as {@code PT-1.3S}.
1106 * <p>
1107 * This instance is immutable and unaffected by this method call.
1108 *
1109 * @return a {@code Duration} based on this duration with the amount negated, not null
1110 * @throws ArithmeticException if numeric overflow occurs
1111 */
1112 public Duration negated() {
1113 return multipliedBy(-1);
1114 }
1115
1116 /**
1117 * Returns a copy of this duration with a positive length.
1118 * <p>
1119 * This method returns a positive duration by effectively removing the sign from any negative total length.
1120 * For example, {@code PT-1.3S} will be returned as {@code PT1.3S}.
1121 * <p>
1122 * This instance is immutable and unaffected by this method call.
1123 *
1124 * @return a {@code Duration} based on this duration with an absolute length, not null
1125 * @throws ArithmeticException if numeric overflow occurs
1126 */
1127 public Duration abs() {
1128 return isNegative() ? negated() : this;
1129 }
1130
1131 //-------------------------------------------------------------------------
1132 /**
1133 * Adds this duration to the specified temporal object.
1134 * <p>
1135 * This returns a temporal object of the same observable type as the input
1136 * with this duration added.
1137 * <p>
1138 * In most cases, it is clearer to reverse the calling pattern by using
1139 * {@link Temporal#plus(TemporalAmount)}.
1140 * <pre>
1141 * // these two lines are equivalent, but the second approach is recommended
1142 * dateTime = thisDuration.addTo(dateTime);
1143 * dateTime = dateTime.plus(thisDuration);
1144 * </pre>
1145 * <p>
1146 * The calculation will add the seconds, then nanos.
1147 * Only non-zero amounts will be added.
1148 * <p>
1149 * This instance is immutable and unaffected by this method call.
1150 *
1151 * @param temporal the temporal object to adjust, not null
1152 * @return an object of the same type with the adjustment made, not null
1153 * @throws DateTimeException if unable to add
1154 * @throws ArithmeticException if numeric overflow occurs
1155 */
1156 @Override
1157 public Temporal addTo(Temporal temporal) {
1158 if (seconds != 0) {
1159 temporal = temporal.plus(seconds, SECONDS);
1160 }
1161 if (nanos != 0) {
1162 temporal = temporal.plus(nanos, NANOS);
1163 }
1164 return temporal;
1165 }
1166
1167 /**
1168 * Subtracts this duration from the specified temporal object.
1169 * <p>
1170 * This returns a temporal object of the same observable type as the input
1171 * with this duration subtracted.
1172 * <p>
1173 * In most cases, it is clearer to reverse the calling pattern by using
1174 * {@link Temporal#minus(TemporalAmount)}.
1175 * <pre>
1176 * // these two lines are equivalent, but the second approach is recommended
1177 * dateTime = thisDuration.subtractFrom(dateTime);
1178 * dateTime = dateTime.minus(thisDuration);
1179 * </pre>
1180 * <p>
1181 * The calculation will subtract the seconds, then nanos.
1182 * Only non-zero amounts will be added.
1183 * <p>
1184 * This instance is immutable and unaffected by this method call.
1185 *
1186 * @param temporal the temporal object to adjust, not null
1187 * @return an object of the same type with the adjustment made, not null
1188 * @throws DateTimeException if unable to subtract
1189 * @throws ArithmeticException if numeric overflow occurs
1190 */
1191 @Override
1192 public Temporal subtractFrom(Temporal temporal) {
1193 if (seconds != 0) {
1194 temporal = temporal.minus(seconds, SECONDS);
1195 }
1196 if (nanos != 0) {
1197 temporal = temporal.minus(nanos, NANOS);
1198 }
1199 return temporal;
1200 }
1201
1202 //-----------------------------------------------------------------------
1203 /**
1204 * Gets the number of days in this duration.
1205 * <p>
1206 * This returns the total number of days in the duration by dividing the
1207 * number of seconds by 86,400.
1208 * This is based on the standard definition of a day as 24 hours.
1209 * <p>
1210 * This instance is immutable and unaffected by this method call.
1211 *
1212 * @return the number of days in the duration, may be negative
1213 */
1214 public long toDays() {
1215 return seconds / SECONDS_PER_DAY;
1216 }
1217
1218 /**
1219 * Gets the number of hours in this duration.
1220 * <p>
1221 * This returns the total number of hours in the duration by dividing the
1222 * number of seconds by 3,600.
1223 * <p>
1224 * This instance is immutable and unaffected by this method call.
1225 *
1226 * @return the number of hours in the duration, may be negative
1227 */
1228 public long toHours() {
1229 return seconds / SECONDS_PER_HOUR;
1230 }
1231
1232 /**
1233 * Gets the number of minutes in this duration.
1234 * <p>
1235 * This returns the total number of minutes in the duration by dividing the
1236 * number of seconds by 60.
1237 * <p>
1238 * This instance is immutable and unaffected by this method call.
1239 *
1240 * @return the number of minutes in the duration, may be negative
1241 */
1242 public long toMinutes() {
1243 return seconds / SECONDS_PER_MINUTE;
1244 }
1245
1246 /**
1247 * Gets the number of seconds in this duration.
1248 * <p>
1249 * This returns the total number of whole seconds in the duration.
1250 * <p>
1251 * This instance is immutable and unaffected by this method call.
1252 *
1253 * @return the whole seconds part of the length of the duration, positive or negative
1254 * @since 9
1255 */
1256 public long toSeconds() {
1257 return seconds;
1258 }
1259
1260 /**
1261 * Converts this duration to the total length in milliseconds.
1262 * <p>
1263 * If this duration is too large to fit in a {@code long} milliseconds, then an
1264 * exception is thrown.
1265 * <p>
1266 * If this duration has greater than millisecond precision, then the conversion
1267 * will drop any excess precision information as though the amount in nanoseconds
1268 * was subject to integer division by one million.
1269 *
1270 * @return the total length of the duration in milliseconds
1271 * @throws ArithmeticException if numeric overflow occurs
1272 */
1273 public long toMillis() {
1274 long tempSeconds = seconds;
1275 long tempNanos = nanos;
1276 if (tempSeconds < 0) {
1277 // change the seconds and nano value to
1278 // handle Long.MIN_VALUE case
1279 tempSeconds = tempSeconds + 1;
1280 tempNanos = tempNanos - NANOS_PER_SECOND;
1281 }
1282 long millis = Math.multiplyExact(tempSeconds, 1000);
1283 millis = Math.addExact(millis, tempNanos / NANOS_PER_MILLI);
1284 return millis;
1285 }
1286
1287 /**
1288 * Converts this duration to the total length in nanoseconds expressed as a {@code long}.
1289 * <p>
1290 * If this duration is too large to fit in a {@code long} nanoseconds, then an
1291 * exception is thrown.
1292 *
1293 * @return the total length of the duration in nanoseconds
1294 * @throws ArithmeticException if numeric overflow occurs
1295 */
1296 public long toNanos() {
1297 long tempSeconds = seconds;
1298 long tempNanos = nanos;
1299 if (tempSeconds < 0) {
1300 // change the seconds and nano value to
1301 // handle Long.MIN_VALUE case
1302 tempSeconds = tempSeconds + 1;
1303 tempNanos = tempNanos - NANOS_PER_SECOND;
1304 }
1305 long totalNanos = Math.multiplyExact(tempSeconds, NANOS_PER_SECOND);
1306 totalNanos = Math.addExact(totalNanos, tempNanos);
1307 return totalNanos;
1308 }
1309
1310 /**
1311 * Extracts the number of days in the duration.
1312 * <p>
1313 * This returns the total number of days in the duration by dividing the
1314 * number of seconds by 86,400.
1315 * This is based on the standard definition of a day as 24 hours.
1316 * <p>
1317 * This instance is immutable and unaffected by this method call.
1318 * @apiNote
1319 * This method behaves exactly the same way as {@link #toDays()}.
1320 *
1321 * @return the number of days in the duration, may be negative
1322 * @since 9
1323 */
1324 public long toDaysPart(){
1325 return seconds / SECONDS_PER_DAY;
1326 }
1327
1328 /**
1329 * Extracts the number of hours part in the duration.
1330 * <p>
1331 * This returns the number of remaining hours when dividing {@link #toHours}
1332 * by hours in a day.
1333 * This is based on the standard definition of a day as 24 hours.
1334 * <p>
1335 * This instance is immutable and unaffected by this method call.
1336 *
1337 * @return the number of hours part in the duration, may be negative
1338 * @since 9
1339 */
1340 public int toHoursPart(){
1341 return (int) (toHours() % 24);
1342 }
1343
1344 /**
1345 * Extracts the number of minutes part in the duration.
1346 * <p>
1347 * This returns the number of remaining minutes when dividing {@link #toMinutes}
1348 * by minutes in an hour.
1349 * This is based on the standard definition of an hour as 60 minutes.
1350 * <p>
1351 * This instance is immutable and unaffected by this method call.
1352 *
1353 * @return the number of minutes parts in the duration, may be negative
1354 * @since 9
1355 */
1356 public int toMinutesPart(){
1357 return (int) (toMinutes() % MINUTES_PER_HOUR);
1358 }
1359
1360 /**
1361 * Extracts the number of seconds part in the duration.
1362 * <p>
1363 * This returns the remaining seconds when dividing {@link #toSeconds}
1364 * by seconds in a minute.
1365 * This is based on the standard definition of a minute as 60 seconds.
1366 * <p>
1367 * This instance is immutable and unaffected by this method call.
1368 *
1369 * @return the number of seconds parts in the duration, may be negative
1370 * @since 9
1371 */
1372 public int toSecondsPart(){
1373 return (int) (seconds % SECONDS_PER_MINUTE);
1374 }
1375
1376 /**
1377 * Extracts the number of milliseconds part of the duration.
1378 * <p>
1379 * This returns the milliseconds part by dividing the number of nanoseconds by 1,000,000.
1380 * The length of the duration is stored using two fields - seconds and nanoseconds.
1381 * The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to
1382 * the length in seconds.
1383 * The total duration is defined by calling {@link #getNano()} and {@link #getSeconds()}.
1384 * <p>
1385 * This instance is immutable and unaffected by this method call.
1386 *
1387 * @return the number of milliseconds part of the duration.
1388 * @since 9
1389 */
1390 public int toMillisPart(){
1391 return nanos / 1000_000;
1392 }
1393
1394 /**
1395 * Get the nanoseconds part within seconds of the duration.
1396 * <p>
1397 * The length of the duration is stored using two fields - seconds and nanoseconds.
1398 * The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to
1399 * the length in seconds.
1400 * The total duration is defined by calling {@link #getNano()} and {@link #getSeconds()}.
1401 * <p>
1402 * This instance is immutable and unaffected by this method call.
1403 *
1404 * @return the nanoseconds within the second part of the length of the duration, from 0 to 999,999,999
1405 * @since 9
1406 */
1407 public int toNanosPart(){
1408 return nanos;
1409 }
1410
1411
1412 //-----------------------------------------------------------------------
1413 /**
1414 * Returns a copy of this {@code Duration} truncated to the specified unit.
1415 * <p>
1416 * Truncating the duration returns a copy of the original with conceptual fields
1417 * smaller than the specified unit set to zero.
1418 * For example, truncating with the {@link ChronoUnit#MINUTES MINUTES} unit will
1419 * round down towards zero to the nearest minute, setting the seconds and
1420 * nanoseconds to zero.
1421 * <p>
1422 * The unit must have a {@linkplain TemporalUnit#getDuration() duration}
1423 * that divides into the length of a standard day without remainder.
1424 * This includes all
1425 * {@linkplain ChronoUnit#isTimeBased() time-based units on {@code ChronoUnit}}
1426 * and {@link ChronoUnit#DAYS DAYS}. Other ChronoUnits throw an exception.
1427 * <p>
1428 * This instance is immutable and unaffected by this method call.
1429 *
1430 * @param unit the unit to truncate to, not null
1431 * @return a {@code Duration} based on this duration with the time truncated, not null
1432 * @throws DateTimeException if the unit is invalid for truncation
1433 * @throws UnsupportedTemporalTypeException if the unit is not supported
1434 * @since 9
1435 */
1436 public Duration truncatedTo(TemporalUnit unit) {
1437 Objects.requireNonNull(unit, "unit");
1438 if (unit == ChronoUnit.SECONDS && (seconds >= 0 || nanos == 0)) {
1439 return new Duration(seconds, 0);
1440 } else if (unit == ChronoUnit.NANOS) {
1441 return this;
1442 }
1443 Duration unitDur = unit.getDuration();
1444 if (unitDur.getSeconds() > LocalTime.SECONDS_PER_DAY) {
1445 throw new UnsupportedTemporalTypeException("Unit is too large to be used for truncation");
1446 }
1447 long dur = unitDur.toNanos();
1448 if ((LocalTime.NANOS_PER_DAY % dur) != 0) {
1449 throw new UnsupportedTemporalTypeException("Unit must divide into a standard day without remainder");
1450 }
1451 long nod = (seconds % LocalTime.SECONDS_PER_DAY) * LocalTime.NANOS_PER_SECOND + nanos;
1452 long result = (nod / dur) * dur;
1453 return plusNanos(result - nod);
1454 }
1455
1456 //-----------------------------------------------------------------------
1457 /**
1458 * Compares this duration to the specified {@code Duration}.
1459 * <p>
1460 * The comparison is based on the total length of the durations.
1461 * It is "consistent with equals", as defined by {@link Comparable}.
1462 *
1463 * @param otherDuration the other duration to compare to, not null
1464 * @return the comparator value, that is less than zero if this duration is less than {@code otherDuration},
1465 * zero if they are equal, greater than zero if this duration is greater than {@code otherDuration}
1466 */
1467 @Override
1468 public int compareTo(Duration otherDuration) {
1469 int cmp = Long.compare(seconds, otherDuration.seconds);
1470 if (cmp != 0) {
1471 return cmp;
1472 }
1473 return nanos - otherDuration.nanos;
1474 }
1475
1476 //-----------------------------------------------------------------------
1477 /**
1478 * Checks if this duration is equal to the specified {@code Duration}.
1479 * <p>
1480 * The comparison is based on the total length of the durations.
1481 *
1482 * @param other the other duration, null returns false
1483 * @return true if the other duration is equal to this one
1484 */
1485 @Override
1486 public boolean equals(Object other) {
1487 if (this == other) {
1488 return true;
1489 }
1490 return (other instanceof Duration otherDuration)
1491 && this.seconds == otherDuration.seconds
1492 && this.nanos == otherDuration.nanos;
1493 }
1494
1495 /**
1496 * A hash code for this duration.
1497 *
1498 * @return a suitable hash code
1499 */
1500 @Override
1501 public int hashCode() {
1502 return Long.hashCode(seconds) + (51 * nanos);
1503 }
1504
1505 //-----------------------------------------------------------------------
1506 /**
1507 * A string representation of this duration using ISO-8601 seconds
1508 * based representation, such as {@code PT8H6M12.345S}.
1509 * <p>
1510 * The format of the returned string will be {@code PTnHnMnS}, where n is
1511 * the relevant hours, minutes or seconds part of the duration.
1512 * Any fractional seconds are placed after a decimal point in the seconds section.
1513 * If a section has a zero value, it is omitted.
1514 * The hours, minutes and seconds will all have the same sign.
1515 * <p>
1516 * Examples:
1517 * <pre>
1518 * "20.345 seconds" -- "PT20.345S"
1519 * "15 minutes" (15 * 60 seconds) -- "PT15M"
1520 * "10 hours" (10 * 3,600 seconds) -- "PT10H"
1521 * "2 days" (2 * 86,400 seconds) -- "PT48H"
1522 * </pre>
1523 * Note that multiples of 24 hours are not output as days to avoid confusion
1524 * with {@code Period}.
1525 *
1526 * @return an ISO-8601 representation of this duration, not null
1527 */
1528 @Override
1529 public String toString() {
1530 if (this == ZERO) {
1531 return "PT0S";
1532 }
1533 long effectiveTotalSecs = seconds;
1534 if (seconds < 0 && nanos > 0) {
1535 effectiveTotalSecs++;
1536 }
1537 long hours = effectiveTotalSecs / SECONDS_PER_HOUR;
1538 int minutes = (int) ((effectiveTotalSecs % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE);
1539 int secs = (int) (effectiveTotalSecs % SECONDS_PER_MINUTE);
1540 StringBuilder buf = new StringBuilder(24);
1541 buf.append("PT");
1542 if (hours != 0) {
1543 buf.append(hours).append('H');
1544 }
1545 if (minutes != 0) {
1546 buf.append(minutes).append('M');
1547 }
1548 if (secs == 0 && nanos == 0 && buf.length() > 2) {
1549 return buf.toString();
1550 }
1551 if (seconds < 0 && nanos > 0) {
1552 if (secs == 0) {
1553 buf.append("-0");
1554 } else {
1555 buf.append(secs);
1556 }
1557 } else {
1558 buf.append(secs);
1559 }
1560 if (nanos > 0) {
1561 int pos = buf.length();
1562 if (seconds < 0) {
1563 buf.append(2 * NANOS_PER_SECOND - nanos);
1564 } else {
1565 buf.append(nanos + NANOS_PER_SECOND);
1566 }
1567 while (buf.charAt(buf.length() - 1) == '0') {
1568 buf.setLength(buf.length() - 1);
1569 }
1570 buf.setCharAt(pos, '.');
1571 }
1572 buf.append('S');
1573 return buf.toString();
1574 }
1575
1576 //-----------------------------------------------------------------------
1577 /**
1578 * Writes the object using a
1579 * <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>.
1580 * @serialData
1581 * <pre>
1582 * out.writeByte(1); // identifies a Duration
1583 * out.writeLong(seconds);
1584 * out.writeInt(nanos);
1585 * </pre>
1586 *
1587 * @return the instance of {@code Ser}, not null
1588 */
1589 @java.io.Serial
1590 private Object writeReplace() {
1591 return new Ser(Ser.DURATION_TYPE, this);
1592 }
1593
1594 /**
1595 * Defend against malicious streams.
1596 *
1597 * @param s the stream to read
1598 * @throws InvalidObjectException always
1599 */
1600 @java.io.Serial
1601 private void readObject(ObjectInputStream s) throws InvalidObjectException {
1602 throw new InvalidObjectException("Deserialization via serialization delegate");
1603 }
1604
1605 void writeExternal(DataOutput out) throws IOException {
1606 out.writeLong(seconds);
1607 out.writeInt(nanos);
1608 }
1609
1610 static Duration readExternal(DataInput in) throws IOException {
1611 long seconds = in.readLong();
1612 int nanos = in.readInt();
1613 return Duration.ofSeconds(seconds, nanos);
1614 }
1615
1616 }