如何在Java 8中添加或减去日期?

新的Java 8java.time.LocalDate类提供了plus()和minus()方法,可以向LocalDate对象添加或从对象中减去一定量的周期。

期间使用java.time.Period类表示。要创建一个实例Period,我们可以使用of(),ofDays(),ofWeeks(),ofMonths()和ofYears()方法。

让我们来看一个使用class的plus()andminus()方法LocalDate在以下代码片段中进行加减的示例:

package org.nhooo.example.datetime;

import java.time.LocalDate;
import java.time.Period;

public class DateAddSubtract {
    public static void main(String[] args) {
        // 以天,周,月和年为单位创建时间段。
        Period p1 = Period.ofDays(7);
        Period p2 = Period.ofWeeks(2);
        Period p3 = Period.ofMonths(1);
        Period p4 = Period.ofYears(1);
        Period p5 = Period.of(1, 1, 7);

        // 获取当前日期,并使用以下命令在当前日期中添加一些句点 
        // plus()方法。
        LocalDate now = LocalDate.now();
        LocalDate date1 = now.plus(p1);
        LocalDate date2 = now.plus(p2);
        LocalDate date3 = now.plus(p3);
        LocalDate date4 = now.plus(p4);
        LocalDate date5 = now.plus(p5);

        // 打印出将一些期间添加到当前日期的结果。
        System.out.printf("Add some period to the date: %s%n", now);
        System.out.printf("Plus %7s = %s%n", p1, date1);
        System.out.printf("Plus %7s = %s%n", p2, date2);
        System.out.printf("Plus %7s = %s%n", p3, date3);
        System.out.printf("Plus %7s = %s%n", p4, date4);
        System.out.printf("Plus %7s = %s%n%n", p5, date5);

        // 使用minus()方法从日期中减去某个时间段。
        System.out.printf("Subtract some period from the date: %s%n", now);
        System.out.printf("Minus %7s = %s%n", p1, now.minus(p1));
        System.out.printf("Minus %7s = %s%n", p2, now.minus(p2));
        System.out.printf("Minus %7s = %s%n", p3, now.minus(p3));
        System.out.printf("Minus %7s = %s%n", p4, now.minus(p4));
        System.out.printf("Minus %7s = %s%n%n", p5, now.minus(p5));
    }
}

这是上面代码片段的结果:

Add some period to the date: 2016-01-29
Plus     P7D = 2016-02-05
Plus    P14D = 2016-02-12
Plus     P1M = 2016-02-29
Plus     P1Y = 2017-01-29
Plus P1Y1M7D = 2017-03-07

Subtract some period from the date: 2016-01-29
Minus     P7D = 2016-01-22
Minus    P14D = 2016-01-15
Minus     P1M = 2015-12-29
Minus     P1Y = 2015-01-29
Minus P1Y1M7D = 2014-12-22