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]
# 1

You create the 2 Dates how? Maybe the milliseconds are not the same, and therefore the date isn't the same.

bsampieria at 2007-7-29 18:22:24 > top of Java-index,Java Essentials,Java Programming...
# 2

> 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.

~

yawmarka at 2007-7-29 18:22:24 > top of Java-index,Java Essentials,Java Programming...
# 3

I used that both dates as a SQL date.

mheshpmra at 2007-7-29 18:22:24 > top of Java-index,Java Essentials,Java Programming...
# 4

What is the superclass of java.sql.Date? Stop making assumptions.

bsampieria at 2007-7-29 18:22:24 > top of Java-index,Java Essentials,Java Programming...
# 5

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.

c0demonk3ya at 2007-7-29 18:22:24 > top of Java-index,Java Essentials,Java Programming...
# 6

> 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.

bsampieria at 2007-7-29 18:22:24 > top of Java-index,Java Essentials,Java Programming...
# 7

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

}

}

java_queena at 2007-7-29 18:22:24 > top of Java-index,Java Essentials,Java Programming...
# 8

Thanks I did it well using the above code. Thank U so much friends

mheshpmra at 2007-7-29 18:22:24 > top of Java-index,Java Essentials,Java Programming...