Java – Date Comparison

This example shows you how to do date comparison in Java.

import java.util.Calendar;
import java.util.Date;

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

    // date1 is today
    Calendar cal = Calendar.getInstance();
    Date date1 = cal.getTime();
		
    // date2 is yesterday
    cal.add(Calendar.DATE, -1);
    Date date2 = cal.getTime();
		
    // Date comparison using compareTo
    if(date1.compareTo(date2) < 0) {
      // return -1 if date1 is less than date2
      System.out.println("Date1 is less than date2");  
    } else if(date1.compareTo(date2)>0) {
      // return 1 if date1 is greater than date2
      System.out.println("Date1 is greater than date2");  
    } else {
      // return 0 if date1 is equal to date2
      System.out.println("Date1 is equal to date2");  
    }
		
    // Date comparison using before(), after() and equals()
    if(date1.before(date2)) {
      // return -1 if date1 is less than date2
      System.out.println("Date1 is less than date2");  
    } else if(date1.after(date2)) {
      // return 1 if date1 is greater than date2
      System.out.println("Date1 is greater than date2");  
    } else if (date1.equals(date2)) {
      // return 0 if date1 is equal to date2
      System.out.println("Date1 is equal to date2");  
    }
  }
}

 

Done =)

Reference: EasyWayServer – How to compare date in JAVA

2 thoughts on “Java – Date Comparison”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.