Comparing Two Dates - Java Date Time

Java examples for Date Time:Local Date Time

Introduction

Use one of the compareTo() methods that are part of the Date-Time API classes.

Demo Code

import java.time.LocalDate;
import java.time.Month;

public class Main {

  public static void main(String[] args) {
    LocalDate ldt1 = LocalDate.of(2000, Month.NOVEMBER, 11);
    LocalDate ldt2 = LocalDate.now();
    int comparison = ldt1.compareTo(ldt2);
    if (comparison > 0) {
      System.out.println(ldt1 + " is after " + ldt2);
    } else if (comparison < 0) {
      System.out.println(ldt1 + " is before " + ldt2);
    } else {//from   w w  w  .j  a  v  a  2s.c  o  m
      System.out.println(ldt1 + " is equal to " + ldt2);
    }

    if (ldt1.isAfter(ldt2)) {
      System.out.println(ldt1 + " is after " + ldt2);
    } else if (ldt1.isBefore(ldt2)) {
      System.out.println(ldt1 + " is before " + ldt2);
    } else if (ldt1.isEqual(ldt2)) {
      System.out.println(ldt1 + " is equal to " + ldt2);
    }

  }
}

Result


Related Tutorials