How do I use java.time.Period class?

java.time.Period is a class that represents a quantity or amount of time in terms of years, months, and days. Here’s a brief guide on how to use it:

1. Creating a Period instance

The Period class provides several static methods named of() and between() to create an instance. To create Period of 1 year, 2 months, and 3 days:

Period period = Period.of(1, 2, 3);

Or you can create a Period using LocalDate:

LocalDate start = LocalDate.of(2020, Month.JANUARY, 1);
LocalDate end = LocalDate.of(2023, Month.MARCH, 31);
Period period = Period.between(start, end);

2. Retrieving Years, Months, and Days

Use the getDays(), getMonths(), and getYears() methods to get the number of days, months, and years in the Period.

int days = period.getDays();
int months = period.getMonths();
int years = period.getYears();

3. Adding/subtracting Period to/from a LocalDate

The LocalDate.plus() or LocalDate.minus() methods can be used to add or subtract a Period from a LocalDate.

LocalDate ld = LocalDate.of(2021, Month.JULY, 1);
Period period = Period.of(1, 2, 3);
LocalDate newDate = ld.plus(period);

In this case, newDate will be 1 year, 2 months, and 3 days after July 1, 2021.

4. Mixing units of time

You can use plusDays(), plusMonths(), or plusYears() to add to a Period.

Period period = Period.of(1, 2, 3);
Period newPeriod = period.plusDays(10);

The newPeriod will then be 1 year, 2 months, and 13 days.

How do I use plus and minus method in the Java Date-Time API?

In the Java Date-Time API, the plus and minus methods can be used to calculate and modify dates, times, date/times, and durations.

Each temporal class (LocalDate, LocalTime, LocalDateTime, and Duration) includes these methods.

Here’s a basic example using the LocalDate class:

package org.kodejava.datetime;

import java.time.LocalDate;

public class PlusMinusExample {
    public static void main(String[] args) {
        LocalDate date = LocalDate.now();

        // Calculate the date 5 days into the future
        LocalDate futureDate = date.plusDays(5);
        System.out.println("Date five days in the future: " + futureDate);

        // Calculate the date 5 days in the past.
        LocalDate pastDate = date.minusDays(5);
        System.out.println("Date five days in the past: " + pastDate);
    }
}

Output:

Date five days in the future: 2024-01-22
Date five days in the past: 2024-01-12

You can also use plusWeeks, plusMonths, plusYears, minusWeeks, minusMonths, minusYears methods in a similar manner to add or subtract the respective time period.

Note: All the datetime manipulation methods return a new instance of the date/time object; they do not modify the original object because the classes are immutable.

The plus() and minus() methods in the Java Date-Time API offer finer control over date-time arithmetic by allowing you to add or subtract different types of date-time units such as days, months, or years.

The plus() method is used to add specific time units to a date or time, while the minus() method is used to subtract specific time units.

Here’s an example:

package org.kodejava.datetime;

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

public class PlusMinusOtherExample {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();

        // 1 year, 2 months, and 3 days.
        Period periodToAdd = Period.of(1, 2, 3);
        LocalDate futureDate = today.plus(periodToAdd);
        System.out.println("Date after adding a period: " + futureDate);

        // 2 years, 4 months, and 6 days.
        Period periodToSubtract = Period.of(2, 4, 6);
        LocalDate pastDate = today.minus(periodToSubtract);
        System.out.println("Date after subtracting a period: " + pastDate);
    }
}

The Period class is part of the Java Date-Time API and is used to represent a quantity of time in terms of years, months, and days.

Remember, you can create a Period using the Period.of(int years, int months, int days) method, where years, months, and days are the specific units of time to be represented.

Here are examples using LocalTime and LocalDateTime:

package org.kodejava.datetime;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

public class PlusMinusTime {
    public static void main(String[] args) {
        // Creating a LocalTime object and adding/subtracting hours, minutes, seconds
        LocalTime time = LocalTime.now();

        LocalTime futureTime = time.plus(2, ChronoUnit.HOURS);
        System.out.println("Time after two hours: " + futureTime);

        LocalTime pastTime = time.minus(30, ChronoUnit.MINUTES);
        System.out.println("Time 30 minutes ago: " + pastTime);

        // Creating a LocalDateTime object and adding/subtracting days, months, years
        LocalDateTime dateTime = LocalDateTime.now();

        LocalDateTime futureDateTime = dateTime.plus(1, ChronoUnit.YEARS);
        System.out.println("Date and Time one year into the future: " + futureDateTime);

        LocalDateTime pastDateTime = dateTime.minus(2, ChronoUnit.MONTHS);
        System.out.println("Date and Time two months ago: " + pastDateTime);

        // You can also use plus or minus Days, Weeks, Months, Years directly
        LocalDateTime exactDateTimeFuture = dateTime.plusDays(1).plusWeeks(1).plusMonths(1).plusYears(1);
        System.out.println("Date and Time after one day, week, month, and year: " + exactDateTimeFuture);
    }
}

Note that when we are adding/subtracting units like hours, minutes, and seconds, we use java.time.temporal.ChronoUnit. When adding/subtracting days, weeks, months, and years, we use directly plusDays or minusDays and so on.

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

How do I calculate difference between two dates?

In this example you’ll learn how to use the java.time.Period class (from Java 8) to calculate difference between two dates. Using Period.between() method will give us difference between two dates in years, months and days period.

Beside using the Period class, we also use the ChronoUnit enum to calculate difference between two dates. We use the ChronoUnit.YEARS, ChronoUnit.MONTHS and ChronoUnit.DAYS and call the between() method to get the difference between two dates in years, months and days.

Let’s see an example below.

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.Month;
import java.time.Period;
import java.time.temporal.ChronoUnit;

public class DateDifference {
    public static void main(String[] args) {
        LocalDate birthDate = LocalDate.of(1995, Month.AUGUST, 17);
        LocalDate now = LocalDate.now();

        // Obtains a period consisting of the number of years, months and days
        // between two dates.
        Period age = Period.between(birthDate, now);
        System.out.printf("You are now %d years, %d months and %d days old.%n",
                age.getYears(), age.getMonths(), age.getDays());

        // Using ChronoUnit to calculate difference in years, months and days
        // between two dates.
        long years = ChronoUnit.YEARS.between(birthDate, now);
        long months = ChronoUnit.MONTHS.between(birthDate, now);
        long days = ChronoUnit.DAYS.between(birthDate, now);

        System.out.println("Diff in years  = " + years);
        System.out.println("Diff in months = " + months);
        System.out.println("Diff in days   = " + days);
    }
}

The result of our code snippet above are:

You are now 26 years, 2 months and 30 days old.
Diff in years  = 26
Diff in months = 314
Diff in days   = 9588