Duration

A duration in Joda-Time represents a duration of time measured in milliseconds. The duration is often obtained from an interval.

Durations are a very simple concept, and the implementation is also simple. They have no chronology or time zone, and consist solely of the millisecond duration.

Durations can be added to an instant, or to either end of an interval to change those objects. In datetime maths you could say:

      instant  +  duration  =  instant

Durations implement Comparable which compares the lengths of the two durations.

Using Durations in Joda-Time

Within Joda-Time a duration is represented by the ReadableDuration interface. There is one implementation of the interface provided:

  • Duration - An immutable implementation

The code can be used in various ways:

DateTime start = new DateTime(2004, 12, 25, 0, 0, 0, 0);
DateTime end = new DateTime(2005, 1, 1, 0, 0, 0, 0);

// duration in ms between two instants
Duration dur = new Duration(start, end);

// calc will be the same as end
DateTime calc = start.plus(dur);

Note that the interface ReadableDuration should not be used like the collections API. The interface only contains the core subset of the operations. Instead, you should usually refer directly to the implementation class in your APIs.

Directionality

Joda-Time durations can be negative. For example, the duration between 14:00 and 15:00 on the same day is 1 hour (PT1H), but the duration between 15:00 and 14:00 is minus 1 hour (PT-1H).

Negative durations will affect the results of comparisons. The equals, hashCode, compareTo, isLongerThan, isShorterThan and isEqualTo methods all take the sign of the duration into account. As such, a duration of minus 2 hours (PT-2H) is shorter than a duration of 1 hour (PT1H).

The Duration class has an abs method that will convert a negative duration to a position one if desired.

Nulls

Joda-Time defines a null duration as zero length. Thus, when a method is defined as taking a ReadableDuration, passing null in will be the same as passing in a zero length duration.

Back to top

Version: 2.12.7. Last Published: 2024-04-15.

Reflow Maven skin.