Java Period

The Java Period class is an immutable and thread-safe class that represents quantity or amount of time in terms of years, months and days.

How to use

A period is modeled as a designated period that, individual parts of the period can be negative. Try the following examples to better understand –

AddTo example

The following example program shows how you can add the local date into the period and get the new resultant date.

import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.Temporal;

public class OffsetTimeExample1 {

    public static void main(String[] args) {

        // Create instance of Period
        Period period = Period.ofDays(10);

        // AddTo current date
        Temporal temp = period.addTo(LocalDate.now());
        System.out.println(temp);
    }
}

Add/Subtract days example

The following example program shows how you can plus/minus days in the period.

import java.time.Period;

public class PeriodExample2 {

    public static void main(String[] args) {

        // Create instance of Period
        Period period = Period.ofDays(10);
        System.out.println(period.getDays());

        // Add 5 more days
        period = period.plusDays(5);
        System.out.println(period.getDays());

        // Subtract 10 days
        period = period.minusDays(10);
        System.out.println(period.getDays());
    }
}

Period of example

The following example program shows how you can use of() static function to create an instance of Period.

import java.time.Period;

public class PeriodExample3 {

    public static void main(String[] args) {

        // Create instance of Period
        Period period = Period.of(2019, 5, 10);

        // Print it
        System.out.println(period);

    }
}