Monday 22 April 2013

Compare Dates In Java


This is one of the way for comparing Dates in Java using Date.compareTo() method.

Date.compareTo():
If return value is 0 - argument Date is equal to this Date
If return value is less than 0 (-ve) - this Date is before the Date argument
If return value is greater than 0 (+ve) - this Date is after the Date argument





Following is the example:

package testapp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * @author naveen.k
 */
public class CompareDates {
    public static void main(String[] args) {
        try{
            // Take SimpleDateFormat for choosing the format you need
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            // Parse the dates accordingly
        Date objDate1 = sdf.parse("2013-01-23");
        Date objDate2 = sdf.parse("2013-04-23");

            // Its nothing doing with comparing the dates....
            // It is provided only to show the Date in string format
        String firstDate = sdf.format(objDate1);
        String secondDate = sdf.format(objDate2);

            /*
             * the 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.
             */
        if(objDate1.compareTo(objDate2)>0)
        System.out.println(firstDate + " is after to " + secondDate);
        else if(objDate1.compareTo(objDate2)<0)
        System.out.println(firstDate + " is before to " + secondDate);
        else
        System.out.println("Both Dates are equal");        

    }catch(ParseException ex){
    ex.printStackTrace();
    }
    }
}

1 comment:

  1. Very useful information that you have shared and it is very useful to me. Thanks for sharing the information with us.
    kindle mobi formatting services

    ReplyDelete