Class DurationImpl
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected BigIntegerDays of thisDurationImpl.protected BigIntegerHours of thisDurationImpl.protected BigIntegerMinutes of thisDurationImpl.protected BigIntegerMonths of thisDurationImpl.protected BigDecimalSeconds of thisDurationImpl.protected intIndicates the sign.protected BigIntegerThese were final since DurationImpl is immutable. -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedDurationImpl(boolean isPositive, int years, int months, int days, int hours, int minutes, int seconds) Constructs a new DurationImpl object by specifying each field individually.protectedDurationImpl(boolean isPositive, BigInteger years, BigInteger months, BigInteger days, BigInteger hours, BigInteger minutes, BigDecimal seconds) Constructs a new DurationImpl object by specifying each field individually.protectedDurationImpl(long durationInMilliSeconds) Constructs a new DurationImpl object by specifying the duration in milliseconds.protectedDurationImpl(String lexicalRepresentation) Constructs a new DurationImpl object by parsing its string representation "PnYnMnDTnHnMnS" as defined in XML Schema 1.0 section 3.2.6.1. -
Method Summary
Modifier and TypeMethodDescriptionadd(DurationImpl rhs) Computes a new duration whose value isthis+rhs.voidAdds this duration to aCalendarobject.voidAdds this duration to aDateobject.protected intcalcSignum(boolean isPositive) TODO: Javadocintcompare(DurationImpl rhs) Partial order relation comparison with thisDurationImplinstance.intgetDays()Obtains the value of the DAYS field as an integer value, or 0 if not present.getField(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.intObtains the value of the MINUTES field as an integer value, or 0 if not present.intObtains the value of the MONTHS field as an integer value, or 0 if not present.intObtains the value of the SECONDS field as an integer value, or 0 if not present.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.intgetYears()Obtains the value of the YEARS field as an integer value, or 0 if not present.inthashCode()Returns a hash code consistent with the definition of the equals method.booleanisSet(DatatypeConstants.Field field) Checks if a field is set.multiply(int factor) Computes a new duration whose value isfactortimes longer than the value of this duration.multiply(BigDecimal factor) Computes a new duration whose value isfactortimes longer than the value of this duration.negate()Returns a newDurationImplobject whose value is-this.normalizeWith(Calendar startTimeInstant) Converts the years and months fields into the days field by using a specific time instant as the reference point.intsignum()Returns the sign of this duration in -1,0, or 1.subtract(DurationImpl rhs) Computes a new duration whose value isthis-rhs.protected static voidMakes sure that the given number is non-negative.protected static voidMakes sure that the given number is non-negative.toString()Returns a string representation of this duration object.protected static BigIntegerwrap(int i) TODO: Javadoc
-
Field Details
-
signum
protected int signumIndicates the sign. -1, 0 or 1 if the duration is negative, zero, or positive.
-
years
These were final since DurationImpl is immutable. But new subclasses need to be able to set after conversion. It won't break the immutable nature of them since there's no other way to set new values to them -
months
Months of this
DurationImpl. -
days
Days of this
DurationImpl. -
hours
Hours of this
DurationImpl. -
minutes
Minutes of this
DurationImpl. -
seconds
Seconds of this
DurationImpl.
-
-
Constructor Details
-
DurationImpl
protected DurationImpl(boolean isPositive, BigInteger years, BigInteger months, BigInteger days, BigInteger hours, BigInteger minutes, BigDecimal seconds) Constructs a new DurationImpl 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.
- Parameters:
isPositive- Set tofalseto create a negative duration. When the length of the duration is zero, this parameter will be ignored.years- of thisDurationImplmonths- of thisDurationImpldays- of thisDurationImplhours- of thisDurationImplminutes- of thisDurationImplseconds- of thisDurationImpl- Throws:
IllegalArgumentException- If years, months, days, hours, minutes and seconds parameters are allnull. Or if any of those parameters are negative.
-
DurationImpl
protected DurationImpl(boolean isPositive, int years, int months, int days, int hours, int minutes, int seconds) Constructs a new DurationImpl object by specifying each field individually.
This method is functionally equivalent to invoking another constructor by wrapping all non-zero parameters into
BigIntegerandBigDecimal. Zero value of int parameter is equivalent of null value of the corresponding field.- See Also:
-
DurationImpl
protected DurationImpl(long durationInMilliSeconds) Constructs a new DurationImpl object by specifying the duration in milliseconds.
- Parameters:
durationInMilliSeconds- The length of the duration in milliseconds.
-
DurationImpl
Constructs a new DurationImpl object by parsing its string representation "PnYnMnDTnHnMnS" as defined in XML Schema 1.0 section 3.2.6.1.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 DurationImpl(x).toString().equals(x)
Returns a non-null valid duration object that holds the value indicated by the lexicalRepresentation parameter.- Parameters:
lexicalRepresentation- Lexical representation of a duration.- Throws:
IllegalArgumentException- If the given string does not conform to the aforementioned specification.NullPointerException- If the given string is null.
-
-
Method Details
-
getSign
public 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 postive.
-
calcSignum
protected int calcSignum(boolean isPositive) TODO: Javadoc- Parameters:
isPositive- Sign.- Returns:
- 1 if positive, else -1.
-
testNonNegative
Makes sure that the given number is non-negative. If it is not, throw
IllegalArgumentException.- Parameters:
n- Number to test.f- Field to test.
-
testNonNegative
Makes sure that the given number is non-negative. If it is not, throw
IllegalArgumentException.- Parameters:
n- Number to test.f- Field to test.
-
wrap
TODO: Javadoc- Parameters:
i- int to convert to BigInteger.- Returns:
- BigInteger representation of int.
-
compare
Partial order relation comparison with this
DurationImplinstance.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 thisDurationImplis shorter thandurationparameterDatatypeConstants.EQUALif thisDurationImplis equal todurationparameterDatatypeConstants.GREATERif thisDurationImplis longer thandurationparameterDatatypeConstants.INDETERMINATEif a conclusive partial order relation cannot be determined
- Parameters:
duration- to compare- Returns:
- the relationship between
thisDurationImplanddurationparameter 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- ifdurationisnull.- See Also:
-
hashCode
public int hashCode()Returns a hash code consistent with the definition of the equals method. -
toString
Returns a string representation of this duration object.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
DurationImpl(String)constructor.Formally, the following holds for any
DurationImplobject x.new DurationImpl(x.toString()).equals(x)
-
isSet
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.
-
getField
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 field parameter is null.
-
getYears
public int getYears()Obtains the value of the YEARS field as an integer value, or 0 if not present.This method is a convenience method around the
getField(DatatypeConstants.Field)method.Note that since this method returns int, this method will return an incorrect value for
DurationImpls with the year field that goes beyond the range of int. UsegetField(YEARS)to avoid possible loss of precision.- Returns:
- If the YEARS field is present, return its value as an integer by using the
Number.intValue()method. If the YEARS field is not present, return 0.
-
getMonths
public 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
DurationImpl.
-
getDays
public 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
DurationImpl.
-
getHours
public 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
DurationImpl.
-
getMinutes
public 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
DurationImpl.
-
getSeconds
public 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)
-
getTimeInMillis
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 DurationImpl("PT10.00099S").getTimeInMills(x) == 10000.new DurationImpl("-PT10.00099S").getTimeInMills(x) == -10000.Note that this method uses the
addTo(Calendar)method, which may work incorectly withDurationImplobjects with very large values in its fields. See theaddTo(Calendar)method for details.- Parameters:
startInstant- The length of a month/year varies. ThestartInstantis used to disambiguate this variance. Specifically, this method returns the difference betweenstartInstantandstartInstant+duration- Returns:
- milliseconds between
startInstantandstartInstantplus thisDurationImpl - Throws:
NullPointerException- ifstartInstantparameter is null.
-
getTimeInMillis
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 DurationImpl("PT10.00099S").getTimeInMills(x) == 10000.new DurationImpl("-PT10.00099S").getTimeInMills(x) == -10000.Note that this method uses the
addTo(Date)method, which may work incorectly withDurationImplobjects with very large values in its fields. See theaddTo(Date)method for details.- Parameters:
startInstant- The length of a month/year varies. ThestartInstantis used to disambiguate this variance. Specifically, this method returns the difference betweenstartInstantandstartInstant+duration.- Returns:
- milliseconds between
startInstantandstartInstantplus thisDurationImpl - Throws:
NullPointerException- If the startInstant parameter is null.- See Also:
-
normalizeWith
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 two Calendars are computed in terms of days.
- The computed days, along with the hours, minutes and seconds fields of this duration object is used to construct a new DurationImpl 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:
DurationImplof years and months of thisDurationImplas days.- Throws:
NullPointerException- If the startTimeInstant parameter is null.
-
multiply
Computes a new duration whose value is
factortimes 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 newDurationImplto create.- Returns:
- New
DurationImplthat isfactortimes longer than thisDurationImpl. - See Also:
-
multiply
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
DurationImplclass is immutable, this method doesn't change the value of this object. It simply computes a new DurationImpl 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
DurationImplobject - Throws:
IllegalStateException- if operation produces fraction in the months field.NullPointerException- if thefactorparameter isnull.
-
add
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
DurationImpls 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
DurationImpls are simply defined as field by field addition where missing fields are treated as 0.A field of the resulting
DurationImplwill be unset if and only if respective fields of two inputDurationImpls are unset.Note that
lhs.add(rhs)will be always successful iflhs.signum()*rhs.signum()!=-1or both of them are normalized.- Parameters:
rhs-DurationImplto add to thisDurationImpl- Returns:
- non-null valid DurationImpl 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
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
DurationImpls 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.- Parameters:
rhs-DurationImplto substract from thisDurationImpl.- Returns:
- New
DurationImplcreated from subtractingrhsfrom thisDurationImpl. - 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:
-
negate
Returns a newDurationImplobject whose value is-this.Since the
DurationImplclass is immutable, this method doesn't change the value of this object. It simply computes a new DurationImpl object and returns it.- Returns:
- always return a non-null valid
DurationImplobject.
-
signum
public int signum()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 postive.
-
addTo
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
DurationImplobject 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,DurationImplwith values beyond the range of int in its fields will cause overflow/underflow to the givenCalendar.XMLGregorianCalendarImpl.add(DurationImpl)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.
-
addTo
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.
-