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