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