Java如何在Joda-Time中进行日期计算?
使用Joda-Time库可以简化日期计算过程。例如,我们可以轻松地增加或减少几天,几周,几个月或一年。此操作有加减法。例如,如果您要添加9个星期的日期对象,则可以执行date.plusWeeks(9)。
package org.nhooo.example.joda; import org.joda.time.LocalDate; public class DateCalculationDemo { public static void main(String[] args) { //创建我们要执行的LocalDate实例 //一些日期计算。 LocalDate date = new LocalDate(2019, 7, 1); System.out.println("Date = " + date); //将天,周,月,年值添加到日期对象中。 System.out.println("plusDays(10) = " + date.plusDays(10)); System.out.println("plusWeeks(9) = " + date.plusWeeks(9)); System.out.println("plusMonths(2) = " + date.plusMonths(2)); System.out.println("plusYears(1) = " + date.plusYears(1)); //从日期对象中减去天,周,月,年值。 System.out.println("minusDays(10) = " + date.minusDays(10)); System.out.println("minusWeeks(9) = " + date.minusWeeks(9)); System.out.println("minusMonths(2) = " + date.minusMonths(2)); System.out.println("minusYears(1) = " + date.minusYears(1)); } }
上面程序的输出是:
Date = 2019-07-01 plusDays(10) = 2019-07-11 plusWeeks(9) = 2019-09-02 plusMonths(2) = 2019-09-01 plusYears(1) = 2020-07-01 minusDays(10) = 2019-06-21 minusWeeks(9) = 2019-04-29 minusMonths(2) = 2019-05-01 minusYears(1) = 2018-07-01
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>