w3resource logo


Java Programming Exercies

Java DateTime, Calendar Exercises: Compute the difference between two dates (year, months, days)

Secondary Nav

Java DateTime, Calendar : Exercise-30 with Solution

Write a Java program to compute the difference between two dates (year, months, days).

Java Code:

import java.time.*;
import java.util.*;

public class Exercise1 {  
   public static void main(String[] args)
    {
        LocalDate pdate = LocalDate.of(2012, 01, 01);
        LocalDate now = LocalDate.now();
 
        Period diff = Period.between(pdate, now);
 
     System.out.printf("\nDifference is %d years, %d months and %d days old\n\n", 
                    diff.getYears(), diff.getMonths(), diff.getDays());
  }
}

Sample Output :

Difference is 4 years, 8 months and 18 days old 

Java Practice online:

import java.time.*;
import java.util.*;

public class Exercise30 {  
   public static void main(String[] args)
    {
        LocalDate pdate = LocalDate.of(2012, 01, 01);
        LocalDate now = LocalDate.now();
 
        Period diff = Period.between(pdate, now);
     System.out.println();  
     System.out.printf("\nDifference is %d years, %d months and %d days old\n\n", 
                    diff.getYears(), diff.getMonths(), diff.getDays());
	System.out.println();				
  }
}



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program