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