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
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023
Thanks for the article, it helped me to implement a method getAge 🙂