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