public final class Duration extends Object implements TemporalAmount, Comparable<Duration>, Serializable
This class models a quantity or amount of time in terms of seconds and nanoseconds.
It can be accessed using other durationbased units, such as minutes and hours.
In addition, the DAYS
unit can be used and is treated as
exactly equal to 24 hours, thus ignoring daylight savings effects.
See Period
for the datebased equivalent to this class.
A physical duration could be of infinite length.
For practicality, the duration is stored with constraints similar to Instant
.
The duration uses nanosecond resolution with a maximum value of the seconds that can
be held in a long
. This is greater than the current estimated age of the universe.
The range of a duration requires the storage of a number larger than a long
.
To achieve this, the class stores a long
representing seconds and an int
representing nanosecondofsecond, which will always be between 0 and 999,999,999.
The model is of a directed duration, meaning that the duration may be negative.
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 leapsecond and should not affect
most applications.
See Instant
for a discussion as to the meaning of the second and timescales.
This is a valuebased
class; use of identitysensitive operations (including reference equality
(==
), identity hash code, or synchronization) on instances of
Duration
may have unpredictable results and should be avoided.
The equals
method should be used for comparisons.
Modifier and Type  Field and Description 

static Duration 
ZERO
Constant for a duration of zero.

Modifier and Type  Method and Description 

Duration 
abs()
Returns a copy of this duration with a positive length.

Temporal 
addTo(Temporal temporal)
Adds this duration to the specified temporal object.

static Duration 
between(Temporal startInclusive,
Temporal endExclusive)
Obtains a
Duration representing the duration between two temporal objects. 
int 
compareTo(Duration otherDuration)
Compares this duration to the specified
Duration . 
Duration 
dividedBy(long divisor)
Returns a copy of this duration divided by the specified value.

boolean 
equals(Object otherDuration)
Checks if this duration is equal to the specified
Duration . 
static Duration 
from(TemporalAmount amount)
Obtains an instance of
Duration from a temporal amount. 
long 
get(TemporalUnit unit)
Gets the value of the requested unit.

int 
getNano()
Gets the number of nanoseconds within the second in this duration.

long 
getSeconds()
Gets the number of seconds in this duration.

List<TemporalUnit> 
getUnits()
Gets the set of units supported by this duration.

int 
hashCode()
A hash code for this duration.

boolean 
isNegative()
Checks if this duration is negative, excluding zero.

boolean 
isZero()
Checks if this duration is zero length.

Duration 
minus(Duration duration)
Returns a copy of this duration with the specified duration subtracted.

Duration 
minus(long amountToSubtract,
TemporalUnit unit)
Returns a copy of this duration with the specified duration subtracted.

Duration 
minusDays(long daysToSubtract)
Returns a copy of this duration with the specified duration in standard 24 hour days subtracted.

Duration 
minusHours(long hoursToSubtract)
Returns a copy of this duration with the specified duration in hours subtracted.

Duration 
minusMillis(long millisToSubtract)
Returns a copy of this duration with the specified duration in milliseconds subtracted.

Duration 
minusMinutes(long minutesToSubtract)
Returns a copy of this duration with the specified duration in minutes subtracted.

Duration 
minusNanos(long nanosToSubtract)
Returns a copy of this duration with the specified duration in nanoseconds subtracted.

Duration 
minusSeconds(long secondsToSubtract)
Returns a copy of this duration with the specified duration in seconds subtracted.

Duration 
multipliedBy(long multiplicand)
Returns a copy of this duration multiplied by the scalar.

Duration 
negated()
Returns a copy of this duration with the length negated.

static Duration 
of(long amount,
TemporalUnit unit)
Obtains a
Duration representing an amount in the specified unit. 
static Duration 
ofDays(long days)
Obtains a
Duration representing a number of standard 24 hour days. 
static Duration 
ofHours(long hours)
Obtains a
Duration representing a number of standard hours. 
static Duration 
ofMillis(long millis)
Obtains a
Duration representing a number of milliseconds. 
static Duration 
ofMinutes(long minutes)
Obtains a
Duration representing a number of standard minutes. 
static Duration 
ofNanos(long nanos)
Obtains a
Duration representing a number of nanoseconds. 
static Duration 
ofSeconds(long seconds)
Obtains a
Duration representing a number of seconds. 
static Duration 
ofSeconds(long seconds,
long nanoAdjustment)
Obtains a
Duration representing a number of seconds and an
adjustment in nanoseconds. 
static Duration 
parse(CharSequence text)
Obtains a
Duration from a text string such as PnDTnHnMn.nS . 
Duration 
plus(Duration duration)
Returns a copy of this duration with the specified duration added.

Duration 
plus(long amountToAdd,
TemporalUnit unit)
Returns a copy of this duration with the specified duration added.

Duration 
plusDays(long daysToAdd)
Returns a copy of this duration with the specified duration in standard 24 hour days added.

Duration 
plusHours(long hoursToAdd)
Returns a copy of this duration with the specified duration in hours added.

Duration 
plusMillis(long millisToAdd)
Returns a copy of this duration with the specified duration in milliseconds added.

Duration 
plusMinutes(long minutesToAdd)
Returns a copy of this duration with the specified duration in minutes added.

Duration 
plusNanos(long nanosToAdd)
Returns a copy of this duration with the specified duration in nanoseconds added.

Duration 
plusSeconds(long secondsToAdd)
Returns a copy of this duration with the specified duration in seconds added.

Temporal 
subtractFrom(Temporal temporal)
Subtracts this duration from the specified temporal object.

long 
toDays()
Gets the number of days in this duration.

long 
toHours()
Gets the number of hours in this duration.

long 
toMillis()
Converts this duration to the total length in milliseconds.

long 
toMinutes()
Gets the number of minutes in this duration.

long 
toNanos()
Converts this duration to the total length in nanoseconds expressed as a
long . 
String 
toString()
A string representation of this duration using ISO8601 seconds
based representation, such as
PT8H6M12.345S . 
Duration 
withNanos(int nanoOfSecond)
Returns a copy of this duration with the specified nanoofsecond.

Duration 
withSeconds(long seconds)
Returns a copy of this duration with the specified amount of seconds.

public static final Duration ZERO
public static Duration ofDays(long days)
Duration
representing a number of standard 24 hour days.
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.
days
 the number of days, positive or negativeDuration
, not nullArithmeticException
 if the input days exceeds the capacity of Duration
public static Duration ofHours(long hours)
Duration
representing a number of standard hours.
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.
hours
 the number of hours, positive or negativeDuration
, not nullArithmeticException
 if the input hours exceeds the capacity of Duration
public static Duration ofMinutes(long minutes)
Duration
representing a number of standard minutes.
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.
minutes
 the number of minutes, positive or negativeDuration
, not nullArithmeticException
 if the input minutes exceeds the capacity of Duration
public static Duration ofSeconds(long seconds)
Duration
representing a number of seconds.
The nanosecond in second field is set to zero.
seconds
 the number of seconds, positive or negativeDuration
, not nullpublic static Duration ofSeconds(long seconds, long nanoAdjustment)
Duration
representing a number of seconds and an
adjustment in nanoseconds.
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 the exactly the same duration:
Duration.ofSeconds(3, 1); Duration.ofSeconds(4, 999_999_999); Duration.ofSeconds(2, 1000_000_001);
seconds
 the number of seconds, positive or negativenanoAdjustment
 the nanosecond adjustment to the number of seconds, positive or negativeDuration
, not nullArithmeticException
 if the adjustment causes the seconds to exceed the capacity of Duration
public static Duration ofMillis(long millis)
Duration
representing a number of milliseconds.
The seconds and nanoseconds are extracted from the specified milliseconds.
millis
 the number of milliseconds, positive or negativeDuration
, not nullpublic static Duration ofNanos(long nanos)
Duration
representing a number of nanoseconds.
The seconds and nanoseconds are extracted from the specified nanoseconds.
nanos
 the number of nanoseconds, positive or negativeDuration
, not nullpublic static Duration of(long amount, TemporalUnit unit)
Duration
representing an amount in the specified unit.
The parameters represent the two parts of a phrase like '6 Hours'. For example:
Duration.of(3, SECONDS); Duration.of(465, HOURS);Only a subset of units are accepted by this method. The unit must either have an exact duration or be
ChronoUnit.DAYS
which is treated as 24 hours. Other units throw an exception.amount
 the amount of the duration, measured in terms of the unit, positive or negativeunit
 the unit that the duration is measured in, must have an exact duration, not nullDuration
, not nullDateTimeException
 if the period unit has an estimated durationArithmeticException
 if a numeric overflow occurspublic static Duration from(TemporalAmount amount)
Duration
from a temporal amount.
This obtains a duration based on the specified amount.
A TemporalAmount
represents an amount of time, which may be
datebased or timebased, which this factory extracts to a duration.
The conversion loops around the set of units from the amount and uses
the duration of the unit to
calculate the total Duration
.
Only a subset of units are accepted by this method. The unit must either
have an exact duration
or be ChronoUnit.DAYS
which is treated as 24 hours.
If any other units are found then an exception is thrown.
amount
 the temporal amount to convert, not nullDateTimeException
 if unable to convert to a Duration
ArithmeticException
 if numeric overflow occurspublic static Duration parse(CharSequence text)
Duration
from a text string such as PnDTnHnMn.nS
.
This will parse a textual representation of a duration, including the
string produced by toString()
. The formats accepted are based
on the ISO8601 duration format PnDTnHnMn.nS
with days
considered to be exactly 24 hours.
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 an long
.
The number of seconds must parse to an 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.
The leading plus/minus sign, and negative values for other units are not part of the ISO8601 standard.
Examples:
"PT20.345S"  parses as "20.345 seconds" "PT15M"  parses as "15 minutes" (where a minute is 60 seconds) "PT10H"  parses as "10 hours" (where an hour is 3600 seconds) "P2D"  parses as "2 days" (where a day is 24 hours or 86400 seconds) "P2DT3H4M"  parses as "2 days, 3 hours and 4 minutes" "P6H3M"  parses as "6 hours and +3 minutes" "P6H3M"  parses as "6 hours and 3 minutes" "P6H+3M"  parses as "+6 hours and 3 minutes"
text
 the text to parse, not nullDateTimeParseException
 if the text cannot be parsed to a durationpublic static Duration between(Temporal startInclusive, Temporal endExclusive)
Duration
representing the duration between two temporal objects.
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 LocalTime
then the second argument is converted to a LocalTime
.
The specified temporal objects must support the SECONDS
unit.
For full accuracy, either the NANOS
unit or the
NANO_OF_SECOND
field should be supported.
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 abs()
on the result.
startInclusive
 the start instant, inclusive, not nullendExclusive
 the end instant, exclusive, not nullDuration
, not nullDateTimeException
 if the seconds between the temporals cannot be obtainedArithmeticException
 if the calculation exceeds the capacity of Duration
public long get(TemporalUnit unit)
This returns a value for each of the two supported units,
SECONDS
and NANOS
.
All other units throw an exception.
get
in interface TemporalAmount
unit
 the TemporalUnit
for which to return the valueDateTimeException
 if the unit is not supportedUnsupportedTemporalTypeException
 if the unit is not supportedpublic List<TemporalUnit> getUnits()
The supported units are SECONDS
,
and NANOS
.
They are returned in the order seconds, nanos.
This set can be used in conjunction with get(TemporalUnit)
to access the entire state of the duration.
getUnits
in interface TemporalAmount
public boolean isZero()
A Duration
represents a directed distance between two points on
the timeline and can therefore be positive, zero or negative.
This method checks whether the length is zero.
public boolean isNegative()
A Duration
represents a directed distance between two points on
the timeline and can therefore be positive, zero or negative.
This method checks whether the length is less than zero.
public long getSeconds()
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 getNano()
.
A Duration
represents a directed distance between two points on the timeline.
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.
public int getNano()
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 getSeconds()
.
A Duration
represents a directed distance between two points on the timeline.
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.
public Duration withSeconds(long seconds)
This returns a duration with the specified seconds, retaining the nanoofsecond part of this duration.
This instance is immutable and unaffected by this method call.
seconds
 the seconds to represent, may be negativeDuration
based on this period with the requested seconds, not nullpublic Duration withNanos(int nanoOfSecond)
This returns a duration with the specified nanoofsecond, retaining the seconds part of this duration.
This instance is immutable and unaffected by this method call.
nanoOfSecond
 the nanoofsecond to represent, from 0 to 999,999,999Duration
based on this period with the requested nanoofsecond, not nullDateTimeException
 if the nanoofsecond is invalidpublic Duration plus(Duration duration)
This instance is immutable and unaffected by this method call.
duration
 the duration to add, positive or negative, not nullDuration
based on this duration with the specified duration added, not nullArithmeticException
 if numeric overflow occurspublic Duration plus(long amountToAdd, TemporalUnit unit)
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 exact duration or
be ChronoUnit.DAYS
which is treated as 24 hours. Other units throw an exception.
This instance is immutable and unaffected by this method call.
amountToAdd
 the amount to add, measured in terms of the unit, positive or negativeunit
 the unit that the amount is measured in, must have an exact duration, not nullDuration
based on this duration with the specified duration added, not nullUnsupportedTemporalTypeException
 if the unit is not supportedArithmeticException
 if numeric overflow occurspublic Duration plusDays(long daysToAdd)
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.
This instance is immutable and unaffected by this method call.
daysToAdd
 the days to add, positive or negativeDuration
based on this duration with the specified days added, not nullArithmeticException
 if numeric overflow occurspublic Duration plusHours(long hoursToAdd)
This instance is immutable and unaffected by this method call.
hoursToAdd
 the hours to add, positive or negativeDuration
based on this duration with the specified hours added, not nullArithmeticException
 if numeric overflow occurspublic Duration plusMinutes(long minutesToAdd)
This instance is immutable and unaffected by this method call.
minutesToAdd
 the minutes to add, positive or negativeDuration
based on this duration with the specified minutes added, not nullArithmeticException
 if numeric overflow occurspublic Duration plusSeconds(long secondsToAdd)
This instance is immutable and unaffected by this method call.
secondsToAdd
 the seconds to add, positive or negativeDuration
based on this duration with the specified seconds added, not nullArithmeticException
 if numeric overflow occurspublic Duration plusMillis(long millisToAdd)
This instance is immutable and unaffected by this method call.
millisToAdd
 the milliseconds to add, positive or negativeDuration
based on this duration with the specified milliseconds added, not nullArithmeticException
 if numeric overflow occurspublic Duration plusNanos(long nanosToAdd)
This instance is immutable and unaffected by this method call.
nanosToAdd
 the nanoseconds to add, positive or negativeDuration
based on this duration with the specified nanoseconds added, not nullArithmeticException
 if numeric overflow occurspublic Duration minus(Duration duration)
This instance is immutable and unaffected by this method call.
duration
 the duration to subtract, positive or negative, not nullDuration
based on this duration with the specified duration subtracted, not nullArithmeticException
 if numeric overflow occurspublic Duration minus(long amountToSubtract, TemporalUnit unit)
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 exact duration or
be ChronoUnit.DAYS
which is treated as 24 hours. Other units throw an exception.
This instance is immutable and unaffected by this method call.
amountToSubtract
 the amount to subtract, measured in terms of the unit, positive or negativeunit
 the unit that the amount is measured in, must have an exact duration, not nullDuration
based on this duration with the specified duration subtracted, not nullArithmeticException
 if numeric overflow occurspublic Duration minusDays(long daysToSubtract)
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.
This instance is immutable and unaffected by this method call.
daysToSubtract
 the days to subtract, positive or negativeDuration
based on this duration with the specified days subtracted, not nullArithmeticException
 if numeric overflow occurspublic Duration minusHours(long hoursToSubtract)
The number of hours is multiplied by 3600 to obtain the number of seconds to subtract.
This instance is immutable and unaffected by this method call.
hoursToSubtract
 the hours to subtract, positive or negativeDuration
based on this duration with the specified hours subtracted, not nullArithmeticException
 if numeric overflow occurspublic Duration minusMinutes(long minutesToSubtract)
The number of hours is multiplied by 60 to obtain the number of seconds to subtract.
This instance is immutable and unaffected by this method call.
minutesToSubtract
 the minutes to subtract, positive or negativeDuration
based on this duration with the specified minutes subtracted, not nullArithmeticException
 if numeric overflow occurspublic Duration minusSeconds(long secondsToSubtract)
This instance is immutable and unaffected by this method call.
secondsToSubtract
 the seconds to subtract, positive or negativeDuration
based on this duration with the specified seconds subtracted, not nullArithmeticException
 if numeric overflow occurspublic Duration minusMillis(long millisToSubtract)
This instance is immutable and unaffected by this method call.
millisToSubtract
 the milliseconds to subtract, positive or negativeDuration
based on this duration with the specified milliseconds subtracted, not nullArithmeticException
 if numeric overflow occurspublic Duration minusNanos(long nanosToSubtract)
This instance is immutable and unaffected by this method call.
nanosToSubtract
 the nanoseconds to subtract, positive or negativeDuration
based on this duration with the specified nanoseconds subtracted, not nullArithmeticException
 if numeric overflow occurspublic Duration multipliedBy(long multiplicand)
This instance is immutable and unaffected by this method call.
multiplicand
 the value to multiply the duration by, positive or negativeDuration
based on this duration multiplied by the specified scalar, not nullArithmeticException
 if numeric overflow occurspublic Duration dividedBy(long divisor)
This instance is immutable and unaffected by this method call.
divisor
 the value to divide the duration by, positive or negative, not zeroDuration
based on this duration divided by the specified divisor, not nullArithmeticException
 if the divisor is zero or if numeric overflow occurspublic Duration negated()
This method swaps the sign of the total length of this duration.
For example, PT1.3S
will be returned as PT1.3S
.
This instance is immutable and unaffected by this method call.
Duration
based on this duration with the amount negated, not nullArithmeticException
 if numeric overflow occurspublic Duration abs()
This method returns a positive duration by effectively removing the sign from any negative total length.
For example, PT1.3S
will be returned as PT1.3S
.
This instance is immutable and unaffected by this method call.
Duration
based on this duration with an absolute length, not nullArithmeticException
 if numeric overflow occurspublic Temporal addTo(Temporal temporal)
This returns a temporal object of the same observable type as the input with this duration added.
In most cases, it is clearer to reverse the calling pattern by using
Temporal.plus(TemporalAmount)
.
// these two lines are equivalent, but the second approach is recommended dateTime = thisDuration.addTo(dateTime); dateTime = dateTime.plus(thisDuration);
The calculation will add the seconds, then nanos. Only nonzero amounts will be added.
This instance is immutable and unaffected by this method call.
addTo
in interface TemporalAmount
temporal
 the temporal object to adjust, not nullDateTimeException
 if unable to addArithmeticException
 if numeric overflow occurspublic Temporal subtractFrom(Temporal temporal)
This returns a temporal object of the same observable type as the input with this duration subtracted.
In most cases, it is clearer to reverse the calling pattern by using
Temporal.minus(TemporalAmount)
.
// these two lines are equivalent, but the second approach is recommended dateTime = thisDuration.subtractFrom(dateTime); dateTime = dateTime.minus(thisDuration);
The calculation will subtract the seconds, then nanos. Only nonzero amounts will be added.
This instance is immutable and unaffected by this method call.
subtractFrom
in interface TemporalAmount
temporal
 the temporal object to adjust, not nullDateTimeException
 if unable to subtractArithmeticException
 if numeric overflow occurspublic long toDays()
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.
This instance is immutable and unaffected by this method call.
public long toHours()
This returns the total number of hours in the duration by dividing the number of seconds by 3600.
This instance is immutable and unaffected by this method call.
public long toMinutes()
This returns the total number of minutes in the duration by dividing the number of seconds by 60.
This instance is immutable and unaffected by this method call.
public long toMillis()
If this duration is too large to fit in a long
milliseconds, then an
exception is thrown.
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.
ArithmeticException
 if numeric overflow occurspublic long toNanos()
long
.
If this duration is too large to fit in a long
nanoseconds, then an
exception is thrown.
ArithmeticException
 if numeric overflow occurspublic int compareTo(Duration otherDuration)
Duration
.
The comparison is based on the total length of the durations.
It is "consistent with equals", as defined by Comparable
.
compareTo
in interface Comparable<Duration>
otherDuration
 the other duration to compare to, not nullpublic boolean equals(Object otherDuration)
Duration
.
The comparison is based on the total length of the durations.
equals
in class Object
otherDuration
 the other duration, null returns falseObject.hashCode()
,
HashMap
public int hashCode()
hashCode
in class Object
Object.equals(java.lang.Object)
,
System.identityHashCode(java.lang.Object)
public String toString()
PT8H6M12.345S
.
The format of the returned string will be PTnHnMnS
, where n is
the relevant hours, minutes or seconds part of the duration.
Any fractional seconds are placed after a decimal point i the seconds section.
If a section has a zero value, it is omitted.
The hours, minutes and seconds will all have the same sign.
Examples:
"20.345 seconds"  "PT20.345S "15 minutes" (15 * 60 seconds)  "PT15M" "10 hours" (10 * 3600 seconds)  "PT10H" "2 days" (2 * 86400 seconds)  "PT48H"Note that multiples of 24 hours are not output as days to avoid confusion with
Period
. Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developertargeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2021, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.