203

In Joda-Time 2, what is the difference between the three kinds of time spans:

  • Period
  • Interval
  • Duration

    1. Why do we need three classes?

    2. Which one performs better?

    3. Why is dividing a Period or Duration or Interval instance not implemented? E.g. p = p.divideBy(2);

1
  • 3
    Note that this date-time terminology has not been standardized (yet). The ISO-8601 standard’s idea of a duration is what Joda-Time considers a Period. A proposal to standardize such terminology has been raised but not yet accomplished. Jul 2, 2015 at 22:16

3 Answers 3

259

3 classes are needed because they represent different concepts so it is a matter of picking the appropriate one for the job rather than of relative performance. From the documentation with comments added by me in italics:


An interval in Joda-Time represents an interval of time from one millisecond instant to another instant. Both instants are fully specified instants in the datetime continuum, complete with time zone. Specific times are defined e.g. this might be the interval between 22nd March 2010 20:00:00 GMT and 23rd March 2010 09:00:00 GMT.

A duration in Joda-Time represents a duration of time measured in milliseconds. The duration is often obtained from an interval. i.e. we can subtract start from end of an interval to derive a duration

A period in Joda-Time represents a period of time defined in terms of fields, for example, 3 years 5 months 2 days and 7 hours. This differs from a duration in that it is inexact in terms of milliseconds. A period can only be resolved to an exact number of milliseconds by specifying the instant (including chronology and time zone) it is relative to. e.g. consider the period of 1 year, if we add this to January 1st we will always arrive at the next January 1st but the duration will depend on whether the intervening year is a leap year or not. Similarly if we add 1 month to the 1st of a month then we will arrive at the 1st of the next month but the duration (in milliseconds) will vary based on the month in question


For question 3, A specific method to divide a duration is not really needed because we can always get the number of milliseconds from the duration as a long (using getMillis()), divide it and construct a new duration (using new Duration(long duration)).

Dividing a period doesn't really have a real meaning based on the definition of a period above. e.g. what is half a month? (its length would depend on which month).

2
  • 1
    I think dividing a period does have a meaning - half a month is still a valid unit of time, but it requires a start date to know exactly how long (in exactly the same way a month is a valid period).
    – hadley
    May 7, 2011 at 13:21
  • 11
    Jodatime considers a period to be a tuple of INTEGER valued fields, it doesnt allow fractional values. That's consistent with common (civil) use. Practically nobody in common life considers that '1 month and 10 days' divided by two is 'half a month and 5 days'. If you need to do that division, you probably want to go to a duration (physical time).
    – leonbloy
    May 7, 2011 at 13:58
94

To add to mikej's answer:

A Joda-Time duration is a "physical" time interval; eg:

12000 milliseconds <-- this is a duration

A Joda-Time interval is actually a pair of instants (start instant - end instant). An instant is, again, a "physical" concept, a point in the timeline. Eg (just a possible notation):

(2010/3/3 19:00:00.000 UTC ; 2010/3/3 20:00:00.000 UTC) <-- this is an interval

An interval, then, can be converted to a duration, but not the reverse.

Consider these two intervals:

I1=(2010/3/3 19:00:00.000 UTC ; 2010/3/3 20:00:00.000 UTC)

I2=(2010/3/3 21:00:00.000 UTC ; 2010/3/3 22:00:00.000 UTC)

As intervals, I1 and I2 are different, because the end-points are different; but if I convert them to durations, I get the same thing: 3600000 milliseconds.

(Math analogy: the intervals [10,12] and [95,97] are different intervals, but they have the same length: "interval length" maps to duration).

Finally, a period is a lapse of "civil time", expressed as a number of months, days, hours, etc. It does not -by itself- represent a "physical" interval, hence it can't be directly converted to a duration (months have variable lengths...).

This answers question 3: you can only divide by two a physical time (a duration).

7
  • Four months divided by two would be two months. Why isn't that valid?
    – hadley
    May 7, 2011 at 13:22
  • 1
    How would you compute '2 Months; 18 days' divided by 3? You cant get a consistent definition to that kind of operation.
    – leonbloy
    May 7, 2011 at 13:40
  • 3
    I think you can get a consistent definition, but you have to think about it as 1/3 of the time of "2 months and 18 days". You won't be able to work out exactly what it is until you convert it to a interval. Just because JODA doesn't support it doesn't mean it's invalid.
    – hadley
    May 7, 2011 at 16:19
  • @hadley There isn't a civil definition for "one third of a day". E.g. no contract is valid for one third of a day.
    – ipavlic
    Apr 19, 2012 at 8:42
  • 5
    @Richard Watson Days can be 23, 24 or 25 hours long, because of DST. Therefore "one third of a day starting from..." is valid, but just "one third" is not.
    – ipavlic
    Jul 15, 2012 at 0:06
4

java.time

The existing answers are correct. The purpose of this answer is to inform about the state of Joda-Time API and to introduce Duration and Period provided by the modern date-time API.

In March 2014, Java 8 introduced java.time, the modern date-time API. Since then, it's been recommended to switch from the legacy date-time API from the standard library as well as the Joda-Time to java.time API. Shown below is a notice on the Joda-Time Home Page:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Duration

Duration is defined as "A time-based amount of time, such as '34.5 seconds'". With Java-9 some more convenience methods were introduced to this class.

Demo:

public class Main {
    public static void main(String[] args) {
        Duration duration = Duration.between(LocalTime.now(), LocalTime.of(18, 0));
        // Default format
        System.out.println(duration);

        // Custom format
        // ####################################Java-8####################################
        String formattedDuration = String.format("%d hour(s) %d minute(s) %d second(s)", duration.toHours(),
                duration.toMinutes() % 60, duration.toSeconds() % 60);
        System.out.println(formattedDuration);
        // ##############################################################################

        // ####################################Java-9####################################
        formattedDuration = String.format("%d hour(s) %d minute(s) %d second(s)", duration.toHoursPart(),
                duration.toMinutesPart(), duration.toSecondsPart());
        System.out.println(formattedDuration);
        // ##############################################################################
    }
}

Output from a sample run:

PT1H2M29.900686S
1 hour(s) 2 minute(s) 29 second(s)
1 hour(s) 2 minute(s) 29 second(s)

Online Demo

Period is defined as "A date-based amount of time in the ISO-8601 calendar system, such as '2 years, 3 months and 4 days'".

Demo:

public class Main {
    public static void main(String[] args) {
        Period period = LocalDate.now().until(LocalDate.of(2025, Month.OCTOBER, 18));
        // Default format
        System.out.println(period);

        // Formatted output
        String formattedPeriod = String.format("%d year(s) %d month(s) %d day(s)", period.getYears(),
                period.getMonths(), period.getDays());
        System.out.println(formattedPeriod);
    }
}

Output from a sample run:

P1Y6M25D
1 year(s) 6 month(s) 25 day(s)

Online Demo

Java standard library does not have a class called, Interval. As Annonymous has mentioned, the ThreeTen Extra library provide classes like Interval, LocalDateRange and PeriodDuration which are worth looking at.

Learn more about the modern Date-Time API from Trail: Date Time.

1
  • 1
    Well explained answer with online demos
    – anubhava
    Apr 4 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.