Ilkar
Ilkar

Reputation: 2187

compare two date types variable in java

I found some problem in compare two data types Variable -> java.sql.Date type.

Firstly i'm createing current data (yyyy-mm-dd):

java.util.Date date = new java.util.Date();

java.sql.Date dateSql = new Date(date.getTime());

Secoundly, im receiving data from MySQL:

MyDataEntity myDataEntity = session.getNamedQuery(MyDataEntity.GET_ELEMENT).uniqueResult();

Then i'm trying to compare two dates:

if(dataSql != myDataEntity.getDate()){
System.out.println("different");
}else{
System.out.println("these same");
}

And the effect is, that always these two dates are different. But when i'm printing values of these two datas, i've got these same values:

System.out.println(dataSql);
System.out.println(myDataEntity.getDate);

Effect:

2012-11-16
2012-11-16

But, i found one issue:

if i make:

long date1 = dateSql.getTime();  // print 1353106800000
long date2 = myDataEntity.getDate().getTime(); // print 1353234605091

So how to compare two dates (yyyy-mm-dd) ?

Upvotes: 2

Views: 3860

Answers (2)

GaryF
GaryF

Reputation: 24370

This is a well-known issue: java.sql.Date objects remove the precision found at the lower end of the date object (see all those zeroes at the end of your print). So you must normalise the precision between your java.util.Date and java.sql.Date.

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

Oh, and use .equals to compare objects, not ==.

Upvotes: 0

Bozho
Bozho

Reputation: 597402

First, use .equals(..) to compare non-primitive objects - someDate.equals(anotherDate)

Using == compares their jvm identities - i.e. if they are the same object on the heap, rather than their value.

Then make sure you compare the right things - you want equal dates, then you should discard the hours, minutes and days. For that you can use:

  • math to subtract the millis
  • java.util.Calendar's .set(..) methods.
  • joda-time DateMidnight - best option

Upvotes: 2

Related Questions