Java Data Type How to - Check if a date is before or after another dates in Java 8








Question

We would like to know how to check if a date is before or after another dates in Java 8.

Answer

import static java.time.temporal.ChronoUnit.DAYS;
/*ww  w  .  jav a2 s .c o m*/
import java.time.LocalDate;

public class Main {
  public static void main(String[] argv) {
    LocalDate today = LocalDate.now();
    LocalDate tomorrow = today.plusDays(1);
    LocalDate yesterday = today.minus(1, DAYS);

    if (tomorrow.isAfter(today)) {
      System.out.println("Tomorrow comes after today");
    }

    if (yesterday.isBefore(today)) {
      System.out.println("Yesterday is day before today");
    }
  }
}

The code above generates the following result.