2

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) ?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.