- java.lang.Object
- 
- javax.xml.datatype.Duration
 
- 
 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. Order relationshipDuration objects only have partial order, where two values A and B maybe either: - A<B (A is shorter than B)
- A>B (A is longer than B)
- A==B (A and B are of the same duration)
- A<>B (Comparison between A and B is indeterminate)
 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 amongDurationobjects.Operations over DurationThis 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 Durationclass 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. Range of allowed valuesBecause some operations of Durationrely onCalendareven thoughDurationcan hold very large or very small values, some of the methods may not work correctly on suchDurations. The impacted methods document their dependency onCalendar.- Since:
- 1.5
- See Also:
- XMLGregorianCalendar.add(Duration)
 
- 
- 
Constructor SummaryConstructors Constructor Description Duration()Default no-arg constructor.
 - 
Method SummaryAll Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description abstract Durationadd(Duration rhs)Computes a new duration whose value isthis+rhs.abstract voidaddTo(Calendar calendar)Adds this duration to aCalendarobject.voidaddTo(Date date)Adds this duration to aDateobject.abstract intcompare(Duration duration)Partial order relation comparison with thisDurationinstance.booleanequals(Object duration)Checks if this duration object has the same duration as anotherDurationobject.intgetDays()Obtains the value of the DAYS field as an integer value, or 0 if not present.abstract NumbergetField(DatatypeConstants.Field field)Gets the value of a field.intgetHours()Obtains the value of the HOURS field as an integer value, or 0 if not present.intgetMinutes()Obtains the value of the MINUTES field as an integer value, or 0 if not present.intgetMonths()Obtains the value of the MONTHS field as an integer value, or 0 if not present.intgetSeconds()Obtains the value of the SECONDS field as an integer value, or 0 if not present.abstract intgetSign()Returns the sign of this duration in -1,0, or 1.longgetTimeInMillis(Calendar startInstant)Returns the length of the duration in milli-seconds.longgetTimeInMillis(Date startInstant)Returns the length of the duration in milli-seconds.QNamegetXMLSchemaType()Return the name of the XML Schema date/time type that this instance maps to.intgetYears()Get the years value of thisDurationas anintor0if not present.abstract inthashCode()Returns a hash code consistent with the definition of the equals method.booleanisLongerThan(Duration duration)Checks if this duration object is strictly longer than anotherDurationobject.abstract booleanisSet(DatatypeConstants.Field field)Checks if a field is set.booleanisShorterThan(Duration duration)Checks if this duration object is strictly shorter than anotherDurationobject.Durationmultiply(int factor)Computes a new duration whose value isfactortimes longer than the value of this duration.abstract Durationmultiply(BigDecimal factor)Computes a new duration whose value isfactortimes longer than the value of this duration.abstract Durationnegate()Returns a newDurationobject whose value is-this.abstract DurationnormalizeWith(Calendar startTimeInstant)Converts the years and months fields into the days field by using a specific time instant as the reference point.Durationsubtract(Duration rhs)Computes a new duration whose value isthis-rhs.StringtoString()Returns aStringrepresentation of thisDuration Object.
 
- 
- 
- 
Constructor Detail- 
Durationpublic Duration() Default no-arg constructor.Note: Always use the DatatypeFactoryto construct an instance ofDuration. 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- 
getXMLSchemaTypepublic 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.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 DatatypeConstants.DURATIONX X X X X X DatatypeConstants.DURATION_DAYTIMEX X X X DatatypeConstants.DURATION_YEARMONTHX X - Returns:
- one of the following constants:
   DatatypeConstants.DURATION,DatatypeConstants.DURATION_DAYTIMEorDatatypeConstants.DURATION_YEARMONTH.
- Throws:
- IllegalStateException- If the combination of set fields does not match one of the XML Schema date/time datatypes.
 
 - 
getSignpublic abstract int getSign() Returns the sign of this duration in -1,0, or 1.- Returns:
- -1 if this duration is negative, 0 if the duration is zero, and 1 if the duration is positive.
 
 - 
getYearspublic int getYears() Get the years value of thisDurationas anintor0if not present.getYears()is a convenience method forgetField(DatatypeConstants.YEARS).As the return value is an int, an incorrect value will be returned forDurations with years that go beyond the range of anint. UsegetField(DatatypeConstants.YEARS)to avoid possible loss of precision.- Returns:
- If the years field is present, return its value as an int, else return0.
 
 - 
getMonthspublic int getMonths() Obtains the value of the MONTHS field as an integer value, or 0 if not present. This method works just likegetYears()except that this method works on the MONTHS field.- Returns:
- Months of this Duration.
 
 - 
getDayspublic int getDays() Obtains the value of the DAYS field as an integer value, or 0 if not present. This method works just likegetYears()except that this method works on the DAYS field.- Returns:
- Days of this Duration.
 
 - 
getHourspublic int getHours() Obtains the value of the HOURS field as an integer value, or 0 if not present. This method works just likegetYears()except that this method works on the HOURS field.- Returns:
- Hours of this Duration.
 
 - 
getMinutespublic int getMinutes() Obtains the value of the MINUTES field as an integer value, or 0 if not present. This method works just likegetYears()except that this method works on the MINUTES field.- Returns:
- Minutes of this Duration.
 
 - 
getSecondspublic int getSeconds() Obtains the value of the SECONDS field as an integer value, or 0 if not present. This method works just likegetYears()except that this method works on the SECONDS field.- Returns:
- seconds in the integer value. The fraction of seconds will be discarded (for example, if the actual value is 2.5, this method returns 2)
 
 - 
getTimeInMillispublic 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) == 10000new Duration("-PT10.00099S").getTimeInMills(x) == -10000Note that this method uses the addTo(Calendar)method, which may work incorrectly withDurationobjects with very large values in its fields. See theaddTo(Calendar)method for details.- Parameters:
- startInstant- The length of a month/year varies. The- startInstantis used to disambiguate this variance. Specifically, this method returns the difference between- startInstantand- startInstant+duration
- Returns:
- milliseconds between startInstantandstartInstantplus thisDuration
- Throws:
- NullPointerException- if- startInstantparameter is null.
 
 - 
getTimeInMillispublic 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 Datevaluex,new Duration("PT10.00099S").getTimeInMills(x) == 10000new Duration("-PT10.00099S").getTimeInMills(x) == -10000Note that this method uses the addTo(Date)method, which may work incorrectly withDurationobjects with very large values in its fields. See theaddTo(Date)method for details.- Parameters:
- startInstant- The length of a month/year varies. The- startInstantis used to disambiguate this variance. Specifically, this method returns the difference between- startInstantand- startInstant+duration.
- Returns:
- milliseconds between startInstantandstartInstantplus thisDuration
- Throws:
- NullPointerException- If the startInstant parameter is null.
- See Also:
- getTimeInMillis(Calendar)
 
 - 
getFieldpublic abstract Number getField(DatatypeConstants.Field field) Gets the value of a field. Fields of a duration object may contain arbitrary large value. Therefore this method is designed to return aNumberobject. 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.- Parameters:
- field- one of the six Field constants (YEARS,MONTHS,DAYS,HOURS, MINUTES, or SECONDS.)
- Returns:
- If the specified field is present, this method returns
      a non-null non-negative Numberobject that represents its value. If it is not present, return null. For YEARS, MONTHS, DAYS, HOURS, and MINUTES, this method returns aBigIntegerobject. For SECONDS, this method returns aBigDecimal.
- Throws:
- NullPointerException- If the- fieldis- null.
 
 - 
isSetpublic abstract boolean isSet(DatatypeConstants.Field field) Checks if a field is set. A field of a duration object may or may not be present. This method can be used to test if a field is present.- Parameters:
- field- one of the six Field constants (YEARS,MONTHS,DAYS,HOURS, MINUTES, or SECONDS.)
- Returns:
- true if the field is present. false if not.
- Throws:
- NullPointerException- If the field parameter is null.
 
 - 
addpublic abstract Duration add(Duration rhs) Computes a new duration whose value isthis+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 Durationwill be unset if and only if respective fields of two inputDurations are unset.Note that lhs.add(rhs)will be always successful iflhs.signum()*rhs.signum()!=-1or both of them are normalized.- Parameters:
- rhs-- Durationto add to this- Duration
- Returns:
- non-null valid Duration object.
- Throws:
- 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.
- See Also:
- subtract(Duration)
 
 - 
addTopublic abstract void addTo(Calendar calendar) Adds this duration to aCalendarobject.Calls Calendar.add(int,int)in the order of YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS, and MILLISECONDS if those fields are present. Because theCalendarclass 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 Calendarobject is based on some other calendar systems.Any fractional parts of this Durationobject 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 usingint,Durationwith values beyond the range ofintin its fields will cause overflow/underflow to the givenCalendar.XMLGregorianCalendar.add(Duration)provides the same basic operation as this method while avoiding the overflow/underflow issues.- Parameters:
- calendar- A calendar object whose value will be modified.
- Throws:
- NullPointerException- if the calendar parameter is null.
 
 - 
addTopublic void addTo(Date date) Adds this duration to aDateobject.The given date is first converted into a GregorianCalendar, then the duration is added exactly like theaddTo(Calendar)method.The updated time instant is then converted back into a Dateobject and used to update the givenDateobject.This somewhat redundant computation is necessary to unambiguously determine the duration of months and years. - Parameters:
- date- A date object whose value will be modified.
- Throws:
- NullPointerException- if the date parameter is null.
 
 - 
subtractpublic Duration subtract(Duration rhs) Computes a new duration whose value isthis-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 Fis different from the sign of the most significant field, 1 (ifFis negative) or -1 (otherwise) will be borrowed from the next bigger unit ofF.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.- Parameters:
- rhs-- Durationto subtract from this- Duration.
- Returns:
- New Durationcreated from subtractingrhsfrom thisDuration.
- Throws:
- 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.
- See Also:
- add(Duration)
 
 - 
multiplypublic Duration multiply(int factor) Computes a new duration whose value isfactortimes 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))) - Parameters:
- factor- Factor times longer of new- Durationto create.
- Returns:
- New Durationthat isfactortimes longer than thisDuration.
- See Also:
- multiply(BigDecimal)
 
 - 
multiplypublic abstract Duration multiply(BigDecimal factor) Computes a new duration whose value isfactortimes 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 Durationclass 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 anIllegalStateExceptionto be thrown. For example if you multiple one month by 0.5.To avoid IllegalStateException, use thenormalizeWith(Calendar)method to remove the years and months fields.- Parameters:
- factor- to multiply by
- Returns:
- returns a non-null valid Durationobject
- Throws:
- IllegalStateException- if operation produces fraction in the months field.
- NullPointerException- if the- factorparameter is- null.
 
 - 
negatepublic abstract Duration negate() Returns a newDurationobject whose value is-this.Since the Durationclass is immutable, this method doesn't change the value of this object. It simply computes a new Duration object and returns it.- Returns:
- always return a non-null valid Durationobject.
 
 - 
normalizeWithpublic 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: - the given Calendar object is cloned
- the years, months and days fields will be added to the Calendarobject by using theCalendar.add(int,int)method
- the difference between the two Calendars in computed in milliseconds and converted to days, if a remainder occurs due to Daylight Savings Time, it is discarded
- the computed days, along with the hours, minutes and seconds fields of this duration object is used to construct a new Duration object.
 Note that since the Calendar class uses intto 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.- Parameters:
- startTimeInstant-- Calendarreference point.
- Returns:
- Durationof years and months of this- Durationas days.
- Throws:
- NullPointerException- If the startTimeInstant parameter is null.
 
 - 
comparepublic abstract int compare(Duration duration) Partial order relation comparison with thisDurationinstance.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: - DatatypeConstants.LESSERif this- Durationis shorter than- durationparameter
- DatatypeConstants.EQUALif this- Durationis equal to- durationparameter
- DatatypeConstants.GREATERif this- Durationis longer than- durationparameter
- DatatypeConstants.INDETERMINATEif a conclusive partial order relation cannot be determined
 - Parameters:
- duration- to compare
- Returns:
- the relationship between this Durationanddurationparameter asDatatypeConstants.LESSER,DatatypeConstants.EQUAL,DatatypeConstants.GREATERorDatatypeConstants.INDETERMINATE.
- Throws:
- UnsupportedOperationException- If the underlying implementation cannot reasonably process the request, e.g. W3C XML Schema allows for arbitrarily large/small/precise values, the request may be beyond the implementations capability.
- NullPointerException- if- durationis- null.
- See Also:
- isShorterThan(Duration),- isLongerThan(Duration)
 
 - 
isLongerThanpublic boolean isLongerThan(Duration duration) Checks if this duration object is strictly longer than anotherDurationobject.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). - Parameters:
- duration-- Durationto test this- Durationagainst.
- Returns:
- true if the duration represented by this object is longer than the given duration. false otherwise.
- Throws:
- UnsupportedOperationException- If the underlying implementation cannot reasonably process the request, e.g. W3C XML Schema allows for arbitrarily large/small/precise values, the request may be beyond the implementations capability.
- NullPointerException- If- durationis null.
- See Also:
- isShorterThan(Duration),- compare(Duration duration)
 
 - 
isShorterThanpublic boolean isShorterThan(Duration duration) Checks if this duration object is strictly shorter than anotherDurationobject.- Parameters:
- duration-- Durationto test this- Durationagainst.
- Returns:
- trueif- durationparameter is shorter than this- Duration, else- false.
- Throws:
- UnsupportedOperationException- If the underlying implementation cannot reasonably process the request, e.g. W3C XML Schema allows for arbitrarily large/small/precise values, the request may be beyond the implementations capability.
- NullPointerException- if- durationis null.
- See Also:
- isLongerThan(Duration duration),- compare(Duration duration)
 
 - 
equalspublic boolean equals(Object duration) Checks if this duration object has the same duration as anotherDurationobject.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"))- Overrides:
- equalsin class- Object
- Parameters:
- duration- The object to compare this- Durationagainst.
- Returns:
- trueif this duration is the same length as- duration.- falseif- durationis- null, is not a- Durationobject, or its length is different from this duration.
- Throws:
- UnsupportedOperationException- If the underlying implementation cannot reasonably process the request, e.g. W3C XML Schema allows for arbitrarily large/small/precise values, the request may be beyond the implementations capability.
- See Also:
- compare(Duration duration)
 
 - 
hashCodepublic abstract int hashCode() Returns a hash code consistent with the definition of the equals method.- Overrides:
- hashCodein class- Object
- Returns:
- a hash code value for this object.
- See Also:
- Object.hashCode()
 
 - 
toStringpublic String toString() Returns aStringrepresentation of thisDuration Object.The result is formatted according to the XML Schema 1.0 spec and can be always parsed back later into the equivalent Duration ObjectbyDatatypeFactory.newDuration(String lexicalRepresentation).Formally, the following holds for any DurationObjectx:new Duration(x.toString()).equals(x) 
 
- 
 
-