How do I add or subtract date in Java 8?

The new Java 8 java.time.LocalDate class provide a plus() and minus() methods to add or subtract an amount of period to or from the LocalDate object.

The period is represented using the java.time.Period class. To create an instance of Period we can use the of(), ofDays(), ofWeeks(), ofMonths() and ofYears() methods.

Let’s see an example using the plus() and minus() method of LocalDate class to add and subtract in the code snippet below:

package org.kodejava.datetime;

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

public class DateAddSubtract {
    public static void main(String[] args) {
        // Create periods in days, weeks, months and years.
        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);

        // Obtains current date and add some period to the current date using 
        // the plus() method.
        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);

        // Print out the result of adding some period to the current date.
        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);

        // Subtract some period from the date using the minus() method.
        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));
    }
}

And here are the result of the code snippet above:

Add some period to the date: 2021-11-16
Plus     P7D = 2021-11-23
Plus    P14D = 2021-11-30
Plus     P1M = 2021-12-16
Plus     P1Y = 2022-11-16
Plus P1Y1M7D = 2022-12-23

Subtract some period from the date: 2021-11-16
Minus     P7D = 2021-11-09
Minus    P14D = 2021-11-02
Minus     P1M = 2021-10-16
Minus     P1Y = 2020-11-16
Minus P1Y1M7D = 2020-10-09
Wayan

Leave a Reply

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