Java如何使用Joda-Time的Interval类?
本示例向您展示如何org.joda.time.Interval在Joda-Time中使用该类。时间间隔表示两个时刻之间的时间段。间隔包括开始时刻,不包括结束。结束时刻始终大于或等于开始时刻。
package org.nhooo.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)); //创建从开始到结束瞬间的间隔。 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()); //将间隔再增加一个月 interval = interval.withEnd(interval.getEnd().plusMonths(1)); System.out.println("Interval = " + 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()); } }
以下是我们程序打印的结果:
Interval = 2019-07-22T13:42:04.763+08:00/2019-09-22T13:42:04.763+08:00 Start = 2019-07-22T13:42:04.763+08:00 End = 2019-09-22T13:42:04.763+08:00 Days = 62 Hours = 1488 Minutes = 89280 Seconds = 5356800 Interval = 2019-07-22T13:42:04.763+08:00/2019-10-22T13:42:04.763+08:00 Duration = PT7948800S Days = 92 Hours = 2208 Minutes = 132480 Seconds = 7948800
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=joda-time/joda-time/2.10.3/joda-time-2.10.3.jar --> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.10.3</version> </dependency>