Java.util.Date.compareTo() Method



The java.util.Date.compareTo(Date anotherDate) method compares two Dates.


Following is the declaration for java.util.Date.compareTo() method

public int compareTo(Date anotherDate)


anotherDate − date to be compared to

Return Value

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.


NullPointerException − if anotherDate is null.


The following example shows the usage of java.util.Date.compareTo() method.

Live Demo
package com.tutorialspoint;

import java.util.*;

public class DateDemo {
   public static void main(String[] args) {

      // create two dates
      Date date = new Date(98, 5, 21);
      Date date2 = new Date(99, 1, 9);

      // 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);

Let us compile and run the above program, this will produce the following result −

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