Java – How to assign Date parameters to Hibernate query for current timezone


When you assign a date to a named SQL parameter Hibernate automatically converts it to GMT time. How do you make it use the current server timezone for all dates?

Lets say you have a query:

Query q = session.createQuery("from Table where date_field < :now");
q.setDate("now", new java.util.Date());

"now" will be set to GMT time, while "new Date()" gets your current server time.


Best Solution

As it turned out Hibernate doesn't convert dates to GMT automatically, it just cuts off time if you use query.setDate(), so if you pass "2009-01-16 12:13:14" it becomes "2009-01-16 00:00:00".

To take time into consideration you need to use query.setTimestamp("date", dateObj) instead.