Period between() method in Java


The Period between two dates can be obtained using the between() method in the Period class in Java. This method requires two parameters i.e. the start date and the end date and it returns the Period between these two dates.

A program that demonstrates this is given as follows

Example

 Live Demo

import java.time.Period;
import java.time.LocalDate;
public class Demo {
   public static void main(String[] args) {
      LocalDate startDate = LocalDate.parse("2015-03-15");
      LocalDate endDate = LocalDate.parse("2019-05-20");
      System.out.println("The start date is: " + startDate);
      System.out.println("The end date is: " + endDate);
      Period p = Period.between(startDate, endDate);
      System.out.println("
The Period between the start and end date is : " + p);    } }

Output

The start date is: 2015-03-15
The end date is: 2019-05-20
The Period between the start and end date is : P4Y2M5D

Now let us understand the above program.

First the start date and end date is displayed. Then the Period between these two dates is obtained using the between() method and displayed. A code snippet that demonstrates this is as follows:

LocalDate startDate = LocalDate.parse("2015-03-15");
LocalDate endDate = LocalDate.parse("2019-05-20");
System.out.println("The start date is: " + startDate);
System.out.println("The end date is: " + endDate);
Period p = Period.between(startDate, endDate);
System.out.println("
The Period between the start and end date is : " + p);

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements