Skip to Content

Compare two Java Date objects using compareTo method example

  1. /*
  2.   Compare two Java Date objects using compareTo method example.
  3.   This example shows how to compare two java Date objects using compareTo method of
  4.   java Date Class.
  5. */
  6.  
  7. import java.util.Date;
  8.  
  9. public class CompareDateUsingCompareToExample{
  10.  
  11.   public static void main(String[] args) {
  12.    
  13.     //create first date object
  14.     Date d1 = new Date();
  15.  
  16.     //make interval of 10 millisecond before creating second date object    
  17.     try{
  18.       Thread.sleep(10);
  19.     }catch(Exception e){
  20.     }
  21.    
  22.    
  23.     //create second date object
  24.     Date d2 = new Date();
  25.    
  26.     System.out.println("First Date : " + d1);
  27.     System.out.println("Second Date : " + d2);
  28.    
  29.     /*
  30.      Use compareTo method of java Date class to compare two date objects.
  31.      compareTo returns value grater than 0 if first date is after another date,
  32.      returns value less than 0 if first date is before another date and returns
  33.      0 if both dates are equal.
  34.     */
  35.    
  36.     int results = d1.compareTo(d2);
  37.    
  38.     if(results > 0)
  39.       System.out.println("First Date is after second");
  40.     else if (results < 0)
  41.       System.out.println("First Date is before second");
  42.     else
  43.       System.out.println("Both dates are equal");
  44.   }
  45. }
  46.  
  47. /*
  48. TYPICAL Output Would be
  49. First Date : Sun Sep 09 19:50:32 EDT 2007
  50. Second Date : Sun Sep 09 19:50:32 EDT 2007
  51. First Date is before second
  52. */