views:

75

answers:

3

I am using a SQL Server database and Hibernate. I have the following problem related to storing dates:

I have the following code:

String hql = "select user from User user where user.createDate = :date";
Query query = HibernateUtil.getSession().createQuery(hql);
Date date2 = DateHelper.getEndOfDay(new Date());//this returns 2010-07-27 23:59:59.999
query.setParameter("date", date2);

When I am comparing the date 2010-07-27 23:59:59.999 I am getting results that have a date: 2010-07-28 00:00:00.0. Using the setDate() instead of setParameter() returns the users whose saved dates are on the same day, meaning that the hours, minutes etc. are discarded.

The hibernate maps the dates to java.util.Date but in the result list everything is Timestamp I guess because Timestamp extends java.util.Date. What would you suggest to do in order to have a good result when comparing for equality?

+1  A: 

Did you try Query.setDate() or Query.setTimestamp() ?

Konrad Garus
The setDate() is not good because it gives me back all the users whose date is on the same day, meaning that the hour and seconds etc. are discarded.
Atticus
but Timestamp should be fine. (if you get the millis from your date). (+1)
Bozho
In your question you mention "dates" several times, so I wasn't sure if you mean "date" or "date/time" and included both in my answer.
Konrad Garus
It seems that not Hibernate is the cause of the problem but MSSQL since it saves the dates with a precision of 3 milliseconds. Running the same query on the database gives the same problem. I think the best solution is to format the dates before saving them so that the millisecond part would always be 0.
Atticus
A: 

If possible, I suggest you use the JODA DateTime API. Persist the DateTime object to the database using the PersistentDateTime Hibernate User Type class from the joda-hibernate project.

Jatin
Are there other alternatives besides using this API?
Atticus
Not using Joda Time is not a problem.
Pascal Thivent
It's just that this API has some amazing convenience/common-sense methods which are otherwise very tricky to figure out in a custom dev project. Of course it's not a 'problem' is you don't use this one specifically. I'll be surprised if there aren't alternatives out there. Anyone know of any good alternatives?
Jatin
A: 

I think the problem is with MSSQL database since it saves the dates with a 3 millisecond precision as seen in one of the answers of this post.

So the problem is that since the time 23:59:59.999 can not be saved in MSSQL (probably with 3 millisecond precision you can never get 999 when comparing to times retrieved from the database this time has to be converted, and when converting it to some MSSQL compatible date it ends up to be the next day.

I think this is the real problem that I am seeing here. In order to avoid this I think I should format the dates I am saving.

Atticus