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