Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Thanks.

like image 671
serg Avatar asked Nov 14 '08 22:11

serg


People also ask

How to pass date parameter in hibernate query?

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.


2 Answers

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.

like image 64
serg Avatar answered Sep 18 '22 12:09

serg


Hibernate is ignorant of timezones. Any timezone conversion should be done prior to executing the query.

E.g., if your database server is set to CST, but the user is on EST, you'll need to add 1 hour to any timestamps which are the input to a query.

like image 22
Clay Avatar answered Sep 17 '22 12:09

Clay