Java 8 LocalDate Example program to find difference between two dates

Published by admin on

Write a program to find difference between two dates in Java 8 :

In this example , we will learn how to find difference between two dates in Java 8. Date difference is required to find the age of a person , to find how many days/months/years for a specific date etc. In this tutorial, I will show you how to find the difference between two dates in Java 8. Java 8 introduced one new class called ‘LocalDate’ . We are going to use one method of this class to find out the difference :

1. First convert both dates to ‘LocalDate’ objects
2. Now get the difference between these two dates usng ‘Period.between(firstdate,seconddate)’ method.
3. This method returns a ‘Period’ object. Use this object to print out the result.
4. To print years difference, use ‘getYears()’ , for months use ‘getMonths()’ and for days use ‘getDays()’

Example Program :

 * Copyright (C) 2017 codevscolor
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * See the License for the specific language governing permissions and
 * limitations under the License.

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

 * Example class
public class ExampleClass {

    //utility method to print a string
    static void print(String value) {

    public static void main(String[] args) {
        LocalDate firstDate = LocalDate.of(2015, 5, 12);
        LocalDate secondDate = LocalDate.of(2017, 8, 11);

        //find time between two dates
        Period period = Period.between(firstDate, secondDate);

        //get years
        print("Years : " + period.getYears());

        //get months
        print("Months : " + period.getMonths());

        //get days
        print("Days : " + period.getDays());


Output :

Years : 2
Months : 2
Days : 30

You can also modify this program to get the inputs from the user.

Categories: java

Leave a Reply

Your email address will not be published. Required fields are marked *