All Articles

Java 8 – How to calculate days between two dates ?

With Java 8, if we use LocalDate and LocalDateTime to represents dates, calculating the difference between two dates is more intuitive and simple.

Using java.time

Case with LocalDate :

LocalDate now = LocalDate.now();  
LocalDate twoDaysBehind = now.minusDays(2);
 
Period period = Period.between(twoDaysBehind, now);  
long result = period.getDays();  
System.out.println(result); //output : 2 

Dates as LocalDateTime

LocalDateTime nowWithTime = LocalDateTime.now();  
LocalDateTime threeDaysBehind = nowWithTime.minusDays(3);  

Duration duration = Duration.between(threeDaysBehind, nowWithTime);  
result = duration.toDays();  
System.out.println(result); //output : 3 

Using java.time.temporal.ChronoUnit

Case with LocalDate :

LocalDate now = LocalDate.now();  
LocalDate twoDaysBehind = now.minusDays(2);  
   
long result = ChronoUnit.DAYS.between(twoDaysBehind.atStartOfDay(), now.atStartOfDay());
System.out.println(result); //output : 2 

Dates as LocalDateTime

LocalDateTime nowWithTime = LocalDateTime.now();  
LocalDateTime threeDaysBehind = nowWithTime.minusDays(3);  
     
result = ChronoUnit.DAYS.between(threeDaysBehind, nowWithTime);
System.out.println(result); //output : 3 
     

References

Cookie settings

This website uses cookies to ensure you get the best experience on our website. Learn more

Save settings

Necessary cookies

Some cookies are required to provide core functionality. The website won't function properly without these cookies and they are enabled by default.

Analytical cookies

Analytical cookies help us improve our website by collecting and reporting information on its usage.

Marketing cookies

Marketing cookies are used to track visitors across websites to allow publishers to display relevant ads.