Doubt in compare to method
Hi,
I have two dates both are same.(ie. 2007-07-26 and 2007-07-26). I used the following code to compare that But it returns a negative value. So help me to resolve this problem
System.out.println(date1.compareTo(date2));
It prints the following result: -1 I couldn't find out actually what is the problem in that statement. So help me to resolve this.
Thanks in Advance,
Maheshwaran Devaraj
[430 byte] By [
mheshpmra] at [2007-11-27 11:48:58]

> So help me to resolve this.
The date values aren't equal. A java.util.Date object has millisecond precision (as mentioned), so "2007-07-26" doesn't contain enough information to tell you whether two dates are the same or not.
~
How are you actually creating the Date objects?
If you are creating the Date objects by using Calendar.getInstance().getTime()
then they will botht have different millisecond values and as such would not be equal.
But if you create them by using the deprecated methods of new Date(int year, int month, int day)
then they should be equal.
> But if you create them by using the deprecated
> methods of new Date(int year, int month, int
> day)
then they should be equal.
Yes... except that here, Date will add 1900 to year... All in part why those constructors are deprecated and shouldn't be used.
If you created or converted the date to java.sql.date then you will be able to check the date correctly . Check the below code:
import java.sql.Date;
import java.text.*;
public class TestDate {
public static void main(String args[]){
java.sql.Date c1 = java.sql.Date.valueOf("2007-07-26");
java.sql.Date c2 = java.sql.Date.valueOf("2007-07-26");
System.out.println(c1.compareTo(c2));
if (c1.equals(c2))
System.out.print(" same as ");
}
}