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.
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 .
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With