Even if the date is equal or not equal CompareTo failes. It just print 1.
CompareTo doesn't return 0 on comparison. !!
this silly code squeeze my head. Hey friends where i made foul?
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class date {
public static void main (String args[]) throws ParseException
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date expiry = sdf.parse("2012-11-09");
System.out.println(sdf.format(expiry));
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(expiry);
cal1.add(Calendar.DATE, -2);
System.out.println(sdf.format(cal1.getTime()));
System.out.println(sdf.format(cal2.getTime()));
int j = cal1.compareTo(cal2);
System.out.println("The result is :" + j);
}
}
compareTo
tells the truth. You've just hidden the hours, minutes, seconds and milliseconds from the output.
The expiry
date is set to a day at 00:00:00.0000
(the very first millisecond of that day) while cal2
still carries the actual time.