Java: Compute the difference between two dates (year, months, days)
Java DateTime, Calendar: Exercise-30 with Solution
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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/datetime/java-datetime-exercise-30.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics