Java DateTime, Calendar Exercises: 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 (year, 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.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework