w3resource

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


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

Sample Solution:

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 5 years, 5 months and 20 days old

N.B.: The result may varry for your system date and time.

Flowchart:

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

For more Practice: Solve these Related Problems:

  • Write a Java program to calculate the difference in years, months, and days between two specified dates.
  • Write a Java program to compute and display the precise period between two dates using the Period class.
  • Write a Java program to compare two dates and output the difference in a "Y years, M months, D days" format.
  • Write a Java program to determine the elapsed time between two dates and express it in years, months, and days.

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to convert a string to date.
Next: Write a Java program to compute the difference between two dates (Hours, minutes, milli, seconds and nano).

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.