Abel Jojo
Abel Jojo

Reputation: 758

Java date compareTo failed

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);
}

}

Upvotes: 1

Views: 1997

Answers (3)

Kishor Sharma
Kishor Sharma

Reputation: 599

CompareTo compares the time values (millisecond offsets from the Epoch) represented by two Calendar objects. If you print both cal1 and cal2 with formating you will see the time difference.

System.out.println(cal1.getTime());
System.out.println(cal2.getTime());

This will show you exact time holding by two calender instance.

Upvotes: 1

Harish
Harish

Reputation: 2512

compareTo is the function gives you the solution... You can just look at here.

http://www.java-examples.com/compare-two-java-date-objects-using-compareto-method-example

Upvotes: 1

Andreas Dolk
Andreas Dolk

Reputation: 114767

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.

Upvotes: 3

Related Questions