Find Difference Between Two Dates In Java 8

Many times we need to find difference between two dates in Java. Before Java 8 we need to rely on third party libraries like Joda-Time but with Java 8 we are no longer dependent on third party libraries.

Java 8 provides a way to find difference between two dates in terms of Days, Months, Years, Hours, Minutes and Seconds Units.

So lets see how to find difference between two dates using Java 8.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;

public class DateDifference {

 public static void main(String[] args) {
  LocalDate nowDate = LocalDate.now();
  
  LocalDate pastDate = LocalDate.of(2018, 12, 31);
  
  System.out.println(Period.between(pastDate, nowDate).getDays());
  
  System.out.println(ChronoUnit.YEARS.between(pastDate, nowDate));
  
  LocalDateTime nowDateTime = LocalDateTime.now();
  
  LocalDateTime pastDateTime = LocalDateTime.of(2019, 12, 31, 12, 12, 12);
  
  System.out.println(Duration.between(pastDateTime, nowDateTime).getSeconds());
  
  System.out.println(ChronoUnit.HOURS.between(pastDateTime, nowDateTime));
 }

}


0 Comments