Comparing two Dates in Java with the use of after method

In this example we are going to compare two date objects in Java programming language.

Comparing two Dates in Java with the use of after method

In this example we are going to compare two date objects in Java programming language.

Comparing two Dates in Java with the use of after method

Comparing two Dates in Java with the use of after method

     

In  this example we are going to compare two date objects in Java programming language. For comparing the date objects we can use after() method of the java.util.Date class. The after() method returns boolean value according to date objects.

In CompareDateAfter class we have defined firstDate object and then we used the Thread.Sleep(1000) method to make thread sleep for 1 second. After one second we have created another object of date class called secondDate. Now in the program we have used after() method to compare the dates.

firstDate.after(secondDate);

  • firstDate.after(secondDate) will return true when firstDate is initialized after secondDate and
  • firstDate.after(secondDate) will return false when firstDate is initialized before secondDate

Here is the full example code of CompareDateAfter class as follows:

CompareDateAfter.java

import java.util.Date;
public class CompareDateAfter{

  public static void main(String[] args) {
 Date firstDate = new Date();
  try{
  Thread.sleep(1000);
  }catch(Exception e){
  }
  Date secondDate = new Date();
  System.out.println("FirstDate:="+firstDate);
  System.out.println("SecondDate:="+secondDate);
  if(firstDate.after(secondDate))  
  System.out.println("Second Date is initialized before First Date");
  else 
  System.out.println("Second Date is initialized after First Date");
  }
}

Output:


C:\DateExample>javac CompareDateAfter.java

C:\DateExample>java CompareDateAfter
FirstDate:=Wed Oct 08 18:01:14 GMT+05:30 2008
SecondDate:=Wed Oct 08 18:01:15 GMT+05:30 2008
Second Date is initialized after First Date

C:\DateExample>

Download Source Code