How do I use the Interval class of Joda Time?
Date: 2012-02-28. Category: org.joda.time examples. Hits: 2K time(s).
This example show you how to use the org.joda.time.Interval class in Joda. An interval object represent an interval of time from one millisecond instant to another 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());
//
// 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);
}
}
Below is the result printed by our program:
Interval = 2012-02-28T17:53:36.997/2012-04-28T17:53:36.997 Start = 2012-02-28T17:53:36.997+08:00 End = 2012-04-28T17:53:36.997+08:00 Interval = 2012-02-28T17:53:36.997/2012-05-28T17:53:36.997 Duration = PT7776000S