Java: Calculate the difference between two dates in days
Write a Java program to calculate the difference between two dates in days.
Sample Solution:
Java Code:
Sample Output:
Before JDK 8: Date/Calendar case: Tue Jan 01 07:15:13 UTC 2019 <-> Sun Mar 01 07:15:13 UTC 2020 Difference in milliseconds is: 36720000012 Difference in days is: 425 Starting with JDK 8: LocalDate case: 2019-01-01 <-> 2020-03-01 Difference as Period: 1y2m0d Difference in days is via between(): 425 Difference in months is via between(): 14 Difference in years is via between(): 1 Difference in days is via until(): 425 Difference in months is via until(): 14 Difference in years is via until(): 1 LocalDateTime case: 2019-01-01T22:15:15 <-> 2020-01-01T23:15:15 Difference in minutes without zone: 525660 Difference in hours without zone: 8761 ZonedDateTime case: Europe/Bucharest: 2019-01-01T22:15:15+02:00[Europe/Bucharest] <-> Australia/Perth: 2019-01-02T05:15:15+08:00[Australia/Perth] Difference in minutes with zone (same instant): 60 Difference in hours with zone (same instant): 1 Europe/Bucharest: 2019-01-01T22:15:15+02:00[Europe/Bucharest] <-> Australia/Perth: 2020-01-01T23:15:15+08:00[Australia/Perth] Difference in minutes with zone (not same instant): 525300 Difference in hours with zone: 8755
Flowchart:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous:Write a Java program to get seconds since 1970.
Next: Write a java program to convert String to date and time and vice a versa.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics