How do I use the Interval class of Joda-Time?

This example show you how to use the org.joda.time.Interval class in Joda-Time. A time interval represents a period of time between two instants. Intervals are inclusive of the start instant and exclusive of the end. The end instant is always greater than or equal to the start instant.

package org.kodejava.example.joda;

import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.Interval;
import org.joda.time.Months;

public class IntervalDemo {
    public static void main(String[] args) {
        DateTime startDate = new DateTime();
        DateTime endDate = startDate.plus(Months.months(2));

        // Creates an interval from a start to an end instant.
        Interval interval = new Interval(startDate, endDate);
        System.out.println("Interval = " + interval);
        System.out.println("Start    = " + interval.getStart());
        System.out.println("End      = " + interval.getEnd());

        System.out.println("Days     = " + interval.toDuration().getStandardDays());
        System.out.println("Hours    = " + interval.toDuration().getStandardHours());
        System.out.println("Minutes  = " + interval.toDuration().getStandardMinutes());
        System.out.println("Seconds  = " + interval.toDuration().getStandardSeconds());

        // Add one more month to the interval
        interval = interval.withEnd(interval.getEnd().plusMonths(1));
        System.out.println("Interval = " + interval);

        // Gets the duration of this time interval
        Duration duration = interval.toDuration();
        System.out.println("Duration = " + duration);
        System.out.println("Days     = " + duration.getStandardDays());
        System.out.println("Hours    = " + duration.getStandardHours());
        System.out.println("Minutes  = " + duration.getStandardMinutes());
        System.out.println("Seconds  = " + duration.getStandardSeconds());
    }
}

Below is the result printed by our program:

Interval = 2017-02-16T15:37:19.746+08:00/2017-04-16T15:37:19.746+08:00
Start    = 2017-02-16T15:37:19.746+08:00
End      = 2017-04-16T15:37:19.746+08:00
Days     = 59
Hours    = 1416
Minutes  = 84960
Seconds  = 5097600
Interval = 2017-02-16T15:37:19.746+08:00/2017-05-16T15:37:19.746+08:00
Duration = PT7689600S
Days     = 89
Hours    = 2136
Minutes  = 128160
Seconds  = 7689600

Maven Dependencies

<!-- http://repo1.maven.org/maven2/joda-time/joda-time/2.9.7/joda-time-2.9.7.jar -->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.9.7</version>
</dependency>

Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply