U
 generic type of time unitspublic final class Duration<U extends IsoUnit> extends AbstractDuration<U> implements Serializable
ISO8601compatible duration between two time points.
Instances can be created by following factory methods:
of(long, U)
ofCalendarUnits(int, int, int)
ofClockUnits(int, int, int)
ofPositive()
(builderpattern)ofNegative()
(builderpattern)parsePeriod(String)
parseCalendarPeriod(String)
parseClockPeriod(String)
parseWeekBasedPeriod(String)
All instances are immutable, but changed copies can be created
by using the methods plus()
, with()
, union()
,
multipliedBy()
, abs()
and inverse()
. The time
units ClockUnit.MILLIS
and ClockUnit.MICROS
will
automatically normalized to nanoseconds. In every other case a normalization
must be explicitly triggered by with(Normalizer)
.
Note: The definition of an optional negative sign is not part of
ISO8061, but part of the XMLschemaspecification and defines the
position of two time points relative to each other. A manipulation of
the sign is possible with the method inverse()
.
The time arithmetic handles the addition of a duration to a time point and the subtraction of a duration from a time point as dependent on the sign of the duration as described in the standard algorithm of the super class.
Modifier and Type  Class and Description 

static class 
Duration.Builder
Builder class for constructing a duration conforming to ISO8601
which consists of years, months, days and any wall time units.

static class 
Duration.Formatter<U extends IsoUnit>
Nonlocalized and userdefined format for durations based on a
pattern containing some standard symbols and literals.

TimeSpan.Item<U>
Modifier and Type  Field and Description 

static Normalizer<CalendarUnit> 
STD_CALENDAR_PERIOD
Normalizes the calendrical items of a duration on the base
1 year = 12 months  without converting the days to months. 
static Normalizer<ClockUnit> 
STD_CLOCK_PERIOD
Normalizes the wall time items of a duration on the base
1 day = 24 hours und 1 hour = 60 minutes and
1 minute = 60 seconds . 
static Normalizer<IsoUnit> 
STD_PERIOD
Normalizes the duration items on the base of
1 year = 12 months and 1 day = 24 hours and
1 hour = 60 minutes and 1 minute = 60 seconds 
without converting days to months. 
Modifier and Type  Method and Description 

Duration<U> 
abs()
Gets the absolute always nonnegative copy of this duration.

static Normalizer<IsoUnit> 
approximateHours(int steps)
Yields an approximate normalizer in steps of hours which
finally uses years, months, days and rounded hours.

static Normalizer<IsoUnit> 
approximateMaxUnitOnly()
Creates a normalizer which yields an approximate duration based on the maximum unit
of the original duration (but not smaller than seconds).

static Normalizer<IsoUnit> 
approximateMaxUnitOrWeeks()
Like
approximateMaxUnitOnly() but can create weekbased durations
if the count of days is bigger than 6 . 
static Normalizer<IsoUnit> 
approximateMinutes(int steps)
Yields an approximate normalizer in steps of minutes which
finally uses years, months, days, hours and rounded minutes.

static Normalizer<IsoUnit> 
approximateSeconds(int steps)
Yields an approximate normalizer in steps of seconds which finally
uses years, months, days, hours, minutes and rounded seconds.

static <U extends IsoUnit,T extends TimePoint<? super U,T>> 
comparator(T base)
Creates a
Comparator which compares durations based on
their lengths. 
static Duration<IsoUnit> 
compose(Duration<CalendarUnit> calendarPeriod,
Duration<ClockUnit> clockPeriod)
Creates a composition of a calendar period and a clock period.

boolean 
contains(IsoUnit unit)
Queries if this duration contains given time unit.

boolean 
equals(Object obj)
Based on all stored duration items and the sign.

static <U extends IsoUnit> 
formatter(Class<U> type,
String pattern)
Equivalent to
Duration.Formatter.ofPattern(Class, String) . 
static Duration.Formatter<IsoUnit> 
formatter(String pattern)
Equivalent to
Duration.Formatter.ofPattern(String) . 
static Duration<ClockUnit> 
from(Duration threetenDuration)
Short cut for
TemporalType.THREETEN_DURATION.translate(threetenDuration) . 
static Duration<CalendarUnit> 
from(Period threetenPeriod)
Short cut for
TemporalType.THREETEN_PERIOD.translate(threetenPeriod) . 
static Duration<IsoUnit> 
from(TemporalAmount threeten)
Tries to convert given temporal amount to a duration.

long 
getPartialAmount(IsoUnit unit)
Gets the partial amount associated with given time unit.

List<TimeSpan.Item<U>> 
getTotalLength()
Yields all containted time span items with amount and unit in
the order from largest to smallest time units.

int 
hashCode()
Computes the hash code.

static TimeMetric<IsoUnit,Duration<IsoUnit>> 
in(Timezone tz,
IsoUnit... units)
Helps to evaluate the zonal duration between two timestamps
and applies an offset correction if necessary.

static <U extends IsoUnit> 
in(U... units)
Constructs a metric for any kind of standard units in
normalized form.

static TimeMetric<ClockUnit,Duration<ClockUnit>> 
inClockUnits()
Constructs a metric in hours, minutes, seconds and nanoseconds.

Duration<U> 
inverse()
Gets a copy of this duration with reversed sign.

static TimeMetric<IsoDateUnit,Duration<IsoDateUnit>> 
inWeekBasedUnits()
Constructs a metric in weekbased years, weeks and days.

static TimeMetric<CalendarUnit,Duration<CalendarUnit>> 
inYearsMonthsDays()
Constructs a metric in years, months and days.

boolean 
isNegative()
Queries if this time span is negative.

Duration<U> 
multipliedBy(int factor)
Multiplies all partial amounts of this duration by given factor.

static <U extends IsoUnit> 
of(long amount,
U unit)
Creates a new duration which only knows one unit.

static Duration<CalendarUnit> 
ofCalendarUnits(int years,
int months,
int days)
Creates a positive duration in years, months and days.

static Duration<ClockUnit> 
ofClockUnits(int hours,
int minutes,
int seconds)
Creates a positive duratioon in hours, minutes and seconds.

static Duration.Builder 
ofNegative()
Konstructs a new negative duration for combined date and time items
by applying the builder pattern.

static Duration.Builder 
ofPositive()
Konstructs a new positive duration for combined date and time items
by applying the builder pattern.

static <U extends IsoUnit> 
ofZero()
Gets an empty duration without units.

static Duration<CalendarUnit> 
parseCalendarPeriod(String period)
Parses a canonical representation with only date units to a
calendrical duration.

static Duration<ClockUnit> 
parseClockPeriod(String period)
Parses a canonical representation with only wall time units to a
timeonly duration.

static Duration<IsoUnit> 
parsePeriod(String period)
Parses a canonical representation to a duration.

static Duration<IsoDateUnit> 
parseWeekBasedPeriod(String period)
Parses a canonical representation with only weekbased units (Y, W and D) to a
calendrical duration where years are interpreted as weekbased years.

Duration<U> 
plus(long amount,
U unit)
Gets a copy of this duration where given amount will be added
to the partial amount of this duration in given unit.

Duration<U> 
plus(TimeSpan<? extends U> timespan)
Creates a duration as union of this instance and given timespan
where partial amounts of equal units will be summed up.

Duration<CalendarUnit> 
toCalendarPeriod()
Extracts a new duration with all contained calendar units only.

Duration<ClockUnit> 
toClockPeriod()
Extracts a new duration with all contained clock units only.

Duration<ClockUnit> 
toClockPeriodWithDaysAs24Hours()
Extracts a new duration with all contained clock units only.

String 
toString()
Gets a canonical representation which optionally starts with a
negative sign then continues with the letter "P", followed
by a sequence of alphanumerical chars similar to the definition given
in ISO8601.

String 
toStringISO()
Gets a canonical representation which starts with the letter
"P", followed by a sequence of alphanumerical chars as
defined in ISO8601.

String 
toStringXML()
Gets a canonical representation conforming to XMLschema which
optionally starts with a negative sign then continues with the letter
"P", followed by a sequence of alphanumerical chars similar
to the definition given in ISO8601.

TemporalAmount 
toTemporalAmount()
Converts this duration to a general temporal amount compatible with JSR310spec.

List<Duration<U>> 
union(TimeSpan<? extends U> timespan)
Creates a duration as union of this instance and given timespan
where partial amounts of equal units will be summed up.

Duration<U> 
with(long amount,
U unit)
Gets a copy of this duration where the partial amount associated
with given time unit is changed.

Duration<U> 
with(Normalizer<U> normalizer)
Normalizes this duration by given normalizer.

addTo, isEmpty, isPositive, subtractFrom
public static Normalizer<IsoUnit> STD_PERIOD
Normalizes the duration items on the base of
1 year = 12 months
and 1 day = 24 hours
and
1 hour = 60 minutes
and 1 minute = 60 seconds

without converting days to months.
Attention: Timezonedependent changes of length of day or
leapseconds are ignored. That is why this normalization should
only be applied on ISOtimestamps without timezone reference.
Only time units of enum types CalendarUnit
and
ClockUnit
will be normalized.
Weeks will be normalized to days if weeks do not represent the only calendrical duration items.
PlainTimestamp.normalize(TimeSpan)
public static Normalizer<CalendarUnit> STD_CALENDAR_PERIOD
Normalizes the calendrical items of a duration on the base
1 year = 12 months
 without converting the days to months.
Weeks will be normalized to days if weeks do not represent
the only calendrical duration items. Only time units of type
CalendarUnit
will be normalized.
PlainDate.normalize(TimeSpan)
public static Normalizer<ClockUnit> STD_CLOCK_PERIOD
Normalizes the wall time items of a duration on the base
1 day = 24 hours
und 1 hour = 60 minutes
and
1 minute = 60 seconds
.
Attention: Timezonedependent changes of length of day or
leapseconds are ignored. That is why this normalization should
only be applied on ISOtimestamps without timezone reference.
Only time units of enum type ClockUnit
will be normalized.
PlainTime
public static <U extends IsoUnit> Duration<U> ofZero()
Gets an empty duration without units.
This method can also be used for generic upcasting of the
type U to IsoUnit
:
Duration<CalendarUnit> dur = Duration.ofCalendarUnits(2, 5, 30); Duration<IsoUnit> upcasted = Duration.ofZero().plus(dur);
U
 generic unit typepublic static <U extends IsoUnit> Duration<U> of(long amount, U unit)
Creates a new duration which only knows one unit.
Is the given amount is negative then the duration will be
negative, too. Is the amount equal to 0
then an empty
duration will be returned. Milliseconds or microseconds will
be automatically normalized to nanoseconds.
U
 generic unit typeamount
 amount as count of unitsunit
 single time unitpublic static Duration.Builder ofPositive()
Konstructs a new positive duration for combined date and time items by applying the builder pattern.
Duration
public static Duration.Builder ofNegative()
Konstructs a new negative duration for combined date and time items by applying the builder pattern.
Duration
public static Duration<CalendarUnit> ofCalendarUnits(int years, int months, int days)
Creates a positive duration in years, months and days.
All arguments must not be negative. Is any argument equal to
0
then it will be ignored. If a negative duration is needed
then an application can simply call inverse()
on the result.
years
 amount in yearsmonths
 amount in monthsdays
 amount in daysIllegalArgumentException
 if any argument is negativeinverse()
public static Duration<ClockUnit> ofClockUnits(int hours, int minutes, int seconds)
Creates a positive duratioon in hours, minutes and seconds.
All arguments must not be negative. Is any argument equal to
0
then it will be ignored. If a negative duration is needed
then an application can simply call inverse()
on the result.
hours
 amount in hoursminutes
 amount in minutesseconds
 amount in secondsIllegalArgumentException
 if any argument is negativeinverse()
public static Duration<IsoUnit> from(TemporalAmount threeten)
Tries to convert given temporal amount to a duration.
Note that the arithmetic of given amount is probably different from that of the result. Every unit
compatible with java.time.temporal.ChronoUnit
with exception of ERAS
and FOREVER
can be processed. Also the units IsoFields.QUARTER_YEARS
and IsoFields.WEEK_BASED_YEARS
are accepted.
threeten
 temporal amountIllegalArgumentException
 if the argument contains a nonmappable temporal unit or has mixed signsfrom(java.time.Duration)
,
from(java.time.Period)
,
STD_PERIOD
public static Duration<ClockUnit> from(Duration threetenDuration)
Short cut for TemporalType.THREETEN_DURATION.translate(threetenDuration)
.
threetenDuration
 Threetenequivalent of a clock durationTemporalType.THREETEN_DURATION
,
STD_CLOCK_PERIOD
public static Duration<CalendarUnit> from(Period threetenPeriod)
Short cut for TemporalType.THREETEN_PERIOD.translate(threetenPeriod)
.
Note that the arithmetic of given period is slightly different from that of the result when it comes to handling negative durations:
System.out.println( LocalDate.of(2015, 7, 1).minus(Period.of(0, 1, 1))); // 20150531 System.out.println( PlainDate.of(2015, 7, 1).minus(Duration.ofCalendarUnits(0, 1, 1))); // 20150530
threetenPeriod
 Threetenequivalent of a calendar durationChronoException
 if conversion fails due to mixed signsTemporalType.THREETEN_PERIOD
,
STD_CALENDAR_PERIOD
@SafeVarargs public static <U extends IsoUnit> TimeMetric<U,Duration<U>> in(U... units)
Constructs a metric for any kind of standard units in normalized form.
Important: If the smallest unit is missing which fits the precision of timepoints to be compared then a remainder of subtraction will exist. The result of distance calculation will not express the full temporal distance in this case. For the completeness of calculation, the day unit is required if the distance between two dates is needed.
Example with different unit types: If this method
is called with different unit types then it is strongly recommended to
first assign the units to static constants of type IsoUnit
in
order to avoid compiler problems with generics. This practice also
helps to improve the readability of code.
private static final IsoUnit DAYS = CalendarUnit.DAYS; private static final IsoUnit HOURS = ClockUnit.HOURS; private static final IsoUnit MINUTES = ClockUnit.MINUTES; PlainTimestamp start = PlainTimestamp.of(2014, 3, 28, 0, 30); PlainTimestamp end = PlainTimestamp.of(2014, 4, 5, 14, 15); Duration<IsoUnit> duration = Duration.in(DAYS, HOURS, MINUTES).between(start, end); System.out.println(duration); // output: P8DT13H45M
U
 generic unit typeunits
 time units to be used in calculationIllegalArgumentException
 if no time unit is given or
if there are unit duplicatespublic static TimeMetric<CalendarUnit,Duration<CalendarUnit>> inYearsMonthsDays()
Constructs a metric in years, months and days.
Finally the resulting duration will be normalized such that smaller units will be converted to bigger units if possible.
in(U[])
,
CalendarUnit.YEARS
,
CalendarUnit.MONTHS
,
CalendarUnit.DAYS
public static TimeMetric<ClockUnit,Duration<ClockUnit>> inClockUnits()
Constructs a metric in hours, minutes, seconds and nanoseconds.
Finally the resulting duration will be normalized such that smaller units will be converted to bigger units if possible.
in(U[])
,
ClockUnit.HOURS
,
ClockUnit.MINUTES
,
ClockUnit.SECONDS
,
ClockUnit.NANOS
public static TimeMetric<IsoDateUnit,Duration<IsoDateUnit>> inWeekBasedUnits()
Constructs a metric in weekbased years, weeks and days.
Finally the resulting duration will be normalized such that smaller units will be converted to bigger units if possible.
in(U[])
,
CalendarUnit.weekBasedYears()
,
CalendarUnit.WEEKS
,
CalendarUnit.DAYS
public static TimeMetric<IsoUnit,Duration<IsoUnit>> in(Timezone tz, IsoUnit... units)
Helps to evaluate the zonal duration between two timestamps and applies an offset correction if necessary.
Following example handles the change from winter time to summer time in Germany causing 4 instead of 5 hours difference:
PlainTimestamp start = PlainTimestamp.of(2014, 3, 30, 0, 0); PlainTimestamp end = PlainTimestamp.of(2014, 3, 30, 5, 0); IsoUnit hours = ClockUnit.HOURS; System.out.println( Duration.in(Timezone.of("Europe/Berlin"), hours) .between(start, end).toString()); // output: PT4H
tz
 timezoneunits
 time units to be used in calculationIllegalArgumentException
 if no time unit is given or
if there are unit duplicatespublic List<TimeSpan.Item<U>> getTotalLength()
TimeSpan
Yields all containted time span items with amount and unit in the order from largest to smallest time units.
getTotalLength
in interface TimeSpan<U extends IsoUnit>
public boolean isNegative()
TimeSpan
Queries if this time span is negative.
A negative time span relates to the subtraction of two time points where first one is after second one. The partial amounts of every time span are never negative. Hence this attribute is not associated with the partial amounts but only with the time span itself.
Note: An empty time span itself is never negative in agreement
with the mathematical relation (1) * 0 = 0
.
isNegative
in interface TimeSpan<U extends IsoUnit>
true
if negative and not empty else false
public boolean contains(IsoUnit unit)
Queries if this duration contains given time unit.
Any time unit is also part of this duration if it is a fractional part of a second (digit symbol) which is to be converted first.
contains
in interface TimeSpan<U extends IsoUnit>
contains
in class AbstractDuration<U extends IsoUnit>
unit
 time unit to be checked (optional)true
if this duration contains given unit
else false
getPartialAmount(U)
public long getPartialAmount(IsoUnit unit)
Gets the partial amount associated with given time unit.
If this duration does not contain given time unit then this method
will yield the value 0
. Fractional parts of seconds which
are known by their numerical symbols will automatically be converted.
That means if a duration stores nanoseconds, but is queried for
microseconds then the nanosecond amount will be multiplied by factor
1000
and finally returned.
getPartialAmount
in interface TimeSpan<U extends IsoUnit>
getPartialAmount
in class AbstractDuration<U extends IsoUnit>
unit
 time unit the amount is queried for (optional)>= 0
)public static <U extends IsoUnit,T extends TimePoint<? super U,T>> Comparator<Duration<U>> comparator(T base)
Creates a Comparator
which compares durations based on
their lengths.
Internally, the comparing algorithm uses the expression
base.plus(duration1).compareTo(base.plus(duration2))
.
The given basis time point is necessary because some durations
with flexible units like months have else no fixed length.
U
 generic unit typeT
 generic type of time pointbase
 base time point which durations will use for comparisonComparator
for plain durationsTimePoint.compareTo(T)
public Duration<U> plus(long amount, U unit)
Gets a copy of this duration where given amount will be added to the partial amount of this duration in given unit.
The method also takes in account the sign of the duration. Example:
System.out.println(Duration.of(5, MONTHS).plus(6, MONTHS)); // output: P1M
Notes: Is the amount to be added equal to 0
then the method
will simply yield this duration. Mixed signs are not permitted and will
be rejected by an exception. For example following expression is not
allowed:
Duration.of(1, MONTHS).plus(30, DAYS); // throws IllegalStateException
amount
 temporal amount to be added (maybe negative)unit
 associated time unitIllegalStateException
 if the result gets mixed signs by adding the partial amountsIllegalArgumentException
 if different units of same length existArithmeticException
 in case of long overflowwith(long, U)
public Duration<U> plus(TimeSpan<? extends U> timespan)
Creates a duration as union of this instance and given timespan where partial amounts of equal units will be summed up.
In order to sum up timespans with different unit types, following trick can be applied:
Duration<IsoUnit> zero = Duration.ofZero(); Duration<IsoUnit> result = zero.plus(this).plus(timespan);
Note about sign handling: If this duration and given timespan have different signs then Time4J tries to apply a normalization in the hope the mixed signs disappear. Otherwise this method will throw an exception in case of mixed signs for different duration items. So it is strongly recommended only to merge durations with equal signs.
timespan
 other time span this duration will be merged
with by adding the partial amountsIllegalStateException
 if the result gets mixed signs by
adding the partial amountsIllegalArgumentException
 if different units of same length existArithmeticException
 in case of long overflowunion(TimeSpan)
public Duration<U> with(long amount, U unit)
Gets a copy of this duration where the partial amount associated with given time unit is changed.
Equivalent to plus(amount  getAmount(unit), unit)
.
amount
 temporal amount to be set (maybe negative)unit
 associated time unitIllegalStateException
 if the result gets mixed signs by
setting the partial amountsIllegalArgumentException
 if different units of same length existArithmeticException
 in case of long overflowplus(long, U)
public Duration<U> abs()
Gets the absolute always nonnegative copy of this duration.
Example:
System.out.println(Duration.of(5, MONTHS).abs()); // output: P5M
isNegative()
,
inverse()
public Duration<U> inverse()
Gets a copy of this duration with reversed sign.
A double call of this method will yield an equal duration so following invariant holds:
System.out.println(this.inverse().inverse().equals(this)); // output: true
For the special case of an empty duration, this method has no
effect and just returns the same instance. The method is equivalent
to the expression multipliedBy(1)
.
Example:
System.out.println(Duration.of(5, MONTHS).inverse()); // output: P5M
inverse
in class AbstractDuration<U extends IsoUnit>
isNegative()
,
multipliedBy(int)
public Duration<U> multipliedBy(int factor)
Multiplies all partial amounts of this duration by given factor.
Is the factor equal to 0
then the new duration is empty.
If the factor 1
is specified then the method will just yield
this instance unaffected. In the case of a negative factor the sign
will also be inverted.
factor
 multiplication factorArithmeticException
 in case of long overflowpublic List<Duration<U>> union(TimeSpan<? extends U> timespan)
Creates a duration as union of this instance and given timespan where partial amounts of equal units will be summed up.
The list result of this method can be used in time arithmetic as follows:
Duration<CalendarUnit> dateDur = Duration.ofCalendarUnits(2, 7, 10); Duration<ClockUnit> timeDur = Duration.ofClockUnits(0, 30, 0); PlainTimestamp tsp = PlainTimestamp.of(2014, 1, 1, 0, 0); for (Duration<?> dur : Duration.ofZero().plus(dateDur).union(timeDur)) { tsp = tsp.plus(dur); } System.out.println(tsp); // 20160811T00:30
Note that this example will even work in case of mixed signs. No
exception will be thrown. Instead this duration and the other one would
just be added to the timestamp within a loop  step by step. In contrast
to plus(TimeSpan)
, Time4J does not try to normalize the durations
in order to produce a unique sign (on best effort base) in case of
mixed signs.
timespan
 other time span this duration is to be merged withIllegalArgumentException
 if different units of same length existArithmeticException
 in case of long overflowplus(TimeSpan)
public static Duration<IsoUnit> compose(Duration<CalendarUnit> calendarPeriod, Duration<ClockUnit> clockPeriod)
Creates a composition of a calendar period and a clock period.
calendarPeriod
 calendrical durationclockPeriod
 duration with clock unitstoCalendarPeriod()
,
toClockPeriod()
public Duration<CalendarUnit> toCalendarPeriod()
Extracts a new duration with all contained calendar units only.
The clock time part will be removed.
compose(Duration, Duration)
,
toClockPeriod()
public Duration<ClockUnit> toClockPeriod()
Extracts a new duration with all contained clock units only.
The calendrical part will be removed.
compose(Duration, Duration)
,
toCalendarPeriod()
public Duration<ClockUnit> toClockPeriodWithDaysAs24Hours()
Extracts a new duration with all contained clock units only.
The calendrical part will be removed with the exception of the days which will be converted into hours (on the base 1 day = 24 hours).
compose(Duration, Duration)
,
toCalendarPeriod()
public TemporalAmount toTemporalAmount()
Converts this duration to a general temporal amount compatible with JSR310spec.
The conversion is possible if and only if following units are part of this duration:
The resulting temporal amount is preferred to be applied on the local types of JSR310 for the sake of conceptual clarity so the general mapping using this method looks like:
Duration<IsoUnit>
can be applied on LocalDateTime
Duration<CalendarUnit>
can be applied on LocalDate
Duration<ClockUnit>
can be applied on LocalTime
Other temporal types of JSR310 might be supported, too (like YearMonth
or ZonedDateTime
).
Note that using this method cannot be typesafe due to the design of JSR310 (possibly throwing an exception
at runtime) and includes some performance penalty because of the costs of conversion. Users should rather use
Time4Jtypes for achieving best results.
UnsupportedOperationException
 if this duration contains any unit not listed abovepublic Duration<U> with(Normalizer<U> normalizer)
Normalizes this duration by given normalizer.
normalizer
 help object for normalizing this durationSTD_PERIOD
,
STD_CALENDAR_PERIOD
,
STD_CLOCK_PERIOD
,
approximateHours(int)
,
approximateMinutes(int)
,
approximateSeconds(int)
,
ClockUnit.only()
public static Normalizer<IsoUnit> approximateHours(int steps)
Yields an approximate normalizer in steps of hours which finally uses years, months, days and rounded hours.
The rounding algorithm consists of a combination of integer division and multiplication using the given step width. Example for suppressing hours (and all smaller units) by mean of an extra big step width of 24 hours (= 1 day):
Duration<IsoUnit> dur = Duration.ofPositive().years(2).months(13).days(35) .minutes(132).build() .with(Duration.approximateHours(24)); System.out.println(dur); // output: P3Y2M4D
Another example for rounded hours using static imports:
System.out.println(Duration.<IsoUnit>of(7, HOURS).with(approximateHours(3))); // output: PT6H
steps
 rounding step widthIllegalArgumentException
 if the argument is not positivepublic static Normalizer<IsoUnit> approximateMinutes(int steps)
Yields an approximate normalizer in steps of minutes which finally uses years, months, days, hours and rounded minutes.
steps
 rounding step widthIllegalArgumentException
 if the argument is not positiveapproximateHours(int)
public static Normalizer<IsoUnit> approximateSeconds(int steps)
Yields an approximate normalizer in steps of seconds which finally uses years, months, days, hours, minutes and rounded seconds.
steps
 rounding step widthIllegalArgumentException
 if the argument is not positiveapproximateHours(int)
public static Normalizer<IsoUnit> approximateMaxUnitOnly()
Creates a normalizer which yields an approximate duration based on the maximum unit of the original duration (but not smaller than seconds).
approximateHours(int)
,
approximateMinutes(int)
,
approximateSeconds(int)
public static Normalizer<IsoUnit> approximateMaxUnitOrWeeks()
Like approximateMaxUnitOnly()
but can create weekbased durations
if the count of days is bigger than 6
.
approximateMaxUnitOnly()
public boolean equals(Object obj)
Based on all stored duration items and the sign.
equals
in class Object
true
if obj
is also a Duration
,
has the same units and amounts, the same sign and the same
calendrical status else false
getTotalLength()
,
isNegative()
public String toString()
Gets a canonical representation which optionally starts with a negative sign then continues with the letter "P", followed by a sequence of alphanumerical chars similar to the definition given in ISO8601.
Example: In ISO8601 a duration of one month, three days and four
hours is described as "P1M3DT4H". The special char
"T" separates date and time part. Units are normally
printed using their symbols, as second alternative using the output
of their toString()
method within curly brackets.
Is the duration negative then the representation will have a preceding minus sign as specified by XMLschema (for example "P2D") while an empty duration will always have the format "PT0S" (second as universal unit). If the second part is also fractional then this method will use the comma as decimal separator char as recommended by ISO8601.
Note: The latter ISOrecommendation to use the comma as decimal separator char can be overriden by setting the system property "net.time4j.format.iso.decimal.dot" to "true" so that the english variation of a dot will be choosen instead.
toString
in class AbstractDuration<U extends IsoUnit>
toStringISO()
,
toStringXML()
,
parsePeriod(String)
public String toStringISO()
Gets a canonical representation which starts with the letter "P", followed by a sequence of alphanumerical chars as defined in ISO8601.
A negative sign is not defined in ISO8601 and will be rejected by this method with an exception. An empty duration will always have the format "PT0S" (second as universal unit). If the second part is also fractional then this method will use the comma as decimal separator char as recommended by ISO8601.
Note: The latter ISOrecommendation to use the comma as decimal separator char can be overriden by setting the system property "net.time4j.format.iso.decimal.dot" to "true" so that the english variation of a dot will be choosen instead. Furthermore, weeks are normalized to days if there are other calendrical units like years or months.
Only units of types CalendarUnit
or ClockUnit
can
be printed.
ChronoException
 if this duration is negative or if any special
units shall be output, but units of type CalendarUnit
will be translated to isocompatible units if necessaryparsePeriod(String)
,
IsoUnit.getSymbol()
public String toStringXML()
Gets a canonical representation conforming to XMLschema which optionally starts with a negative sign then continues with the letter "P", followed by a sequence of alphanumerical chars similar to the definition given in ISO8601.
Is the duration negative then the representation will have a preceding minus sign as specified by XMLschema (for example "P2D") while an empty duration will always have the format "PT0S" (second as universal unit). If the second part is also fractional then this method will use the dot as decimal separator char (deviating specification in XMLschema). Weeks will always be normalized to days.
Only units of types CalendarUnit
or ClockUnit
can
be printed.
ChronoException
 if any special units shall be
output, but units of type CalendarUnit
will be
translated to xmlcompatible units if necessaryparsePeriod(String)
,
IsoUnit.getSymbol()
public static Duration<IsoUnit> parsePeriod(String period) throws ParseException
Parses a canonical representation to a duration.
Canonical representations which start with the literal P are also called "period" in Time4J (Pstring). This format is strongly recommended for storage in databases or XML. Syntax in a notation similar to regular expressions:
sign := []? amount := [09]+ fraction := [,\.]{amount} yearsmonthsdays := ({amount}Y)?({amount}M)?({amount}D)? weeks := ({amount}W)? date := {yearsmonthsdays}  {weeks} time := ({amount}H)?({amount}M)?({amount}{fraction}?S)? period := {sign}P{date}(T{time})?  PT{time}
The units MILLENNIA, CENTURIES, DECADES and QUARTERS defined in
CalendarUnit
are supported but not special units like
CalendarUnit.weekBasedYears()
.
Furthermore there is the constraint that the symbols P and T
must be followed by at least one duration item of amount and unit.
All items with zero amount will be ignored however. The only item
which is allowed to have a fractional part is SECONDS and can contain
a comma as well as a dot as decimal separator. In ISO8601 the comma
is the preferred char, in XMLschema only the dot is allowed. If this
parser is used in context of XMLschema (type xs:duration) it must
be stated that week items are missing in contrast to ISO8601. The
method toStringXML()
takes into account these characteristics
of XMLschema (leaving aside the fact that XMLschema is potentially
designed for unlimited big amounts but Time4J can define durations
only in long range with nanosecond precision at best).
Note: The alternative ISOformats PYYYYMMDDThh:mm:ss and PYYYYDDDThh:mm:ss and their basic variants are supported since version v2.0.
Examples for supported formats:
date := P7Y4M3D (negative: 7 years, 4 months, 3 days) time := PT3H2M1,4S (positive: 3 hours, 2 minutes, 1400 milliseconds) datetime := P1Y1M5DT15H59M10.400S (dot as decimal separator) alternative := P00000215T17:45
period
 duration in canonical, ISO8601compatible or
XMLschemacompatible format (Pstring)ParseException
 if parsing failsparseCalendarPeriod(String)
,
parseClockPeriod(String)
,
toString()
,
toStringISO()
,
toStringXML()
public static Duration<CalendarUnit> parseCalendarPeriod(String period) throws ParseException
Parses a canonical representation with only date units to a calendrical duration.
period
 duration in canonical, ISO8601compatible or
XMLschemacompatible format (Pstring)ParseException
 if parsing failsparsePeriod(String)
,
parseClockPeriod(String)
public static Duration<ClockUnit> parseClockPeriod(String period) throws ParseException
Parses a canonical representation with only wall time units to a timeonly duration.
period
 duration in canonical, ISO8601compatible or
XMLschemacompatible format (Pstring)ParseException
 if parsing failsparsePeriod(String)
,
parseCalendarPeriod(String)
public static Duration<IsoDateUnit> parseWeekBasedPeriod(String period) throws ParseException
Parses a canonical representation with only weekbased units (Y, W and D) to a calendrical duration where years are interpreted as weekbased years.
period
 duration in canonical or ISO8601compatible format (Pstring)ParseException
 if parsing failsparsePeriod(String)
,
CalendarUnit.weekBasedYears()
public static Duration.Formatter<IsoUnit> formatter(String pattern)
Equivalent to Duration.Formatter.ofPattern(String)
.
pattern
 format patternIllegalArgumentException
 in any case of pattern inconsistencies or failurespublic static <U extends IsoUnit> Duration.Formatter<U> formatter(Class<U> type, String pattern)
Equivalent to Duration.Formatter.ofPattern(Class, String)
.
U
 generic unit typetype
 reified unit typepattern
 format patternIllegalArgumentException
 in any case of pattern inconsistencies or failuresCopyright © 2014–2018. All rights reserved.