| |||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
DatatypeFactory df = …;
Duration warrantyDuration = df.newDuration("P1Y");
Based on 6 examples
public abstract class Duration extends Object
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 {@link #compare(Duration duration)} method implements this relationship.
See the {@link #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 {@link Calendar}
even though {@link Duration} can hold very large or very small values,
some of the methods may not work correctly on such Duration
s.
The impacted methods document their dependency on {@link Calendar}.
Constructor Summary | |
---|---|
Duration() Default no-arg constructor. |
Method Summary | |
---|---|
abstract Duration |
Computes a new duration whose value is this+rhs .
|
abstract void |
Adds this duration to a java.util.Calendar object. |
void |
Adds this duration to a java.util.Date object. |
abstract int |
Partial order relation comparison with this Duration instance.
|
boolean |
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. |
abstract Number |
getField(DatatypeConstants.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 |
Obtains the value of the MINUTES field as an integer value, or 0 if not present. |
int |
Obtains the value of the MONTHS field as an integer value, or 0 if not present. |
int |
Obtains the value of the SECONDS field as an integer value, or 0 if not present. |
abstract int |
getSign() Returns the sign of this duration in -1,0, or 1. |
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. |
QName |
Return the name of the XML Schema date/time type that this instance maps to. |
int |
getYears() Get the years value of this Duration as an int or 0 if not present.
|
abstract int |
hashCode() Returns a hash code consistent with the definition of the equals method. |
boolean |
isLongerThan(Duration duration) Checks if this duration object is strictly longer than another Duration object.
|
abstract boolean |
isSet(DatatypeConstants.Field field) Checks if a field is set. |
boolean |
isShorterThan(Duration duration) Checks if this duration object is strictly shorter than another Duration object.
|
abstract 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.
|
abstract Duration |
negate() Returns a new Duration object whose
value is -this .
|
abstract Duration |
normalizeWith(Calendar startTimeInstant) Converts the years and months fields into the days field by using a specific time instant as the reference point. |
Duration |
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, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
Constructor Detail |
---|
public Duration()
Note: Always use the {@link DatatypeFactory} to
construct an instance of Duration
.
The constructor on this class cannot be guaranteed to
produce an object with a consistent state and may be
removed in the future.
Method Detail |
---|
public abstract 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 {@link IllegalStateException}.
Formally, the computation is defined as follows.
Firstly, we can assume that two Duration
s 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 Duration
s 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 Duration
s 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
public abstract void addTo(Calendar calendar)
Calls {@link java.util.Calendar#add(int,int)} in the order of YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS, and MILLISECONDS if those fields are present. Because the {@link 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 {@link 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 {@link 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 {@link Calendar}.
{@link 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.public void addTo(Date date)
The given date is first converted into a {@link java.util.GregorianCalendar}, then the duration is added exactly like the {@link #addTo(Calendar)} method.
The updated time instant is then converted back into a {@link Date} object and used to update the given {@link 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.public abstract int compare(Duration duration)
Partial order relation comparison with this Duration
instance.
Comparison result must be in accordance with W3C XML Schema 1.0 Part 2, Section 3.2.7.6.2, Order relation on duration.
Return:
Duration
is shorter than duration
parameterDuration
is equal to duration
parameterDuration
is longer than duration
parameter
duration
- to comparethis
Duration
and duration
parameter as
{@link DatatypeConstants#LESSER}, {@link DatatypeConstants#EQUAL}, {@link DatatypeConstants#GREATER}
or {@link DatatypeConstants#INDETERMINATE}.public boolean equals(Object duration)
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 Duration
s 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 Object
duration
- The object to compare this Duration
against.true
if this duration is the same length as
duration
.
false
if duration
is null
,
is not a
Duration
object,
or its length is different from this duration.public int getDays()
Duration
.public abstract Number getField(DatatypeConstants.Field field)
field
- one of the six Field constants (YEARS,MONTHS,DAYS,HOURS,
MINUTES, or SECONDS.)public int getHours()
Duration
.public int getMinutes()
Duration
.public int getMonths()
Duration
.public int getSeconds()
public abstract int getSign()
public 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 {@link #addTo(Calendar)} method,
which may work incorrectly with Duration
objects with
very large values in its fields. See the {@link #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
public 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 {@link #addTo(Date)} method,
which may work incorrectly with Duration
objects with
very large values in its fields. See the {@link #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
public QName getXMLSchemaType()
Return the name of the XML Schema date/time type that this instance
maps to. Type is computed based on fields that are set,
i.e. {@link #isSet(DatatypeConstants.Field field)} == true
.
Required fields for XML Schema 1.0 Date/Time Datatypes. (timezone is optional for all date/time datatypes) |
||||||
---|---|---|---|---|---|---|
Datatype | year | month | day | hour | minute | second |
{@link DatatypeConstants#DURATION} | X | X | X | X | X | X |
{@link DatatypeConstants#DURATION_DAYTIME} | X | X | X | X | ||
{@link DatatypeConstants#DURATION_YEARMONTH} | X | X |
public int getYears()
Get the years value of this Duration
as an int
or 0
if not present.
getYears()
is a convenience method for
{@link #getField(DatatypeConstants.Field field) getField(DatatypeConstants.YEARS)}.
As the return value is an int
, an incorrect value will be returned for Duration
s
with years that go beyond the range of an int
.
Use {@link #getField(DatatypeConstants.Field field) getField(DatatypeConstants.YEARS)} to avoid possible loss of precision.
int
, else return 0
.public abstract int hashCode()
hashCode
in class Object
public boolean isLongerThan(Duration duration)
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).
duration
- Duration
to test this Duration
against.public abstract boolean isSet(DatatypeConstants.Field field)
field
- one of the six Field constants (YEARS,MONTHS,DAYS,HOURS,
MINUTES, or SECONDS.)public boolean isShorterThan(Duration duration)
Checks if this duration object is strictly shorter than
another Duration
object.
duration
- Duration
to test this Duration
against.true
if duration
parameter is shorter than this Duration
,
else false
.public abstract 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 {@link 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 {@link IllegalStateException} to be thrown. For example if you multiple one month by 0.5.
To avoid {@link IllegalStateException}, use the {@link #normalizeWith(Calendar)} method to remove the years and months fields.
factor
- to multiply byDuration
objectpublic 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 factor
times longer than this Duration
.public abstract 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 abstract 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:
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.public 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 {@link IllegalStateException}.
Formally the computation is defined as follows.
First, we can assume that two Duration
s 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 {@link IllegalStateException}.
rhs
- Duration
to subtract from this Duration
.Duration
created from subtracting rhs
from this Duration
.public String toString()
Returns a String
representation of this Duration
Object
.
The result is formatted according to the XML Schema 1.0 spec and can be always parsed back later into the
equivalent Duration
Object
by {@link DatatypeFactory#newDuration(String lexicalRepresentation)}.
Formally, the following holds for any Duration
Object
x:
new Duration(x.toString()).equals(x)
toString
in class Object
null
valid String
representation of this Duration
.
| |||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |