Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare dates in hibernate

In my Data base dates are as 2012-04-09 04:02:53 2012-04-09 04:04:51 2012-04-08 04:04:51, etc, I need to retrieve data which have current date in there date field. I mean i need to match only 2012-04-09' . How can i do it using hibernate criteria.

like image 548
Romi Avatar asked Apr 09 '12 13:04

Romi


People also ask

How do I compare dates in HQL?

In Oracle You Can Use HQL trunc() Date Function Another function you can use for HQL date comparison queries is the HQL trunc() function. This function discards the hour part of the date. Please note that this will only work when using Hibernate with Oracle and the OracleDialect .


1 Answers

Use Restrictions.between() to generate a where clause which the date column is between '2012-04-09 00:00:00' and '2012-04-09 23:59:59'

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date fromDate = df.parse("2012-04-09 00:00:00");
Date toDate = df.parse("2012-04-09 23:59:59");

criteria.add(Restrictions.between("dateField", fromDate, toDate));

Please note that all the properties used in the Criteria API is the Java property name , but not the actual column name.


Update: Get fromDate and toDate for the current date using JDK only

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date fromDate = calendar.getTime();

calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
Date toDate = calendar.getTime();

criteria.add(Restrictions.between("dateField", fromDate, toDate));
like image 148
Ken Chan Avatar answered Sep 30 '22 13:09

Ken Chan