Saturday, November 21, 2009

Java : Compare two dates using Date or Calendar class

Many times while programming in java we need to compare two dates, below are the two methods can be used to compare 2 dates, it can be done using either Date class or Calendar class. Below both program produces same output.

Method 1 : Using Date class

/* CompareDate.java */

import java.util.*;
import java.text.*;

public class CompareDate
{
public static void main(String[] args)
{
String date1 = "10-11-2009";//any date

String date2 = "10-11-2009";//any date

SimpleDateFormat formatterDate = new SimpleDateFormat("dd-MM-yyyy");

Date d1 = null;
Date d2 = null;

try
{
d1 = formatterDate.parse(date1);
d2 = formatterDate.parse(date2);
}
catch (Exception e)
{
System.out.println("Parse Exception :"+e);
}


int results = d1.compareTo(d2);


if(results > 0)
{
System.out.println("d1 "+date1+" is greater than d2 "+date2);
}
else if (results < 0)
{
System.out.println("d1 "+date1+" is less than d2 "+date2);
}
else //results = 0
{
System.out.println("d1 "+date1+" is equal to d2 "+date2);
}
}
}



Method 2 : Using Calendar class

/* CompareDate.java */

import java.util.*;
import java.text.*;

public class CompareDate
{
public static void main(String[] args)
{
String date1 = "15-11-2009";//any date

String date2 = "11-11-2009";//any date

SimpleDateFormat formatterDate = new SimpleDateFormat("dd-MM-yyyy");

Date d1 = null;
Date d2 = null;

try
{
d1 = formatterDate.parse(date1);
d2 = formatterDate.parse(date2);
}
catch (Exception e)
{
System.out.println("Parse Exception :"+e);
}

Calendar ss=Calendar.getInstance();
Calendar ee=Calendar.getInstance();


ss.setTime(d1);
ee.setTime(d2);


if(d1.after(d2))
{
System.out.println("d1 "+date1+" is greater than d2 "+date2);
}
else if (d1.before(d2))
{
System.out.println("d1 "+date1+" is less than d2 "+date2);
}
else //d1.equals(d2)
{
System.out.println("d1 "+date1+" is equal to d2 "+date2);
}
}
}

No comments:

Post a Comment