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.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 = 2021-10-29T07:30:29.811+08:00/2021-12-29T07:30:29.811+08:00
Start    = 2021-10-29T07:30:29.811+08:00
End      = 2021-12-29T07:30:29.811+08:00
Days     = 61
Hours    = 1464
Minutes  = 87840
Seconds  = 5270400
Interval = 2021-10-29T07:30:29.811+08:00/2022-01-29T07:30:29.811+08:00
Duration = PT7948800S
Days     = 92
Hours    = 2208
Minutes  = 132480
Seconds  = 7948800

Maven Dependencies

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.12.7</version>
</dependency>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.