Duration

A time-based amount of time, such as '34.5 seconds'. !(p) This class models a quantity or amount of time _in terms of seconds and nanoseconds. It can be accessed using other duration-based units, such as minutes and hours. In addition, the {@link ChronoUnit#DAYS DAYS} unit can be used and is treated as exactly equal to 24 hours, thus ignoring daylight savings effects. See {@link Period} for the date-based equivalent to this class. !(p) A physical duration could be of infinite length. For practicality, the duration is stored with constraints similar to {@link Instant}. The duration uses nanosecond resolution with a maximum value of the seconds that can be held _in a {@code long}. This is greater than the current estimated age of the universe. !(p) The range of a duration requires the storage of a number larger than a {@code long}. To achieve this, the class stores a {@code long} representing seconds and an {@code int} representing nanosecond-of-second, which will always be between 0 and 999,999,999. The model is of a directed duration, meaning that the duration may be negative. !(p) The duration is measured _in "seconds", but these are not necessarily identical to the scientific "SI second" definition based on atomic clocks. This difference only impacts durations measured near a leap-second and should not affect most applications. See {@link Instant} for a discussion as to the meaning of the second and time-scales.

!(p) This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a> class; use of identity-sensitive operations (including reference equality ({@code ==}), identity hash code, or synchronization) on instances of {@code Duration} may have unpredictable results and should be avoided. The {@code equals} method should be used for comparisons.

@implSpec This class is immutable and thread-safe.

@since 1.8

final
class Duration : TemporalAmount , Comparable!(Duration) {}

Constructors

this
this(long seconds, int nanos)

Constructs an instance of {@code Duration} using seconds and nanoseconds.

Members

Functions

abs
Duration abs()

Returns a copy of this duration with a positive length. !(p) This method returns a positive duration by effectively removing the sign from any negative total length. For example, {@code PT-1.3S} will be returned as {@code PT1.3S}. !(p) This instance is immutable and unaffected by this method call.

addTo
Temporal addTo(Temporal temporal)

Adds this duration to the specified temporal object. !(p) This returns a temporal object of the same observable type as the input with this duration added. !(p) In most cases, it is clearer to reverse the calling pattern by using {@link Temporal#plus(TemporalAmount)}. !(pre) // these two lines are equivalent, but the second approach is recommended dateTime = thisDuration.addTo(dateTime); dateTime = dateTime.plus(thisDuration); </pre> !(p) The calculation will add the seconds, then nanos. Only non-zero amounts will be added. !(p) This instance is immutable and unaffected by this method call.

compareTo
int compareTo(Duration otherDuration)

Compares this duration to the specified {@code Duration}. !(p) The comparison is based on the total length of the durations. It is "consistent with equals", as defined by {@link Comparable}.

get
long get(TemporalUnit unit)

Gets the value of the requested unit. !(p) This returns a value for each of the two supported units, {@link ChronoUnit#SECONDS SECONDS} and {@link ChronoUnit#NANOS NANOS}. All other units throw an exception.

getNano
int getNano()

Gets the number of nanoseconds within the second _in this duration. !(p) The length of the duration is stored using two fields - seconds and nanoseconds. The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to the length _in seconds. The total duration is defined by calling this method and {@link #getSeconds()}. !(p) A {@code Duration} represents a directed distance between two points on the time-line. A negative duration is expressed by the negative sign of the seconds part. A duration of -1 nanosecond is stored as -1 seconds plus 999,999,999 nanoseconds.

getSeconds
long getSeconds()

Gets the number of seconds _in this duration. !(p) The length of the duration is stored using two fields - seconds and nanoseconds. The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to the length _in seconds. The total duration is defined by calling this method and {@link #getNano()}. !(p) A {@code Duration} represents a directed distance between two points on the time-line. A negative duration is expressed by the negative sign of the seconds part. A duration of -1 nanosecond is stored as -1 seconds plus 999,999,999 nanoseconds.

getUnits
List!(TemporalUnit) getUnits()

Gets the set of units supported by this duration. !(p) The supported units are {@link ChronoUnit#SECONDS SECONDS}, and {@link ChronoUnit#NANOS NANOS}. They are returned _in the order seconds, nanos. !(p) This set can be used _in conjunction with {@link #get(TemporalUnit)} to access the entire state of the duration.

isNegative
bool isNegative()

Checks if this duration is negative, excluding zero. !(p) A {@code Duration} represents a directed distance between two points on the time-line and can therefore be positive, zero or negative. This method checks whether the length is less than zero.

isZero
bool isZero()

Checks if this duration is zero length. !(p) A {@code Duration} represents a directed distance between two points on the time-line and can therefore be positive, zero or negative. This method checks whether the length is zero.

minus
Duration minus(Duration duration)

Returns a copy of this duration with the specified duration subtracted. !(p) This instance is immutable and unaffected by this method call.

minus
Duration minus(long amountToSubtract, TemporalUnit unit)

Returns a copy of this duration with the specified duration subtracted. !(p) The duration amount is measured _in terms of the specified unit. Only a subset of units are accepted by this method. The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception. !(p) This instance is immutable and unaffected by this method call.

minusDays
Duration minusDays(long daysToSubtract)

Returns a copy of this duration with the specified duration _in standard 24 hour days subtracted. !(p) The number of days is multiplied by 86400 to obtain the number of seconds to subtract. This is based on the standard definition of a day as 24 hours. !(p) This instance is immutable and unaffected by this method call.

minusHours
Duration minusHours(long hoursToSubtract)

Returns a copy of this duration with the specified duration _in hours subtracted. !(p) The number of hours is multiplied by 3600 to obtain the number of seconds to subtract. !(p) This instance is immutable and unaffected by this method call.

minusMillis
Duration minusMillis(long millisToSubtract)

Returns a copy of this duration with the specified duration _in milliseconds subtracted. !(p) This instance is immutable and unaffected by this method call.

minusMinutes
Duration minusMinutes(long minutesToSubtract)

Returns a copy of this duration with the specified duration _in minutes subtracted. !(p) The number of hours is multiplied by 60 to obtain the number of seconds to subtract. !(p) This instance is immutable and unaffected by this method call.

minusNanos
Duration minusNanos(long nanosToSubtract)

Returns a copy of this duration with the specified duration _in nanoseconds subtracted. !(p) This instance is immutable and unaffected by this method call.

minusSeconds
Duration minusSeconds(long secondsToSubtract)

Returns a copy of this duration with the specified duration _in seconds subtracted. !(p) This instance is immutable and unaffected by this method call.

multipliedBy
Duration multipliedBy(long multiplicand)

Returns a copy of this duration multiplied by the scalar. !(p) This instance is immutable and unaffected by this method call.

negated
Duration negated()

Returns a copy of this duration with the length negated. !(p) This method swaps the sign of the total length of this duration. For example, {@code PT1.3S} will be returned as {@code PT-1.3S}. !(p) This instance is immutable and unaffected by this method call.

opCmp
int opCmp(Duration o)
Undocumented in source. Be warned that the author may not have intended to support it.
opEquals
bool opEquals(Object otherDuration)

Checks if this duration is equal to the specified {@code Duration}. !(p) The comparison is based on the total length of the durations.

plus
Duration plus(Duration duration)

Returns a copy of this duration with the specified duration added. !(p) This instance is immutable and unaffected by this method call.

plus
Duration plus(long amountToAdd, TemporalUnit unit)

Returns a copy of this duration with the specified duration added. !(p) The duration amount is measured _in terms of the specified unit. Only a subset of units are accepted by this method. The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception. !(p) This instance is immutable and unaffected by this method call.

plusDays
Duration plusDays(long daysToAdd)

Returns a copy of this duration with the specified duration _in standard 24 hour days added. !(p) The number of days is multiplied by 86400 to obtain the number of seconds to add. This is based on the standard definition of a day as 24 hours. !(p) This instance is immutable and unaffected by this method call.

plusHours
Duration plusHours(long hoursToAdd)

Returns a copy of this duration with the specified duration _in hours added. !(p) This instance is immutable and unaffected by this method call.

plusMillis
Duration plusMillis(long millisToAdd)

Returns a copy of this duration with the specified duration _in milliseconds added. !(p) This instance is immutable and unaffected by this method call.

plusMinutes
Duration plusMinutes(long minutesToAdd)

Returns a copy of this duration with the specified duration _in minutes added. !(p) This instance is immutable and unaffected by this method call.

plusNanos
Duration plusNanos(long nanosToAdd)

Returns a copy of this duration with the specified duration _in nanoseconds added. !(p) This instance is immutable and unaffected by this method call.

plusSeconds
Duration plusSeconds(long secondsToAdd)

Returns a copy of this duration with the specified duration _in seconds added. !(p) This instance is immutable and unaffected by this method call.

subtractFrom
Temporal subtractFrom(Temporal temporal)

Subtracts this duration from the specified temporal object. !(p) This returns a temporal object of the same observable type as the input with this duration subtracted. !(p) In most cases, it is clearer to reverse the calling pattern by using {@link Temporal#minus(TemporalAmount)}. !(pre) // these two lines are equivalent, but the second approach is recommended dateTime = thisDuration.subtractFrom(dateTime); dateTime = dateTime.minus(thisDuration); </pre> !(p) The calculation will subtract the seconds, then nanos. Only non-zero amounts will be added. !(p) This instance is immutable and unaffected by this method call.

toDays
long toDays()

Gets the number of days _in this duration. !(p) This returns the total number of days _in the duration by dividing the number of seconds by 86400. This is based on the standard definition of a day as 24 hours. !(p) This instance is immutable and unaffected by this method call.

toDaysPart
long toDaysPart()

Extracts the number of days _in the duration. !(p) This returns the total number of days _in the duration by dividing the number of seconds by 86400. This is based on the standard definition of a day as 24 hours. !(p) This instance is immutable and unaffected by this method call.

toHash
size_t toHash()

A hash code for this duration.

toHours
long toHours()

Gets the number of hours _in this duration. !(p) This returns the total number of hours _in the duration by dividing the number of seconds by 3600. !(p) This instance is immutable and unaffected by this method call.

toHoursPart
int toHoursPart()

Extracts the number of hours part _in the duration. !(p) This returns the number of remaining hours when dividing {@link #toHours} by hours _in a day. This is based on the standard definition of a day as 24 hours. !(p) This instance is immutable and unaffected by this method call.

toMillis
long toMillis()

Converts this duration to the total length _in milliseconds. !(p) If this duration is too large to fit _in a {@code long} milliseconds, then an exception is thrown. !(p) If this duration has greater than millisecond precision, then the conversion will drop any excess precision information as though the amount _in nanoseconds was subject to integer division by one million.

toMillisPart
int toMillisPart()

Extracts the number of milliseconds part of the duration. !(p) This returns the milliseconds part by dividing the number of nanoseconds by 1,000,000. The length of the duration is stored using two fields - seconds and nanoseconds. The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to the length _in seconds. The total duration is defined by calling {@link #getNano()} and {@link #getSeconds()}. !(p) This instance is immutable and unaffected by this method call.

toMinutes
long toMinutes()

Gets the number of minutes _in this duration. !(p) This returns the total number of minutes _in the duration by dividing the number of seconds by 60. !(p) This instance is immutable and unaffected by this method call.

toMinutesPart
int toMinutesPart()

Extracts the number of minutes part _in the duration. !(p) This returns the number of remaining minutes when dividing {@link #toMinutes} by minutes _in an hour. This is based on the standard definition of an hour as 60 minutes. !(p) This instance is immutable and unaffected by this method call.

toNanos
long toNanos()

Converts this duration to the total length _in nanoseconds expressed as a {@code long}. !(p) If this duration is too large to fit _in a {@code long} nanoseconds, then an exception is thrown.

toNanosPart
int toNanosPart()

Get the nanoseconds part within seconds of the duration. !(p) The length of the duration is stored using two fields - seconds and nanoseconds. The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to the length _in seconds. The total duration is defined by calling {@link #getNano()} and {@link #getSeconds()}. !(p) This instance is immutable and unaffected by this method call.

toSeconds
long toSeconds()

Gets the number of seconds _in this duration. !(p) This returns the total number of whole seconds _in the duration. !(p) This instance is immutable and unaffected by this method call.

toSecondsPart
int toSecondsPart()

Extracts the number of seconds part _in the duration. !(p) This returns the remaining seconds when dividing {@link #toSeconds} by seconds _in a minute. This is based on the standard definition of a minute as 60 seconds. !(p) This instance is immutable and unaffected by this method call.

toString
string toString()

A string representation of this duration using ISO-8601 seconds based representation, such as {@code PT8H6M12.345S}. !(p) The format of the returned string will be {@code PTnHnMnS}, where n is the relevant hours, minutes or seconds part of the duration. Any fractional seconds are placed after a decimal point _in the seconds section. If a section has a zero value, it is omitted. The hours, minutes and seconds will all have the same sign. !(p)

truncatedTo
Duration truncatedTo(TemporalUnit unit)

Returns a copy of this {@code Duration} truncated to the specified unit. !(p) Truncating the duration returns a copy of the original with conceptual fields smaller than the specified unit set to zero. For example, truncating with the {@link ChronoUnit#MINUTES MINUTES} unit will round down towards zero to the nearest minute, setting the seconds and nanoseconds to zero. !(p) The unit must have a {@linkplain TemporalUnit#getDuration() duration} that divides into the length of a standard day without remainder. This includes all {@linkplain ChronoUnit#isTimeBased() time-based units on {@code ChronoUnit}} and {@link ChronoUnit#DAYS DAYS}. Other ChronoUnits throw an exception. !(p) This instance is immutable and unaffected by this method call.

withNanos
Duration withNanos(int nanoOfSecond)

Returns a copy of this duration with the specified nano-of-second. !(p) This returns a duration with the specified nano-of-second, retaining the seconds part of this duration. !(p) This instance is immutable and unaffected by this method call.

withSeconds
Duration withSeconds(long seconds)

Returns a copy of this duration with the specified amount of seconds. !(p) This returns a duration with the specified seconds, retaining the nano-of-second part of this duration. !(p) This instance is immutable and unaffected by this method call.

writeExternal
void writeExternal(DataOutput _out)

Defend against malicious streams.

Static functions

BI_NANOS_PER_SECOND
BigInteger BI_NANOS_PER_SECOND()

Constant for nanos per second.

ZERO
Duration ZERO()

Constant for a duration of zero.

between
Duration between(Temporal startInclusive, Temporal endExclusive)

Obtains a {@code Duration} representing the duration between two temporal objects. !(p) This calculates the duration between two temporal objects. If the objects are of different types, then the duration is calculated based on the type of the first object. For example, if the first argument is a {@code TimeConstant} then the second argument is converted to a {@code TimeConstant}. !(p) The specified temporal objects must support the {@link ChronoUnit#SECONDS SECONDS} unit. For full accuracy, either the {@link ChronoUnit#NANOS NANOS} unit or the {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} field should be supported. !(p) The result of this method can be a negative period if the end is before the start. To guarantee to obtain a positive duration call {@link #abs()} on the result.

from
Duration from(TemporalAmount amount)

Obtains an instance of {@code Duration} from a temporal amount. !(p) This obtains a duration based on the specified amount. A {@code TemporalAmount} represents an amount of time, which may be date-based or time-based, which this factory extracts to a duration. !(p) The conversion loops around the set of units from the amount and uses the {@linkplain TemporalUnit#getDuration() duration} of the unit to calculate the total {@code Duration}. Only a subset of units are accepted by this method. The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or be {@link ChronoUnit#DAYS} which is treated as 24 hours. If any other units are found then an exception is thrown.

of
Duration of(long amount, TemporalUnit unit)

Obtains a {@code Duration} representing an amount _in the specified unit. !(p) The parameters represent the two parts of a phrase like '6 Hours'. For example: !(pre) Duration.of(3, SECONDS); Duration.of(465, HOURS); </pre> Only a subset of units are accepted by this method. The unit must either have an {@linkplain TemporalUnit#isDurationEstimated() exact duration} or be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception.

ofDays
Duration ofDays(long days)

Obtains a {@code Duration} representing a number of standard 24 hour days. !(p) The seconds are calculated based on the standard definition of a day, where each day is 86400 seconds which implies a 24 hour day. The nanosecond _in second field is set to zero.

ofHours
Duration ofHours(long hours)

Obtains a {@code Duration} representing a number of standard hours. !(p) The seconds are calculated based on the standard definition of an hour, where each hour is 3600 seconds. The nanosecond _in second field is set to zero.

ofMillis
Duration ofMillis(long millis)

Obtains a {@code Duration} representing a number of milliseconds. !(p) The seconds and nanoseconds are extracted from the specified milliseconds.

ofMinutes
Duration ofMinutes(long minutes)

Obtains a {@code Duration} representing a number of standard minutes. !(p) The seconds are calculated based on the standard definition of a minute, where each minute is 60 seconds. The nanosecond _in second field is set to zero.

ofNanos
Duration ofNanos(long nanos)

Obtains a {@code Duration} representing a number of nanoseconds. !(p) The seconds and nanoseconds are extracted from the specified nanoseconds.

ofSeconds
Duration ofSeconds(long seconds)

Obtains a {@code Duration} representing a number of seconds. !(p) The nanosecond _in second field is set to zero.

ofSeconds
Duration ofSeconds(long seconds, long nanoAdjustment)

Obtains a {@code Duration} representing a number of seconds and an adjustment _in nanoseconds. !(p) This method allows an arbitrary number of nanoseconds to be passed _in. The factory will alter the values of the second and nanosecond _in order to ensure that the stored nanosecond is _in the range 0 to 999,999,999. For example, the following will result _in exactly the same duration: !(pre) Duration.ofSeconds(3, 1); Duration.ofSeconds(4, -999_999_999); Duration.ofSeconds(2, 1000_000_001); </pre>

parse
Duration parse(string text)

Obtains a {@code Duration} from a text string such as {@code PnDTnHnMn.nS}. !(p) This will parse a textual representation of a duration, including the string produced by {@code toString()}. The formats accepted are based on the ISO-8601 duration format {@code PnDTnHnMn.nS} with days considered to be exactly 24 hours. !(p) The string starts with an optional sign, denoted by the ASCII negative or positive symbol. If negative, the whole period is negated. The ASCII letter "P" is next _in upper or lower case. There are then four sections, each consisting of a number and a suffix. The sections have suffixes _in ASCII of "D", "H", "M" and "S" for days, hours, minutes and seconds, accepted _in upper or lower case. The suffixes must occur _in order. The ASCII letter "T" must occur before the first occurrence, if any, of an hour, minute or second section. At least one of the four sections must be present, and if "T" is present there must be at least one section after the "T". The number part of each section must consist of one or more ASCII digits. The number may be prefixed by the ASCII negative or positive symbol. The number of days, hours and minutes must parse to a {@code long}. The number of seconds must parse to a {@code long} with optional fraction. The decimal point may be either a dot or a comma. The fractional part may have from zero to 9 digits. !(p) The leading plus/minus sign, and negative values for other units are not part of the ISO-8601 standard. !(p)

readExternal
Duration readExternal(DataInput _in)
Undocumented in source. Be warned that the author may not have intended to support it.

Variables

PATTERN
enum string PATTERN;

The pattern for parsing.

Inherited Members

From TemporalAmount

get
long get(TemporalUnit unit)

Returns the value of the requested unit. The units returned from {@link #getUnits()} uniquely define the value of the {@code TemporalAmount}. A value must be returned for each unit listed _in {@code getUnits}.

getUnits
List!(TemporalUnit) getUnits()

Returns the list of units uniquely defining the value of this TemporalAmount. The list of {@code TemporalUnits} is defined by the implementation class. The list is a snapshot of the units at the time {@code getUnits} is called and is not mutable. The units are ordered from longest duration to the shortest duration of the unit.

addTo
Temporal addTo(Temporal temporal)

Adds to the specified temporal object. !(p) Adds the amount to the specified temporal object using the logic encapsulated _in the implementing class. !(p) There are two equivalent ways of using this method. The first is to invoke this method directly. The second is to use {@link Temporal#plus(TemporalAmount)}: !(pre) // These two lines are equivalent, but the second approach is recommended dateTime = amount.addTo(dateTime); dateTime = dateTime.plus(adder); </pre> It is recommended to use the second approach, {@code plus(TemporalAmount)}, as it is a lot clearer to read _in code.

subtractFrom
Temporal subtractFrom(Temporal temporal)

Subtracts this object from the specified temporal object. !(p) Subtracts the amount from the specified temporal object using the logic encapsulated _in the implementing class. !(p) There are two equivalent ways of using this method. The first is to invoke this method directly. The second is to use {@link Temporal#minus(TemporalAmount)}: !(pre) // these two lines are equivalent, but the second approach is recommended dateTime = amount.subtractFrom(dateTime); dateTime = dateTime.minus(amount); </pre> It is recommended to use the second approach, {@code minus(TemporalAmount)}, as it is a lot clearer to read _in code.

Meta