java.lang.Objectjavax.xml.datatype.Duration
Immutable representation of a time span as defined in the W3C XML Schema 1.0 specification.
A Duration object represents a period of Gregorian time, which consists of six fields (years, months, days, hours, minutes, and seconds) plus a sign (+/-) field.
The first five fields have non-negative (>=0) integers or null (which represents that the field is not set), and the seconds field has a non-negative decimal or null. A negative sign indicates a negative duration.
This class provides a number of methods that make it easy to use for the duration datatype of XML Schema 1.0 with the errata.
Duration objects only have partial order, where two values A and B maybe either:
For example, 30 days cannot be meaningfully compared to one month.
The compare(Duration, Duration) method implements this
relationship.
See the isLongerThan(Duration) method for details about
the order relationship among Duration objects.
This class provides a set of basic arithmetic operations, such as addition, subtraction and multiplication. Because durations don't have total order, an operation could fail for some combinations of operations. For example, you cannot subtract 15 days from 1 month. See the javadoc of those methods for detailed conditions where this could happen.
Also, division of a duration by a number is not provided because
the Duration class can only deal with finite precision
decimal numbers. For example, one cannot represent 1 sec divided by 3.
However, you could substitute a division by 3 with multiplying by numbers such as 0.3 or 0.333.
Because some operations of Duration rely on Calendar
even though Duration can hold very large or very small values,
some of the methods may not work correctly on such Durations.
The impacted methods document their dependency on Calendar.
XMLGregorianCalendar.add(Duration),
Serialized Form| Nested Class Summary | |
|---|---|
static class |
Duration.Field
Type-safe enum class that represents six fields of the Duration class. |
| Field Summary | |
|---|---|
static Duration.Field |
DAYS
A constant that represents the days field. |
static int |
EQUAL
Partial order relation comparison result. |
static int |
GREATER
Partial order relation comparison result. |
static Duration.Field |
HOURS
A constant that represents the hours field. |
static int |
INDETERMINATE
Partial order relation comparison result. |
static int |
LESSER
Partial order relation comparison result. |
static Duration.Field |
MINUTES
A constant that represents the minutes field. |
static Duration.Field |
MONTHS
A constant that represents the months field. |
static Duration.Field |
SECONDS
A constant that represents the seconds field. |
static Duration.Field |
YEARS
A constant that represents the years field. |
| Constructor Summary | |
|---|---|
Duration(boolean isPositive,
BigInteger years,
BigInteger months,
BigInteger days,
BigInteger hours,
BigInteger minutes,
BigDecimal seconds)
Constructs a new Duration object by specifying each field individually. |
|
Duration(boolean isPositive,
int years,
int months,
int days,
int hours,
int minutes,
int seconds)
Constructs a new Duration object by specifying each field individually. |
|
Duration(long durationInMilliSeconds)
Constructs a new Duration object by specifying the duration in milliseconds. |
|
Duration(String lexicalRepresentation)
Constructs a new Duration object by parsing its string representation "PnYnMnDTnHnMnS" as defined in XML Schema 1.0 section 3.2.6.1. |
|
| Method Summary | |
|---|---|
Duration |
add(Duration rhs)
Computes a new duration whose value is this+rhs. |
void |
addTo(Calendar calendar)
Adds this duration to a Calendar object. |
void |
addTo(Date date)
Adds this duration to a Date object. |
static int |
compare(Duration lhs,
Duration rhs)
Partial order relation comparison between two Duration instances. |
boolean |
equals(Object rhs)
Checks if this duration object has the same duration as another Duration object. |
int |
getDays()
Obtains the value of the DAYS field as an integer value, or 0 if not present. |
Number |
getField(Duration.Field field)
Gets the value of a field. |
int |
getHours()
Obtains the value of the HOURS field as an integer value, or 0 if not present. |
int |
getMinutes()
Obtains the value of the MINUTES field as an integer value, or 0 if not present. |
int |
getMonths()
Obtains the value of the MONTHS field as an integer value, or 0 if not present. |
int |
getSeconds()
Obtains the value of the SECONDS field as an integer value, or 0 if not present. |
long |
getTimeInMillis(Calendar startInstant)
Returns the length of the duration in milli-seconds. |
long |
getTimeInMillis(Date startInstant)
Returns the length of the duration in milli-seconds. |
int |
getYears()
Obtains the value of the YEARS field as an integer value, or 0 if not present. |
int |
hashCode()
Returns a hash code consistent with the definition of the equals method. |
boolean |
isLongerThan(Duration rhs)
Checks if this duration object is strictly longer than another Duration object. |
boolean |
isSet(Duration.Field field)
Checks if a field is set. |
boolean |
isShorterThan(Duration rhs)
Checks if this duration object is strictly shorter than another Duration object. |
Duration |
multiply(BigDecimal factor)
Computes a new duration whose value is factor times
longer than the value of this duration. |
Duration |
multiply(int factor)
Computes a new duration whose value is factor times
longer than the value of this duration. |
Duration |
negate()
Returns a new Duration object whose
value is -this. |
Duration |
normalizeWith(Calendar startTimeInstant)
Converts the years and months fields into the days field by using a specific time instant as the reference point. |
int |
signum()
Returns the sign of this duration in -1,0, or 1. |
Duration |
subtract(Duration rhs)
Computes a new duration whose value is this-rhs. |
String |
toString()
Returns a string representation of this duration object. |
| Methods inherited from class java.lang.Object |
|---|
clone, finalize, getClass, notify, notifyAll, wait, wait, wait |
| Field Detail |
|---|
public static final int LESSER
compare(Duration, Duration),
Constant Field Valuespublic static final int EQUAL
compare(Duration, Duration),
Constant Field Valuespublic static final int GREATER
compare(Duration, Duration),
Constant Field Valuespublic static final int INDETERMINATE
compare(Duration, Duration),
Constant Field Valuespublic static final Duration.Field YEARS
A constant that represents the years field.
public static final Duration.Field MONTHS
A constant that represents the months field.
public static final Duration.Field DAYS
A constant that represents the days field.
public static final Duration.Field HOURS
A constant that represents the hours field.
public static final Duration.Field MINUTES
A constant that represents the minutes field.
public static final Duration.Field SECONDS
A constant that represents the seconds field.
| Constructor Detail |
|---|
public Duration(boolean isPositive,
BigInteger years,
BigInteger months,
BigInteger days,
BigInteger hours,
BigInteger minutes,
BigDecimal seconds)
Constructs a new Duration object by specifying each field individually.
All the parameters are optional as long as at least one field is present. If specified, parameters have to be zero or positive.
isPositive - Set to false to create a negative duration. When the length
of the duration is zero, this parameter will be ignored.years - of this Durationmonths - of this Durationdays - of this Durationhours - of this Durationminutes - of this Durationseconds - of this Duration
IllegalArgumentException - If years, months, days, hours, minutes and
seconds parameters are all null. Or if any
of those parameters are negative.
public Duration(boolean isPositive,
int years,
int months,
int days,
int hours,
int minutes,
int seconds)
Constructs a new Duration object by specifying each field individually.
This method is functionally equivalent to
invoking another constructor by wrapping
all non-zero parameters into BigInteger and BigDecimal.
Zero value of int parameter is equivalent of null value of
the corresponding field.
Duration(boolean, BigInteger, BigInteger, BigInteger, BigInteger,
BigInteger, BigDecimal)public Duration(long durationInMilliSeconds)
Constructs a new Duration object by specifying the duration in milliseconds.
The DAYS, HOURS, MINUTES and SECONDS fields are used to
represent the specifed duration in a reasonable way.
That is, the constructed object x satisfies
the following conditions:
durationInMilliSeconds - The length of the duration in milliseconds.
public Duration(String lexicalRepresentation)
throws IllegalArgumentException
The string representation may not have any leading and trailing whitespaces.
For example, this method parses strings like "P1D" (1 day), "-PT100S" (-100 sec.), "P1DT12H" (1 days and 12 hours).
The parsing is done field by field so that the following holds for any lexically correct string x:
new Duration(x).toString().equals(x)Returns a non-null valid duration object that holds the value indicated by the lexicalRepresentation parameter.
lexicalRepresentation - Lexical representation of a duration.
IllegalArgumentException - If the given string does not conform to the aforementioned
specification.
NullPointerException - If the given string is null.| Method Detail |
|---|
public static int compare(Duration lhs,
Duration rhs)
Partial order relation comparison between two Duration instances.
Comparison result must be in accordance with W3C XML Schema 1.0 Part 2, Section 3.2.7.6.2, Order relation on duration.
lhs - instance of Duration to comparerhs - instance of Duration to compare
lhs and rhs as LESSER, EQUAL, GREATER
or INDETERMINATE.
NullPointerException - if lhs or rhs
parameters are null.isShorterThan(Duration),
isLongerThan(Duration)public final boolean isLongerThan(Duration rhs)
Checks if this duration object is strictly longer than
another Duration object.
Duration X is "longer" than Y if and only if X>Y as defined in the section 3.2.6.2 of the XML Schema 1.0 specification.
For example, "P1D" (one day) > "PT12H" (12 hours) and "P2Y" (two years) > "P23M" (23 months).
rhs - A non-null valid Duration instance.
NullPointerException - if the rhs parameter is null.isShorterThan(Duration),
compare(Duration, Duration)public final boolean isShorterThan(Duration rhs)
Checks if this duration object is strictly shorter than
another Duration object.
This method is really just a convenience method of
rhs.isLongerThan(this).
rhs - Duration to test this Duration against.
true if Duration parameter is shorter than this Duration,
else false.
NullPointerException - if parameter is null.isLongerThan(Duration),
compare(Duration, Duration)public final boolean equals(Object rhs)
Checks if this duration object has the same duration
as another Duration object.
For example, "P1D" (1 day) is equal to "PT24H" (24 hours).
Duration X is equal to Y if and only if time instant t+X and t+Y are the same for all the test time instants specified in the section 3.2.6.2 of the XML Schema 1.0 specification.
Note that there are cases where two Durations are
"incomparable" to each other, like one month and 30 days.
For example,
!new Duration("P1M").isShorterThan(new Duration("P30D"))
!new Duration("P1M").isLongerThan(new Duration("P30D"))
!new Duration("P1M").equals(new Duration("P30D"))
equals in class Objectrhs - A non-null valid Duration object.
true if this duration is the same length as
rhs.
false if rhs is not a
Duration object
or its length is different from this duration.
NullPointerException - if parameter is null.compare(Duration, Duration)public int hashCode()
hashCode in class ObjectObject.hashCode()public String toString()
The result is formatter according to the XML Schema 1.0
spec and can be always parsed back later into the
equivalent duration object by
the Duration(String) constructor.
Formally, the following holds for any Duration
object x.
new Duration(x.toString()).equals(x)
toString in class Objectpublic boolean isSet(Duration.Field field)
field - one of the six Field constants (YEARS,MONTHS,DAYS,HOURS,
MINUTES, or SECONDS.)
NullPointerException - If the field parameter is null.public Number getField(Duration.Field field)
Number object.
In case of YEARS, MONTHS, DAYS, HOURS, and MINUTES, the returned
number will be a non-negative integer. In case of seconds,
the returned number may be a non-negative decimal value.
field - one of the six Field constants (YEARS,MONTHS,DAYS,HOURS,
MINUTES, or SECONDS.)
Number object that
represents its value. If it is not present, return null.
For YEARS, MONTHS, DAYS, HOURS, and MINUTES, this method
returns a BigInteger object. For SECONDS, this
method returns a BigDecimal.
NullPointerException - If the field parameter is null.public int getYears()
This method is a convenience method around the
getField(Duration.Field) method.
Note that since this method returns int, this
method will return an incorrect value for Durations
with the year field that goes beyond the range of int.
Use getField(YEARS) to avoid possible loss of precision.
Number.intValue()
method. If the YEARS field is not present, return 0.public int getMonths()
getYears() except
that this method works on the MONTHS field.
Duration.public int getDays()
getYears() except
that this method works on the DAYS field.
Duration.public int getHours()
getYears() except
that this method works on the HOURS field.
Duration.public int getMinutes()
getYears() except
that this method works on the MINUTES field.
Duration.public int getSeconds()
getYears() except
that this method works on the SECONDS field.
public final long getTimeInMillis(Calendar startInstant)
Returns the length of the duration in milli-seconds.
If the seconds field carries more digits than milli-second order,
those will be simply discarded (or in other words, rounded to zero.)
For example, for any Calendar value x,
new Duration("PT10.00099S").getTimeInMills(x) == 10000.new Duration("-PT10.00099S").getTimeInMills(x) == -10000.
Note that this method uses the addTo(Calendar) method,
which may work incorectly with Duration objects with
very large values in its fields. See the addTo(Calendar)
method for details.
startInstant - The length of a month/year varies. The startInstant is
used to disambiguate this variance. Specifically, this method
returns the difference between startInstant and
startInstant+duration
startInstant and
startInstant plus this Duration
NullPointerException - if startInstant parameter
is null.public final long getTimeInMillis(Date startInstant)
Returns the length of the duration in milli-seconds.
If the seconds field carries more digits than milli-second order,
those will be simply discarded (or in other words, rounded to zero.)
For example, for any Date value x,
new Duration("PT10.00099S").getTimeInMills(x) == 10000.new Duration("-PT10.00099S").getTimeInMills(x) == -10000.
Note that this method uses the addTo(Date) method,
which may work incorectly with Duration objects with
very large values in its fields. See the addTo(Date)
method for details.
startInstant - The length of a month/year varies. The startInstant is
used to disambiguate this variance. Specifically, this method
returns the difference between startInstant and
startInstant+duration.
startInstant and
startInstant plus this Duration
NullPointerException - If the startInstant parameter is null.getTimeInMillis(Calendar)public Duration normalizeWith(Calendar startTimeInstant)
Converts the years and months fields into the days field by using a specific time instant as the reference point.
For example, duration of one month normalizes to 31 days given the start time instance "July 8th 2003, 17:40:32".
Formally, the computation is done as follows:
Calendar object
by using the Calendar.add(int,int) method.
Note that since the Calendar class uses int to
hold the value of year and month, this method may produce
an unexpected result if this duration object holds
a very large value in the years or months fields.
startTimeInstant - Calendar reference point.
Duration of years and months of this Duration as days.
NullPointerException - If the startTimeInstant parameter is null.public Duration multiply(int factor)
Computes a new duration whose value is factor times
longer than the value of this duration.
This method is provided for the convenience. It is functionally equivalent to the following code:
multiply(new BigDecimal(String.valueOf(factor)))
factor - Factor times longer of new Duration to create.
Duration that is factortimes longer than this Duration.multiply(BigDecimal)public final Duration multiply(BigDecimal factor)
factor times
longer than the value of this duration.
For example,
"P1M" (1 month) * "12" = "P12M" (12 months) "PT1M" (1 min) * "0.3" = "PT18S" (18 seconds) "P1M" (1 month) * "1.5" = IllegalStateException
Since the Duration class is immutable, this method
doesn't change the value of this object. It simply computes
a new Duration object and returns it.
The operation will be performed field by field with the precision
of BigDecimal. Since all the fields except seconds are
restricted to hold integers,
any fraction produced by the computation will be
carried down toward the next lower unit. For example,
if you multiply "P1D" (1 day) with "0.5", then it will be 0.5 day,
which will be carried down to "PT12H" (12 hours).
When fractions of month cannot be meaningfully carried down
to days, or year to months, this will cause an
IllegalStateException to be thrown.
For example if you multiple one month by 0.5.
To avoid IllegalStateException, use
the normalizeWith(Calendar) method to remove the years
and months fields.
factor - to multiply by
Duration object
IllegalStateException - if operation produces fraction in
the months field.
NullPointerException - if the factor parameter is
null.public final Duration add(Duration rhs)
Computes a new duration whose value is this+rhs.
For example,
"1 day" + "-3 days" = "-2 days" "1 year" + "1 day" = "1 year and 1 day" "-(1 hour,50 minutes)" + "-20 minutes" = "-(1 hours,70 minutes)" "15 hours" + "-3 days" = "-(2 days,9 hours)" "1 year" + "-1 day" = IllegalStateException
Since there's no way to meaningfully subtract 1 day from 1 month,
there are cases where the operation fails in
IllegalStateException.
Formally, the computation is defined as follows.
Firstly, we can assume that two Durations to be added
are both positive without losing generality (i.e.,
(-X)+Y=Y-X, X+(-Y)=X-Y,
(-X)+(-Y)=-(X+Y))
Addition of two positive Durations are simply defined as
field by field addition where missing fields are treated as 0.
A field of the resulting Duration will be unset if and
only if respective fields of two input Durations are unset.
Note that lhs.add(rhs) will be always successful if
lhs.signum()*rhs.signum()!=-1 or both of them are
normalized.
rhs - Duration to add to this Duration
NullPointerException - If the rhs parameter is null.
IllegalStateException - If two durations cannot be meaningfully added. For
example, adding negative one day to one month causes
this exception.subtract(Duration)public final Duration subtract(Duration rhs)
Computes a new duration whose value is this-rhs.
For example:
"1 day" - "-3 days" = "4 days" "1 year" - "1 day" = IllegalStateException "-(1 hour,50 minutes)" - "-20 minutes" = "-(1hours,30 minutes)" "15 hours" - "-3 days" = "3 days and 15 hours" "1 year" - "-1 day" = "1 year and 1 day"
Since there's no way to meaningfully subtract 1 day from 1 month,
there are cases where the operation fails in IllegalStateException.
Formally the computation is defined as follows.
First, we can assume that two Durations are both positive
without losing generality. (i.e.,
(-X)-Y=-(X+Y), X-(-Y)=X+Y,
(-X)-(-Y)=-(X-Y))
Then two durations are subtracted field by field. If the sign of any non-zero field F is different from the sign of the most significant field, 1 (if F is negative) or -1 (otherwise) will be borrowed from the next bigger unit of F.
This process is repeated until all the non-zero fields have the same sign.
If a borrow occurs in the days field (in other words, if
the computation needs to borrow 1 or -1 month to compensate
days), then the computation fails by throwing an
IllegalStateException.
rhs - Duration to substract from this Duration.
Duration created from subtracting rhs from this Duration.
IllegalStateException - If two durations cannot be meaningfully subtracted. For
example, subtracting one day from one month causes
this exception.
NullPointerException - If the rhs parameter is null.add(Duration)public Duration negate()
Duration object whose
value is -this.
Since the Duration class is immutable, this method
doesn't change the value of this object. It simply computes
a new Duration object and returns it.
Duration object.public int signum()
public void addTo(Calendar calendar)
Calendar object.
Calls Calendar.add(int,int) in the
order of YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS, and MILLISECONDS
if those fields are present. Because the Calendar class
uses int to hold values, there are cases where this method
won't work correctly (for example if values of fields
exceed the range of int.)
Also, since this duration class is a Gregorian duration, this
method will not work correctly if the given Calendar
object is based on some other calendar systems.
Any fractional parts of this Duration object
beyond milliseconds will be simply ignored. For example, if
this duration is "P1.23456S", then 1 is added to SECONDS,
234 is added to MILLISECONDS, and the rest will be unused.
Note that because Calendar.add(int, int) is using
int, Duration with values beyond the
range of int in its fields
will cause overflow/underflow to the given Calendar.
XMLGregorianCalendar.add(Duration) provides the same
basic operation as this method while avoiding
the overflow/underflow issues.
calendar - A calendar object whose value will be modified.
NullPointerException - if the calendar parameter is null.public void addTo(Date date)
Date object.
The given date is first converted into
a GregorianCalendar, then the duration
is added exactly like the addTo(Calendar) method.
The updated time instant is then converted back into a
Date object and used to update the given Date object.
This somewhat redundant computation is necessary to unambiguously determine the duration of months and years.
date - A date object whose value will be modified.
NullPointerException - if the date parameter is null.