Compare Dates in Java

JavaObject Oriented ProgrammingProgramming

To compare dates in Java, use the compareTo() method. The syntax is as follows −

public int compareTo(Date anotherDate)

Here, anotherDate is the date to be compared with. The return value is 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.

Example

Let us now see an example to compare dates −

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String[] args) {
      // create two dates
      Date date = new Date(19, 3, 25);
      Date date2 = new Date(19, 9, 12);
      // make 3 comparisons with them
      int comparison = date.compareTo(date2);
      int comparison2 = date2.compareTo(date);
      int comparison3 = date.compareTo(date);
      // print the results
      System.out.println("Comparison Result:" + comparison);
      System.out.println("Comparison2 Result:" + comparison2);
      System.out.println("Comparison3 Result:" + comparison3);
   }
}

Output

Comparison Result:-1
Comparison2 Result:1
Comparison3 Result:0

Example

We can also check whether two dates are equals based on millisecond difference using equals() method −

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String[] args) {
      Date date = new Date(70, 1, 10);
      Date date2 = new Date(70, 1, 10);
      boolean check = date.equals(date2);
      System.out.println("Dates are equal:" + check);
   }
}

Output

Dates are equal:true
raja
Published on 26-Sep-2019 16:50:05
Advertisements