Path: blob/master/src/java.base/share/classes/java/time/Duration.java
41152 views
/*1* Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file:30*31* Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos32*33* All rights reserved.34*35* Redistribution and use in source and binary forms, with or without36* modification, are permitted provided that the following conditions are met:37*38* * Redistributions of source code must retain the above copyright notice,39* this list of conditions and the following disclaimer.40*41* * Redistributions in binary form must reproduce the above copyright notice,42* this list of conditions and the following disclaimer in the documentation43* and/or other materials provided with the distribution.44*45* * Neither the name of JSR-310 nor the names of its contributors46* may be used to endorse or promote products derived from this software47* without specific prior written permission.48*49* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS50* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT51* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR52* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR53* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,54* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,55* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR56* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF57* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING58* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS59* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.60*/61package java.time;6263import static java.time.LocalTime.MINUTES_PER_HOUR;64import static java.time.LocalTime.NANOS_PER_MILLI;65import static java.time.LocalTime.NANOS_PER_SECOND;66import static java.time.LocalTime.SECONDS_PER_DAY;67import static java.time.LocalTime.SECONDS_PER_HOUR;68import static java.time.LocalTime.SECONDS_PER_MINUTE;69import static java.time.temporal.ChronoField.NANO_OF_SECOND;70import static java.time.temporal.ChronoUnit.DAYS;71import static java.time.temporal.ChronoUnit.NANOS;72import static java.time.temporal.ChronoUnit.SECONDS;7374import java.io.DataInput;75import java.io.DataOutput;76import java.io.IOException;77import java.io.InvalidObjectException;78import java.io.ObjectInputStream;79import java.io.Serializable;80import java.math.BigDecimal;81import java.math.BigInteger;82import java.math.RoundingMode;83import java.time.format.DateTimeParseException;84import java.time.temporal.ChronoField;85import java.time.temporal.ChronoUnit;86import java.time.temporal.Temporal;87import java.time.temporal.TemporalAmount;88import java.time.temporal.TemporalUnit;89import java.time.temporal.UnsupportedTemporalTypeException;90import java.util.List;91import java.util.Objects;92import java.util.regex.Matcher;93import java.util.regex.Pattern;9495/**96* A time-based amount of time, such as '34.5 seconds'.97* <p>98* This class models a quantity or amount of time in terms of seconds and nanoseconds.99* It can be accessed using other duration-based units, such as minutes and hours.100* In addition, the {@link ChronoUnit#DAYS DAYS} unit can be used and is treated as101* exactly equal to 24 hours, thus ignoring daylight savings effects.102* See {@link Period} for the date-based equivalent to this class.103* <p>104* A physical duration could be of infinite length.105* For practicality, the duration is stored with constraints similar to {@link Instant}.106* The duration uses nanosecond resolution with a maximum value of the seconds that can107* be held in a {@code long}. This is greater than the current estimated age of the universe.108* <p>109* The range of a duration requires the storage of a number larger than a {@code long}.110* To achieve this, the class stores a {@code long} representing seconds and an {@code int}111* representing nanosecond-of-second, which will always be between 0 and 999,999,999.112* The model is of a directed duration, meaning that the duration may be negative.113* <p>114* The duration is measured in "seconds", but these are not necessarily identical to115* the scientific "SI second" definition based on atomic clocks.116* This difference only impacts durations measured near a leap-second and should not affect117* most applications.118* See {@link Instant} for a discussion as to the meaning of the second and time-scales.119* <p>120* This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>121* class; programmers should treat instances that are122* {@linkplain #equals(Object) equal} as interchangeable and should not123* use instances for synchronization, or unpredictable behavior may124* occur. For example, in a future release, synchronization may fail.125* The {@code equals} method should be used for comparisons.126*127* @implSpec128* This class is immutable and thread-safe.129*130* @since 1.8131*/132@jdk.internal.ValueBased133public final class Duration134implements TemporalAmount, Comparable<Duration>, Serializable {135136/**137* Constant for a duration of zero.138*/139public static final Duration ZERO = new Duration(0, 0);140/**141* Serialization version.142*/143@java.io.Serial144private static final long serialVersionUID = 3078945930695997490L;145/**146* Constant for nanos per second.147*/148private static final BigInteger BI_NANOS_PER_SECOND = BigInteger.valueOf(NANOS_PER_SECOND);149/**150* The pattern for parsing.151*/152private static class Lazy {153static final Pattern PATTERN =154Pattern.compile("([-+]?)P(?:([-+]?[0-9]+)D)?" +155"(T(?:([-+]?[0-9]+)H)?(?:([-+]?[0-9]+)M)?(?:([-+]?[0-9]+)(?:[.,]([0-9]{0,9}))?S)?)?",156Pattern.CASE_INSENSITIVE);157}158159/**160* The number of seconds in the duration.161*/162private final long seconds;163/**164* The number of nanoseconds in the duration, expressed as a fraction of the165* number of seconds. This is always positive, and never exceeds 999,999,999.166*/167private final int nanos;168169//-----------------------------------------------------------------------170/**171* Obtains a {@code Duration} representing a number of standard 24 hour days.172* <p>173* The seconds are calculated based on the standard definition of a day,174* where each day is 86400 seconds which implies a 24 hour day.175* The nanosecond in second field is set to zero.176*177* @param days the number of days, positive or negative178* @return a {@code Duration}, not null179* @throws ArithmeticException if the input days exceeds the capacity of {@code Duration}180*/181public static Duration ofDays(long days) {182return create(Math.multiplyExact(days, SECONDS_PER_DAY), 0);183}184185/**186* Obtains a {@code Duration} representing a number of standard hours.187* <p>188* The seconds are calculated based on the standard definition of an hour,189* where each hour is 3600 seconds.190* The nanosecond in second field is set to zero.191*192* @param hours the number of hours, positive or negative193* @return a {@code Duration}, not null194* @throws ArithmeticException if the input hours exceeds the capacity of {@code Duration}195*/196public static Duration ofHours(long hours) {197return create(Math.multiplyExact(hours, SECONDS_PER_HOUR), 0);198}199200/**201* Obtains a {@code Duration} representing a number of standard minutes.202* <p>203* The seconds are calculated based on the standard definition of a minute,204* where each minute is 60 seconds.205* The nanosecond in second field is set to zero.206*207* @param minutes the number of minutes, positive or negative208* @return a {@code Duration}, not null209* @throws ArithmeticException if the input minutes exceeds the capacity of {@code Duration}210*/211public static Duration ofMinutes(long minutes) {212return create(Math.multiplyExact(minutes, SECONDS_PER_MINUTE), 0);213}214215//-----------------------------------------------------------------------216/**217* Obtains a {@code Duration} representing a number of seconds.218* <p>219* The nanosecond in second field is set to zero.220*221* @param seconds the number of seconds, positive or negative222* @return a {@code Duration}, not null223*/224public static Duration ofSeconds(long seconds) {225return create(seconds, 0);226}227228/**229* Obtains a {@code Duration} representing a number of seconds and an230* adjustment in nanoseconds.231* <p>232* This method allows an arbitrary number of nanoseconds to be passed in.233* The factory will alter the values of the second and nanosecond in order234* to ensure that the stored nanosecond is in the range 0 to 999,999,999.235* For example, the following will result in exactly the same duration:236* <pre>237* Duration.ofSeconds(3, 1);238* Duration.ofSeconds(4, -999_999_999);239* Duration.ofSeconds(2, 1000_000_001);240* </pre>241*242* @param seconds the number of seconds, positive or negative243* @param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative244* @return a {@code Duration}, not null245* @throws ArithmeticException if the adjustment causes the seconds to exceed the capacity of {@code Duration}246*/247public static Duration ofSeconds(long seconds, long nanoAdjustment) {248long secs = Math.addExact(seconds, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND));249int nos = (int) Math.floorMod(nanoAdjustment, NANOS_PER_SECOND);250return create(secs, nos);251}252253//-----------------------------------------------------------------------254/**255* Obtains a {@code Duration} representing a number of milliseconds.256* <p>257* The seconds and nanoseconds are extracted from the specified milliseconds.258*259* @param millis the number of milliseconds, positive or negative260* @return a {@code Duration}, not null261*/262public static Duration ofMillis(long millis) {263long secs = millis / 1000;264int mos = (int) (millis % 1000);265if (mos < 0) {266mos += 1000;267secs--;268}269return create(secs, mos * 1000_000);270}271272//-----------------------------------------------------------------------273/**274* Obtains a {@code Duration} representing a number of nanoseconds.275* <p>276* The seconds and nanoseconds are extracted from the specified nanoseconds.277*278* @param nanos the number of nanoseconds, positive or negative279* @return a {@code Duration}, not null280*/281public static Duration ofNanos(long nanos) {282long secs = nanos / NANOS_PER_SECOND;283int nos = (int) (nanos % NANOS_PER_SECOND);284if (nos < 0) {285nos += NANOS_PER_SECOND;286secs--;287}288return create(secs, nos);289}290291//-----------------------------------------------------------------------292/**293* Obtains a {@code Duration} representing an amount in the specified unit.294* <p>295* The parameters represent the two parts of a phrase like '6 Hours'. For example:296* <pre>297* Duration.of(3, SECONDS);298* Duration.of(465, HOURS);299* </pre>300* Only a subset of units are accepted by this method.301* The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or302* be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception.303*304* @param amount the amount of the duration, measured in terms of the unit, positive or negative305* @param unit the unit that the duration is measured in, must have an exact duration, not null306* @return a {@code Duration}, not null307* @throws DateTimeException if the period unit has an estimated duration308* @throws ArithmeticException if a numeric overflow occurs309*/310public static Duration of(long amount, TemporalUnit unit) {311return ZERO.plus(amount, unit);312}313314//-----------------------------------------------------------------------315/**316* Obtains an instance of {@code Duration} from a temporal amount.317* <p>318* This obtains a duration based on the specified amount.319* A {@code TemporalAmount} represents an amount of time, which may be320* date-based or time-based, which this factory extracts to a duration.321* <p>322* The conversion loops around the set of units from the amount and uses323* the {@linkplain TemporalUnit#getDuration() duration} of the unit to324* calculate the total {@code Duration}.325* Only a subset of units are accepted by this method. The unit must either326* have an {@linkplain TemporalUnit#isDurationEstimated() exact duration}327* or be {@link ChronoUnit#DAYS} which is treated as 24 hours.328* If any other units are found then an exception is thrown.329*330* @param amount the temporal amount to convert, not null331* @return the equivalent duration, not null332* @throws DateTimeException if unable to convert to a {@code Duration}333* @throws ArithmeticException if numeric overflow occurs334*/335public static Duration from(TemporalAmount amount) {336Objects.requireNonNull(amount, "amount");337Duration duration = ZERO;338for (TemporalUnit unit : amount.getUnits()) {339duration = duration.plus(amount.get(unit), unit);340}341return duration;342}343344//-----------------------------------------------------------------------345/**346* Obtains a {@code Duration} from a text string such as {@code PnDTnHnMn.nS}.347* <p>348* This will parse a textual representation of a duration, including the349* string produced by {@code toString()}. The formats accepted are based350* on the ISO-8601 duration format {@code PnDTnHnMn.nS} with days351* considered to be exactly 24 hours.352* <p>353* The string starts with an optional sign, denoted by the ASCII negative354* or positive symbol. If negative, the whole period is negated.355* The ASCII letter "P" is next in upper or lower case.356* There are then four sections, each consisting of a number and a suffix.357* The sections have suffixes in ASCII of "D", "H", "M" and "S" for358* days, hours, minutes and seconds, accepted in upper or lower case.359* The suffixes must occur in order. The ASCII letter "T" must occur before360* the first occurrence, if any, of an hour, minute or second section.361* At least one of the four sections must be present, and if "T" is present362* there must be at least one section after the "T".363* The number part of each section must consist of one or more ASCII digits.364* The number may be prefixed by the ASCII negative or positive symbol.365* The number of days, hours and minutes must parse to a {@code long}.366* The number of seconds must parse to a {@code long} with optional fraction.367* The decimal point may be either a dot or a comma.368* The fractional part may have from zero to 9 digits.369* <p>370* The leading plus/minus sign, and negative values for other units are371* not part of the ISO-8601 standard.372* <p>373* Examples:374* <pre>375* "PT20.345S" -- parses as "20.345 seconds"376* "PT15M" -- parses as "15 minutes" (where a minute is 60 seconds)377* "PT10H" -- parses as "10 hours" (where an hour is 3600 seconds)378* "P2D" -- parses as "2 days" (where a day is 24 hours or 86400 seconds)379* "P2DT3H4M" -- parses as "2 days, 3 hours and 4 minutes"380* "PT-6H3M" -- parses as "-6 hours and +3 minutes"381* "-PT6H3M" -- parses as "-6 hours and -3 minutes"382* "-PT-6H+3M" -- parses as "+6 hours and -3 minutes"383* </pre>384*385* @param text the text to parse, not null386* @return the parsed duration, not null387* @throws DateTimeParseException if the text cannot be parsed to a duration388*/389public static Duration parse(CharSequence text) {390Objects.requireNonNull(text, "text");391Matcher matcher = Lazy.PATTERN.matcher(text);392if (matcher.matches()) {393// check for letter T but no time sections394if (!charMatch(text, matcher.start(3), matcher.end(3), 'T')) {395boolean negate = charMatch(text, matcher.start(1), matcher.end(1), '-');396397int dayStart = matcher.start(2), dayEnd = matcher.end(2);398int hourStart = matcher.start(4), hourEnd = matcher.end(4);399int minuteStart = matcher.start(5), minuteEnd = matcher.end(5);400int secondStart = matcher.start(6), secondEnd = matcher.end(6);401int fractionStart = matcher.start(7), fractionEnd = matcher.end(7);402403if (dayStart >= 0 || hourStart >= 0 || minuteStart >= 0 || secondStart >= 0) {404long daysAsSecs = parseNumber(text, dayStart, dayEnd, SECONDS_PER_DAY, "days");405long hoursAsSecs = parseNumber(text, hourStart, hourEnd, SECONDS_PER_HOUR, "hours");406long minsAsSecs = parseNumber(text, minuteStart, minuteEnd, SECONDS_PER_MINUTE, "minutes");407long seconds = parseNumber(text, secondStart, secondEnd, 1, "seconds");408boolean negativeSecs = secondStart >= 0 && text.charAt(secondStart) == '-';409int nanos = parseFraction(text, fractionStart, fractionEnd, negativeSecs ? -1 : 1);410try {411return create(negate, daysAsSecs, hoursAsSecs, minsAsSecs, seconds, nanos);412} catch (ArithmeticException ex) {413throw (DateTimeParseException) new DateTimeParseException("Text cannot be parsed to a Duration: overflow", text, 0).initCause(ex);414}415}416}417}418throw new DateTimeParseException("Text cannot be parsed to a Duration", text, 0);419}420421private static boolean charMatch(CharSequence text, int start, int end, char c) {422return (start >= 0 && end == start + 1 && text.charAt(start) == c);423}424425private static long parseNumber(CharSequence text, int start, int end, int multiplier, String errorText) {426// regex limits to [-+]?[0-9]+427if (start < 0 || end < 0) {428return 0;429}430try {431long val = Long.parseLong(text, start, end, 10);432return Math.multiplyExact(val, multiplier);433} catch (NumberFormatException | ArithmeticException ex) {434throw (DateTimeParseException) new DateTimeParseException("Text cannot be parsed to a Duration: " + errorText, text, 0).initCause(ex);435}436}437438private static int parseFraction(CharSequence text, int start, int end, int negate) {439// regex limits to [0-9]{0,9}440if (start < 0 || end < 0 || end - start == 0) {441return 0;442}443try {444int fraction = Integer.parseInt(text, start, end, 10);445446// for number strings smaller than 9 digits, interpret as if there447// were trailing zeros448for (int i = end - start; i < 9; i++) {449fraction *= 10;450}451return fraction * negate;452} catch (NumberFormatException | ArithmeticException ex) {453throw (DateTimeParseException) new DateTimeParseException("Text cannot be parsed to a Duration: fraction", text, 0).initCause(ex);454}455}456457private static Duration create(boolean negate, long daysAsSecs, long hoursAsSecs, long minsAsSecs, long secs, int nanos) {458long seconds = Math.addExact(daysAsSecs, Math.addExact(hoursAsSecs, Math.addExact(minsAsSecs, secs)));459if (negate) {460return ofSeconds(seconds, nanos).negated();461}462return ofSeconds(seconds, nanos);463}464465//-----------------------------------------------------------------------466/**467* Obtains a {@code Duration} representing the duration between two temporal objects.468* <p>469* This calculates the duration between two temporal objects. If the objects470* are of different types, then the duration is calculated based on the type471* of the first object. For example, if the first argument is a {@code LocalTime}472* then the second argument is converted to a {@code LocalTime}.473* <p>474* The specified temporal objects must support the {@link ChronoUnit#SECONDS SECONDS} unit.475* For full accuracy, either the {@link ChronoUnit#NANOS NANOS} unit or the476* {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} field should be supported.477* <p>478* The result of this method can be a negative period if the end is before the start.479* To guarantee to obtain a positive duration call {@link #abs()} on the result.480*481* @param startInclusive the start instant, inclusive, not null482* @param endExclusive the end instant, exclusive, not null483* @return a {@code Duration}, not null484* @throws DateTimeException if the seconds between the temporals cannot be obtained485* @throws ArithmeticException if the calculation exceeds the capacity of {@code Duration}486*/487public static Duration between(Temporal startInclusive, Temporal endExclusive) {488try {489return ofNanos(startInclusive.until(endExclusive, NANOS));490} catch (DateTimeException | ArithmeticException ex) {491long secs = startInclusive.until(endExclusive, SECONDS);492long nanos;493try {494nanos = endExclusive.getLong(NANO_OF_SECOND) - startInclusive.getLong(NANO_OF_SECOND);495if (secs > 0 && nanos < 0) {496secs++;497} else if (secs < 0 && nanos > 0) {498secs--;499}500} catch (DateTimeException ex2) {501nanos = 0;502}503return ofSeconds(secs, nanos);504}505}506507//-----------------------------------------------------------------------508/**509* Obtains an instance of {@code Duration} using seconds and nanoseconds.510*511* @param seconds the length of the duration in seconds, positive or negative512* @param nanoAdjustment the nanosecond adjustment within the second, from 0 to 999,999,999513*/514private static Duration create(long seconds, int nanoAdjustment) {515if ((seconds | nanoAdjustment) == 0) {516return ZERO;517}518return new Duration(seconds, nanoAdjustment);519}520521/**522* Constructs an instance of {@code Duration} using seconds and nanoseconds.523*524* @param seconds the length of the duration in seconds, positive or negative525* @param nanos the nanoseconds within the second, from 0 to 999,999,999526*/527private Duration(long seconds, int nanos) {528super();529this.seconds = seconds;530this.nanos = nanos;531}532533//-----------------------------------------------------------------------534/**535* Gets the value of the requested unit.536* <p>537* This returns a value for each of the two supported units,538* {@link ChronoUnit#SECONDS SECONDS} and {@link ChronoUnit#NANOS NANOS}.539* All other units throw an exception.540*541* @param unit the {@code TemporalUnit} for which to return the value542* @return the long value of the unit543* @throws DateTimeException if the unit is not supported544* @throws UnsupportedTemporalTypeException if the unit is not supported545*/546@Override547public long get(TemporalUnit unit) {548if (unit == SECONDS) {549return seconds;550} else if (unit == NANOS) {551return nanos;552} else {553throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);554}555}556557/**558* Gets the set of units supported by this duration.559* <p>560* The supported units are {@link ChronoUnit#SECONDS SECONDS},561* and {@link ChronoUnit#NANOS NANOS}.562* They are returned in the order seconds, nanos.563* <p>564* This set can be used in conjunction with {@link #get(TemporalUnit)}565* to access the entire state of the duration.566*567* @return a list containing the seconds and nanos units, not null568*/569@Override570public List<TemporalUnit> getUnits() {571return DurationUnits.UNITS;572}573574/**575* Private class to delay initialization of this list until needed.576* The circular dependency between Duration and ChronoUnit prevents577* the simple initialization in Duration.578*/579private static class DurationUnits {580static final List<TemporalUnit> UNITS = List.of(SECONDS, NANOS);581}582583//-----------------------------------------------------------------------584/**585* Checks if this duration is zero length.586* <p>587* A {@code Duration} represents a directed distance between two points on588* the time-line and can therefore be positive, zero or negative.589* This method checks whether the length is zero.590*591* @return true if this duration has a total length equal to zero592*/593public boolean isZero() {594return (seconds | nanos) == 0;595}596597/**598* Checks if this duration is negative, excluding zero.599* <p>600* A {@code Duration} represents a directed distance between two points on601* the time-line and can therefore be positive, zero or negative.602* This method checks whether the length is less than zero.603*604* @return true if this duration has a total length less than zero605*/606public boolean isNegative() {607return seconds < 0;608}609610//-----------------------------------------------------------------------611/**612* Gets the number of seconds in this duration.613* <p>614* The length of the duration is stored using two fields - seconds and nanoseconds.615* The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to616* the length in seconds.617* The total duration is defined by calling this method and {@link #getNano()}.618* <p>619* A {@code Duration} represents a directed distance between two points on the time-line.620* A negative duration is expressed by the negative sign of the seconds part.621* A duration of -1 nanosecond is stored as -1 seconds plus 999,999,999 nanoseconds.622*623* @return the whole seconds part of the length of the duration, positive or negative624*/625public long getSeconds() {626return seconds;627}628629/**630* Gets the number of nanoseconds within the second in this duration.631* <p>632* The length of the duration is stored using two fields - seconds and nanoseconds.633* The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to634* the length in seconds.635* The total duration is defined by calling this method and {@link #getSeconds()}.636* <p>637* A {@code Duration} represents a directed distance between two points on the time-line.638* A negative duration is expressed by the negative sign of the seconds part.639* A duration of -1 nanosecond is stored as -1 seconds plus 999,999,999 nanoseconds.640*641* @return the nanoseconds within the second part of the length of the duration, from 0 to 999,999,999642*/643public int getNano() {644return nanos;645}646647//-----------------------------------------------------------------------648/**649* Returns a copy of this duration with the specified amount of seconds.650* <p>651* This returns a duration with the specified seconds, retaining the652* nano-of-second part of this duration.653* <p>654* This instance is immutable and unaffected by this method call.655*656* @param seconds the seconds to represent, may be negative657* @return a {@code Duration} based on this period with the requested seconds, not null658*/659public Duration withSeconds(long seconds) {660return create(seconds, nanos);661}662663/**664* Returns a copy of this duration with the specified nano-of-second.665* <p>666* This returns a duration with the specified nano-of-second, retaining the667* seconds part of this duration.668* <p>669* This instance is immutable and unaffected by this method call.670*671* @param nanoOfSecond the nano-of-second to represent, from 0 to 999,999,999672* @return a {@code Duration} based on this period with the requested nano-of-second, not null673* @throws DateTimeException if the nano-of-second is invalid674*/675public Duration withNanos(int nanoOfSecond) {676NANO_OF_SECOND.checkValidIntValue(nanoOfSecond);677return create(seconds, nanoOfSecond);678}679680//-----------------------------------------------------------------------681/**682* Returns a copy of this duration with the specified duration added.683* <p>684* This instance is immutable and unaffected by this method call.685*686* @param duration the duration to add, positive or negative, not null687* @return a {@code Duration} based on this duration with the specified duration added, not null688* @throws ArithmeticException if numeric overflow occurs689*/690public Duration plus(Duration duration) {691return plus(duration.getSeconds(), duration.getNano());692}693694/**695* Returns a copy of this duration with the specified duration added.696* <p>697* The duration amount is measured in terms of the specified unit.698* Only a subset of units are accepted by this method.699* The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or700* be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception.701* <p>702* This instance is immutable and unaffected by this method call.703*704* @param amountToAdd the amount to add, measured in terms of the unit, positive or negative705* @param unit the unit that the amount is measured in, must have an exact duration, not null706* @return a {@code Duration} based on this duration with the specified duration added, not null707* @throws UnsupportedTemporalTypeException if the unit is not supported708* @throws ArithmeticException if numeric overflow occurs709*/710public Duration plus(long amountToAdd, TemporalUnit unit) {711Objects.requireNonNull(unit, "unit");712if (unit == DAYS) {713return plus(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY), 0);714}715if (unit.isDurationEstimated()) {716throw new UnsupportedTemporalTypeException("Unit must not have an estimated duration");717}718if (amountToAdd == 0) {719return this;720}721if (unit instanceof ChronoUnit chronoUnit) {722switch (chronoUnit) {723case NANOS: return plusNanos(amountToAdd);724case MICROS: return plusSeconds((amountToAdd / (1000_000L * 1000)) * 1000).plusNanos((amountToAdd % (1000_000L * 1000)) * 1000);725case MILLIS: return plusMillis(amountToAdd);726case SECONDS: return plusSeconds(amountToAdd);727}728return plusSeconds(Math.multiplyExact(unit.getDuration().seconds, amountToAdd));729}730Duration duration = unit.getDuration().multipliedBy(amountToAdd);731return plusSeconds(duration.getSeconds()).plusNanos(duration.getNano());732}733734//-----------------------------------------------------------------------735/**736* Returns a copy of this duration with the specified duration in standard 24 hour days added.737* <p>738* The number of days is multiplied by 86400 to obtain the number of seconds to add.739* This is based on the standard definition of a day as 24 hours.740* <p>741* This instance is immutable and unaffected by this method call.742*743* @param daysToAdd the days to add, positive or negative744* @return a {@code Duration} based on this duration with the specified days added, not null745* @throws ArithmeticException if numeric overflow occurs746*/747public Duration plusDays(long daysToAdd) {748return plus(Math.multiplyExact(daysToAdd, SECONDS_PER_DAY), 0);749}750751/**752* Returns a copy of this duration with the specified duration in hours added.753* <p>754* This instance is immutable and unaffected by this method call.755*756* @param hoursToAdd the hours to add, positive or negative757* @return a {@code Duration} based on this duration with the specified hours added, not null758* @throws ArithmeticException if numeric overflow occurs759*/760public Duration plusHours(long hoursToAdd) {761return plus(Math.multiplyExact(hoursToAdd, SECONDS_PER_HOUR), 0);762}763764/**765* Returns a copy of this duration with the specified duration in minutes added.766* <p>767* This instance is immutable and unaffected by this method call.768*769* @param minutesToAdd the minutes to add, positive or negative770* @return a {@code Duration} based on this duration with the specified minutes added, not null771* @throws ArithmeticException if numeric overflow occurs772*/773public Duration plusMinutes(long minutesToAdd) {774return plus(Math.multiplyExact(minutesToAdd, SECONDS_PER_MINUTE), 0);775}776777/**778* Returns a copy of this duration with the specified duration in seconds added.779* <p>780* This instance is immutable and unaffected by this method call.781*782* @param secondsToAdd the seconds to add, positive or negative783* @return a {@code Duration} based on this duration with the specified seconds added, not null784* @throws ArithmeticException if numeric overflow occurs785*/786public Duration plusSeconds(long secondsToAdd) {787return plus(secondsToAdd, 0);788}789790/**791* Returns a copy of this duration with the specified duration in milliseconds added.792* <p>793* This instance is immutable and unaffected by this method call.794*795* @param millisToAdd the milliseconds to add, positive or negative796* @return a {@code Duration} based on this duration with the specified milliseconds added, not null797* @throws ArithmeticException if numeric overflow occurs798*/799public Duration plusMillis(long millisToAdd) {800return plus(millisToAdd / 1000, (millisToAdd % 1000) * 1000_000);801}802803/**804* Returns a copy of this duration with the specified duration in nanoseconds added.805* <p>806* This instance is immutable and unaffected by this method call.807*808* @param nanosToAdd the nanoseconds to add, positive or negative809* @return a {@code Duration} based on this duration with the specified nanoseconds added, not null810* @throws ArithmeticException if numeric overflow occurs811*/812public Duration plusNanos(long nanosToAdd) {813return plus(0, nanosToAdd);814}815816/**817* Returns a copy of this duration with the specified duration added.818* <p>819* This instance is immutable and unaffected by this method call.820*821* @param secondsToAdd the seconds to add, positive or negative822* @param nanosToAdd the nanos to add, positive or negative823* @return a {@code Duration} based on this duration with the specified seconds added, not null824* @throws ArithmeticException if numeric overflow occurs825*/826private Duration plus(long secondsToAdd, long nanosToAdd) {827if ((secondsToAdd | nanosToAdd) == 0) {828return this;829}830long epochSec = Math.addExact(seconds, secondsToAdd);831epochSec = Math.addExact(epochSec, nanosToAdd / NANOS_PER_SECOND);832nanosToAdd = nanosToAdd % NANOS_PER_SECOND;833long nanoAdjustment = nanos + nanosToAdd; // safe int+NANOS_PER_SECOND834return ofSeconds(epochSec, nanoAdjustment);835}836837//-----------------------------------------------------------------------838/**839* Returns a copy of this duration with the specified duration subtracted.840* <p>841* This instance is immutable and unaffected by this method call.842*843* @param duration the duration to subtract, positive or negative, not null844* @return a {@code Duration} based on this duration with the specified duration subtracted, not null845* @throws ArithmeticException if numeric overflow occurs846*/847public Duration minus(Duration duration) {848long secsToSubtract = duration.getSeconds();849int nanosToSubtract = duration.getNano();850if (secsToSubtract == Long.MIN_VALUE) {851return plus(Long.MAX_VALUE, -nanosToSubtract).plus(1, 0);852}853return plus(-secsToSubtract, -nanosToSubtract);854}855856/**857* Returns a copy of this duration with the specified duration subtracted.858* <p>859* The duration amount is measured in terms of the specified unit.860* Only a subset of units are accepted by this method.861* The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or862* be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception.863* <p>864* This instance is immutable and unaffected by this method call.865*866* @param amountToSubtract the amount to subtract, measured in terms of the unit, positive or negative867* @param unit the unit that the amount is measured in, must have an exact duration, not null868* @return a {@code Duration} based on this duration with the specified duration subtracted, not null869* @throws ArithmeticException if numeric overflow occurs870*/871public Duration minus(long amountToSubtract, TemporalUnit unit) {872return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));873}874875//-----------------------------------------------------------------------876/**877* Returns a copy of this duration with the specified duration in standard 24 hour days subtracted.878* <p>879* The number of days is multiplied by 86400 to obtain the number of seconds to subtract.880* This is based on the standard definition of a day as 24 hours.881* <p>882* This instance is immutable and unaffected by this method call.883*884* @param daysToSubtract the days to subtract, positive or negative885* @return a {@code Duration} based on this duration with the specified days subtracted, not null886* @throws ArithmeticException if numeric overflow occurs887*/888public Duration minusDays(long daysToSubtract) {889return (daysToSubtract == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-daysToSubtract));890}891892/**893* Returns a copy of this duration with the specified duration in hours subtracted.894* <p>895* The number of hours is multiplied by 3600 to obtain the number of seconds to subtract.896* <p>897* This instance is immutable and unaffected by this method call.898*899* @param hoursToSubtract the hours to subtract, positive or negative900* @return a {@code Duration} based on this duration with the specified hours subtracted, not null901* @throws ArithmeticException if numeric overflow occurs902*/903public Duration minusHours(long hoursToSubtract) {904return (hoursToSubtract == Long.MIN_VALUE ? plusHours(Long.MAX_VALUE).plusHours(1) : plusHours(-hoursToSubtract));905}906907/**908* Returns a copy of this duration with the specified duration in minutes subtracted.909* <p>910* The number of hours is multiplied by 60 to obtain the number of seconds to subtract.911* <p>912* This instance is immutable and unaffected by this method call.913*914* @param minutesToSubtract the minutes to subtract, positive or negative915* @return a {@code Duration} based on this duration with the specified minutes subtracted, not null916* @throws ArithmeticException if numeric overflow occurs917*/918public Duration minusMinutes(long minutesToSubtract) {919return (minutesToSubtract == Long.MIN_VALUE ? plusMinutes(Long.MAX_VALUE).plusMinutes(1) : plusMinutes(-minutesToSubtract));920}921922/**923* Returns a copy of this duration with the specified duration in seconds subtracted.924* <p>925* This instance is immutable and unaffected by this method call.926*927* @param secondsToSubtract the seconds to subtract, positive or negative928* @return a {@code Duration} based on this duration with the specified seconds subtracted, not null929* @throws ArithmeticException if numeric overflow occurs930*/931public Duration minusSeconds(long secondsToSubtract) {932return (secondsToSubtract == Long.MIN_VALUE ? plusSeconds(Long.MAX_VALUE).plusSeconds(1) : plusSeconds(-secondsToSubtract));933}934935/**936* Returns a copy of this duration with the specified duration in milliseconds subtracted.937* <p>938* This instance is immutable and unaffected by this method call.939*940* @param millisToSubtract the milliseconds to subtract, positive or negative941* @return a {@code Duration} based on this duration with the specified milliseconds subtracted, not null942* @throws ArithmeticException if numeric overflow occurs943*/944public Duration minusMillis(long millisToSubtract) {945return (millisToSubtract == Long.MIN_VALUE ? plusMillis(Long.MAX_VALUE).plusMillis(1) : plusMillis(-millisToSubtract));946}947948/**949* Returns a copy of this duration with the specified duration in nanoseconds subtracted.950* <p>951* This instance is immutable and unaffected by this method call.952*953* @param nanosToSubtract the nanoseconds to subtract, positive or negative954* @return a {@code Duration} based on this duration with the specified nanoseconds subtracted, not null955* @throws ArithmeticException if numeric overflow occurs956*/957public Duration minusNanos(long nanosToSubtract) {958return (nanosToSubtract == Long.MIN_VALUE ? plusNanos(Long.MAX_VALUE).plusNanos(1) : plusNanos(-nanosToSubtract));959}960961//-----------------------------------------------------------------------962/**963* Returns a copy of this duration multiplied by the scalar.964* <p>965* This instance is immutable and unaffected by this method call.966*967* @param multiplicand the value to multiply the duration by, positive or negative968* @return a {@code Duration} based on this duration multiplied by the specified scalar, not null969* @throws ArithmeticException if numeric overflow occurs970*/971public Duration multipliedBy(long multiplicand) {972if (multiplicand == 0) {973return ZERO;974}975if (multiplicand == 1) {976return this;977}978return create(toBigDecimalSeconds().multiply(BigDecimal.valueOf(multiplicand)));979}980981/**982* Returns a copy of this duration divided by the specified value.983* <p>984* This instance is immutable and unaffected by this method call.985*986* @param divisor the value to divide the duration by, positive or negative, not zero987* @return a {@code Duration} based on this duration divided by the specified divisor, not null988* @throws ArithmeticException if the divisor is zero or if numeric overflow occurs989*/990public Duration dividedBy(long divisor) {991if (divisor == 0) {992throw new ArithmeticException("Cannot divide by zero");993}994if (divisor == 1) {995return this;996}997return create(toBigDecimalSeconds().divide(BigDecimal.valueOf(divisor), RoundingMode.DOWN));998}9991000/**1001* Returns number of whole times a specified Duration occurs within this Duration.1002* <p>1003* This instance is immutable and unaffected by this method call.1004*1005* @param divisor the value to divide the duration by, positive or negative, not null1006* @return number of whole times, rounded toward zero, a specified1007* {@code Duration} occurs within this Duration, may be negative1008* @throws ArithmeticException if the divisor is zero, or if numeric overflow occurs1009* @since 91010*/1011public long dividedBy(Duration divisor) {1012Objects.requireNonNull(divisor, "divisor");1013BigDecimal dividendBigD = toBigDecimalSeconds();1014BigDecimal divisorBigD = divisor.toBigDecimalSeconds();1015return dividendBigD.divideToIntegralValue(divisorBigD).longValueExact();1016}10171018/**1019* Converts this duration to the total length in seconds and1020* fractional nanoseconds expressed as a {@code BigDecimal}.1021*1022* @return the total length of the duration in seconds, with a scale of 9, not null1023*/1024private BigDecimal toBigDecimalSeconds() {1025return BigDecimal.valueOf(seconds).add(BigDecimal.valueOf(nanos, 9));1026}10271028/**1029* Creates an instance of {@code Duration} from a number of seconds.1030*1031* @param seconds the number of seconds, up to scale 9, positive or negative1032* @return a {@code Duration}, not null1033* @throws ArithmeticException if numeric overflow occurs1034*/1035private static Duration create(BigDecimal seconds) {1036BigInteger nanos = seconds.movePointRight(9).toBigIntegerExact();1037BigInteger[] divRem = nanos.divideAndRemainder(BI_NANOS_PER_SECOND);1038if (divRem[0].bitLength() > 63) {1039throw new ArithmeticException("Exceeds capacity of Duration: " + nanos);1040}1041return ofSeconds(divRem[0].longValue(), divRem[1].intValue());1042}10431044//-----------------------------------------------------------------------1045/**1046* Returns a copy of this duration with the length negated.1047* <p>1048* This method swaps the sign of the total length of this duration.1049* For example, {@code PT1.3S} will be returned as {@code PT-1.3S}.1050* <p>1051* This instance is immutable and unaffected by this method call.1052*1053* @return a {@code Duration} based on this duration with the amount negated, not null1054* @throws ArithmeticException if numeric overflow occurs1055*/1056public Duration negated() {1057return multipliedBy(-1);1058}10591060/**1061* Returns a copy of this duration with a positive length.1062* <p>1063* This method returns a positive duration by effectively removing the sign from any negative total length.1064* For example, {@code PT-1.3S} will be returned as {@code PT1.3S}.1065* <p>1066* This instance is immutable and unaffected by this method call.1067*1068* @return a {@code Duration} based on this duration with an absolute length, not null1069* @throws ArithmeticException if numeric overflow occurs1070*/1071public Duration abs() {1072return isNegative() ? negated() : this;1073}10741075//-------------------------------------------------------------------------1076/**1077* Adds this duration to the specified temporal object.1078* <p>1079* This returns a temporal object of the same observable type as the input1080* with this duration added.1081* <p>1082* In most cases, it is clearer to reverse the calling pattern by using1083* {@link Temporal#plus(TemporalAmount)}.1084* <pre>1085* // these two lines are equivalent, but the second approach is recommended1086* dateTime = thisDuration.addTo(dateTime);1087* dateTime = dateTime.plus(thisDuration);1088* </pre>1089* <p>1090* The calculation will add the seconds, then nanos.1091* Only non-zero amounts will be added.1092* <p>1093* This instance is immutable and unaffected by this method call.1094*1095* @param temporal the temporal object to adjust, not null1096* @return an object of the same type with the adjustment made, not null1097* @throws DateTimeException if unable to add1098* @throws ArithmeticException if numeric overflow occurs1099*/1100@Override1101public Temporal addTo(Temporal temporal) {1102if (seconds != 0) {1103temporal = temporal.plus(seconds, SECONDS);1104}1105if (nanos != 0) {1106temporal = temporal.plus(nanos, NANOS);1107}1108return temporal;1109}11101111/**1112* Subtracts this duration from the specified temporal object.1113* <p>1114* This returns a temporal object of the same observable type as the input1115* with this duration subtracted.1116* <p>1117* In most cases, it is clearer to reverse the calling pattern by using1118* {@link Temporal#minus(TemporalAmount)}.1119* <pre>1120* // these two lines are equivalent, but the second approach is recommended1121* dateTime = thisDuration.subtractFrom(dateTime);1122* dateTime = dateTime.minus(thisDuration);1123* </pre>1124* <p>1125* The calculation will subtract the seconds, then nanos.1126* Only non-zero amounts will be added.1127* <p>1128* This instance is immutable and unaffected by this method call.1129*1130* @param temporal the temporal object to adjust, not null1131* @return an object of the same type with the adjustment made, not null1132* @throws DateTimeException if unable to subtract1133* @throws ArithmeticException if numeric overflow occurs1134*/1135@Override1136public Temporal subtractFrom(Temporal temporal) {1137if (seconds != 0) {1138temporal = temporal.minus(seconds, SECONDS);1139}1140if (nanos != 0) {1141temporal = temporal.minus(nanos, NANOS);1142}1143return temporal;1144}11451146//-----------------------------------------------------------------------1147/**1148* Gets the number of days in this duration.1149* <p>1150* This returns the total number of days in the duration by dividing the1151* number of seconds by 86400.1152* This is based on the standard definition of a day as 24 hours.1153* <p>1154* This instance is immutable and unaffected by this method call.1155*1156* @return the number of days in the duration, may be negative1157*/1158public long toDays() {1159return seconds / SECONDS_PER_DAY;1160}11611162/**1163* Gets the number of hours in this duration.1164* <p>1165* This returns the total number of hours in the duration by dividing the1166* number of seconds by 3600.1167* <p>1168* This instance is immutable and unaffected by this method call.1169*1170* @return the number of hours in the duration, may be negative1171*/1172public long toHours() {1173return seconds / SECONDS_PER_HOUR;1174}11751176/**1177* Gets the number of minutes in this duration.1178* <p>1179* This returns the total number of minutes in the duration by dividing the1180* number of seconds by 60.1181* <p>1182* This instance is immutable and unaffected by this method call.1183*1184* @return the number of minutes in the duration, may be negative1185*/1186public long toMinutes() {1187return seconds / SECONDS_PER_MINUTE;1188}11891190/**1191* Gets the number of seconds in this duration.1192* <p>1193* This returns the total number of whole seconds in the duration.1194* <p>1195* This instance is immutable and unaffected by this method call.1196*1197* @return the whole seconds part of the length of the duration, positive or negative1198* @since 91199*/1200public long toSeconds() {1201return seconds;1202}12031204/**1205* Converts this duration to the total length in milliseconds.1206* <p>1207* If this duration is too large to fit in a {@code long} milliseconds, then an1208* exception is thrown.1209* <p>1210* If this duration has greater than millisecond precision, then the conversion1211* will drop any excess precision information as though the amount in nanoseconds1212* was subject to integer division by one million.1213*1214* @return the total length of the duration in milliseconds1215* @throws ArithmeticException if numeric overflow occurs1216*/1217public long toMillis() {1218long tempSeconds = seconds;1219long tempNanos = nanos;1220if (tempSeconds < 0) {1221// change the seconds and nano value to1222// handle Long.MIN_VALUE case1223tempSeconds = tempSeconds + 1;1224tempNanos = tempNanos - NANOS_PER_SECOND;1225}1226long millis = Math.multiplyExact(tempSeconds, 1000);1227millis = Math.addExact(millis, tempNanos / NANOS_PER_MILLI);1228return millis;1229}12301231/**1232* Converts this duration to the total length in nanoseconds expressed as a {@code long}.1233* <p>1234* If this duration is too large to fit in a {@code long} nanoseconds, then an1235* exception is thrown.1236*1237* @return the total length of the duration in nanoseconds1238* @throws ArithmeticException if numeric overflow occurs1239*/1240public long toNanos() {1241long tempSeconds = seconds;1242long tempNanos = nanos;1243if (tempSeconds < 0) {1244// change the seconds and nano value to1245// handle Long.MIN_VALUE case1246tempSeconds = tempSeconds + 1;1247tempNanos = tempNanos - NANOS_PER_SECOND;1248}1249long totalNanos = Math.multiplyExact(tempSeconds, NANOS_PER_SECOND);1250totalNanos = Math.addExact(totalNanos, tempNanos);1251return totalNanos;1252}12531254/**1255* Extracts the number of days in the duration.1256* <p>1257* This returns the total number of days in the duration by dividing the1258* number of seconds by 86400.1259* This is based on the standard definition of a day as 24 hours.1260* <p>1261* This instance is immutable and unaffected by this method call.1262*1263* @return the number of days in the duration, may be negative1264* @since 91265*/1266public long toDaysPart(){1267return seconds / SECONDS_PER_DAY;1268}12691270/**1271* Extracts the number of hours part in the duration.1272* <p>1273* This returns the number of remaining hours when dividing {@link #toHours}1274* by hours in a day.1275* This is based on the standard definition of a day as 24 hours.1276* <p>1277* This instance is immutable and unaffected by this method call.1278*1279* @return the number of hours part in the duration, may be negative1280* @since 91281*/1282public int toHoursPart(){1283return (int) (toHours() % 24);1284}12851286/**1287* Extracts the number of minutes part in the duration.1288* <p>1289* This returns the number of remaining minutes when dividing {@link #toMinutes}1290* by minutes in an hour.1291* This is based on the standard definition of an hour as 60 minutes.1292* <p>1293* This instance is immutable and unaffected by this method call.1294*1295* @return the number of minutes parts in the duration, may be negative1296* @since 91297*/1298public int toMinutesPart(){1299return (int) (toMinutes() % MINUTES_PER_HOUR);1300}13011302/**1303* Extracts the number of seconds part in the duration.1304* <p>1305* This returns the remaining seconds when dividing {@link #toSeconds}1306* by seconds in a minute.1307* This is based on the standard definition of a minute as 60 seconds.1308* <p>1309* This instance is immutable and unaffected by this method call.1310*1311* @return the number of seconds parts in the duration, may be negative1312* @since 91313*/1314public int toSecondsPart(){1315return (int) (seconds % SECONDS_PER_MINUTE);1316}13171318/**1319* Extracts the number of milliseconds part of the duration.1320* <p>1321* This returns the milliseconds part by dividing the number of nanoseconds by 1,000,000.1322* The length of the duration is stored using two fields - seconds and nanoseconds.1323* The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to1324* the length in seconds.1325* The total duration is defined by calling {@link #getNano()} and {@link #getSeconds()}.1326* <p>1327* This instance is immutable and unaffected by this method call.1328*1329* @return the number of milliseconds part of the duration.1330* @since 91331*/1332public int toMillisPart(){1333return nanos / 1000_000;1334}13351336/**1337* Get the nanoseconds part within seconds of the duration.1338* <p>1339* The length of the duration is stored using two fields - seconds and nanoseconds.1340* The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to1341* the length in seconds.1342* The total duration is defined by calling {@link #getNano()} and {@link #getSeconds()}.1343* <p>1344* This instance is immutable and unaffected by this method call.1345*1346* @return the nanoseconds within the second part of the length of the duration, from 0 to 999,999,9991347* @since 91348*/1349public int toNanosPart(){1350return nanos;1351}135213531354//-----------------------------------------------------------------------1355/**1356* Returns a copy of this {@code Duration} truncated to the specified unit.1357* <p>1358* Truncating the duration returns a copy of the original with conceptual fields1359* smaller than the specified unit set to zero.1360* For example, truncating with the {@link ChronoUnit#MINUTES MINUTES} unit will1361* round down towards zero to the nearest minute, setting the seconds and1362* nanoseconds to zero.1363* <p>1364* The unit must have a {@linkplain TemporalUnit#getDuration() duration}1365* that divides into the length of a standard day without remainder.1366* This includes all1367* {@linkplain ChronoUnit#isTimeBased() time-based units on {@code ChronoUnit}}1368* and {@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 null1373* @return a {@code Duration} based on this duration with the time truncated, not null1374* @throws DateTimeException if the unit is invalid for truncation1375* @throws UnsupportedTemporalTypeException if the unit is not supported1376* @since 91377*/1378public Duration truncatedTo(TemporalUnit unit) {1379Objects.requireNonNull(unit, "unit");1380if (unit == ChronoUnit.SECONDS && (seconds >= 0 || nanos == 0)) {1381return new Duration(seconds, 0);1382} else if (unit == ChronoUnit.NANOS) {1383return this;1384}1385Duration unitDur = unit.getDuration();1386if (unitDur.getSeconds() > LocalTime.SECONDS_PER_DAY) {1387throw new UnsupportedTemporalTypeException("Unit is too large to be used for truncation");1388}1389long dur = unitDur.toNanos();1390if ((LocalTime.NANOS_PER_DAY % dur) != 0) {1391throw new UnsupportedTemporalTypeException("Unit must divide into a standard day without remainder");1392}1393long nod = (seconds % LocalTime.SECONDS_PER_DAY) * LocalTime.NANOS_PER_SECOND + nanos;1394long result = (nod / dur) * dur;1395return plusNanos(result - nod);1396}13971398//-----------------------------------------------------------------------1399/**1400* Compares this duration to the specified {@code Duration}.1401* <p>1402* The comparison is based on the total length of the durations.1403* It is "consistent with equals", as defined by {@link Comparable}.1404*1405* @param otherDuration the other duration to compare to, not null1406* @return the comparator value, negative if less, positive if greater1407*/1408@Override1409public int compareTo(Duration otherDuration) {1410int cmp = Long.compare(seconds, otherDuration.seconds);1411if (cmp != 0) {1412return cmp;1413}1414return nanos - otherDuration.nanos;1415}14161417//-----------------------------------------------------------------------1418/**1419* Checks if this duration is equal to the specified {@code Duration}.1420* <p>1421* The comparison is based on the total length of the durations.1422*1423* @param other the other duration, null returns false1424* @return true if the other duration is equal to this one1425*/1426@Override1427public boolean equals(Object other) {1428if (this == other) {1429return true;1430}1431return (other instanceof Duration otherDuration)1432&& this.seconds == otherDuration.seconds1433&& this.nanos == otherDuration.nanos;1434}14351436/**1437* A hash code for this duration.1438*1439* @return a suitable hash code1440*/1441@Override1442public int hashCode() {1443return ((int) (seconds ^ (seconds >>> 32))) + (51 * nanos);1444}14451446//-----------------------------------------------------------------------1447/**1448* A string representation of this duration using ISO-8601 seconds1449* based representation, such as {@code PT8H6M12.345S}.1450* <p>1451* The format of the returned string will be {@code PTnHnMnS}, where n is1452* the relevant hours, minutes or seconds part of the duration.1453* Any fractional seconds are placed after a decimal point in the seconds section.1454* If a section has a zero value, it is omitted.1455* The hours, minutes and seconds will all have the same sign.1456* <p>1457* Examples:1458* <pre>1459* "20.345 seconds" -- "PT20.345S1460* "15 minutes" (15 * 60 seconds) -- "PT15M"1461* "10 hours" (10 * 3600 seconds) -- "PT10H"1462* "2 days" (2 * 86400 seconds) -- "PT48H"1463* </pre>1464* Note that multiples of 24 hours are not output as days to avoid confusion1465* with {@code Period}.1466*1467* @return an ISO-8601 representation of this duration, not null1468*/1469@Override1470public String toString() {1471if (this == ZERO) {1472return "PT0S";1473}1474long effectiveTotalSecs = seconds;1475if (seconds < 0 && nanos > 0) {1476effectiveTotalSecs++;1477}1478long hours = effectiveTotalSecs / SECONDS_PER_HOUR;1479int minutes = (int) ((effectiveTotalSecs % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE);1480int secs = (int) (effectiveTotalSecs % SECONDS_PER_MINUTE);1481StringBuilder buf = new StringBuilder(24);1482buf.append("PT");1483if (hours != 0) {1484buf.append(hours).append('H');1485}1486if (minutes != 0) {1487buf.append(minutes).append('M');1488}1489if (secs == 0 && nanos == 0 && buf.length() > 2) {1490return buf.toString();1491}1492if (seconds < 0 && nanos > 0) {1493if (secs == 0) {1494buf.append("-0");1495} else {1496buf.append(secs);1497}1498} else {1499buf.append(secs);1500}1501if (nanos > 0) {1502int pos = buf.length();1503if (seconds < 0) {1504buf.append(2 * NANOS_PER_SECOND - nanos);1505} else {1506buf.append(nanos + NANOS_PER_SECOND);1507}1508while (buf.charAt(buf.length() - 1) == '0') {1509buf.setLength(buf.length() - 1);1510}1511buf.setCharAt(pos, '.');1512}1513buf.append('S');1514return buf.toString();1515}15161517//-----------------------------------------------------------------------1518/**1519* Writes the object using a1520* <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>.1521* @serialData1522* <pre>1523* out.writeByte(1); // identifies a Duration1524* out.writeLong(seconds);1525* out.writeInt(nanos);1526* </pre>1527*1528* @return the instance of {@code Ser}, not null1529*/1530@java.io.Serial1531private Object writeReplace() {1532return new Ser(Ser.DURATION_TYPE, this);1533}15341535/**1536* Defend against malicious streams.1537*1538* @param s the stream to read1539* @throws InvalidObjectException always1540*/1541@java.io.Serial1542private void readObject(ObjectInputStream s) throws InvalidObjectException {1543throw new InvalidObjectException("Deserialization via serialization delegate");1544}15451546void writeExternal(DataOutput out) throws IOException {1547out.writeLong(seconds);1548out.writeInt(nanos);1549}15501551static Duration readExternal(DataInput in) throws IOException {1552long seconds = in.readLong();1553int nanos = in.readInt();1554return Duration.ofSeconds(seconds, nanos);1555}15561557}155815591560