Using Hibernate to filter results by Date

Today, I was trying to access some data for my project on Twitter and filtering it using the creation date of the tweets. So I began by creating the usual Criteria and added a few Restrictions. For filtering by date, I created Date objects for startDate and endDate using Calendar.getTime() method and added the following Restriction, c.add(Restrictions.between("createdAt", startDate, endDate); Surprisingly, this didn’t work as I had expected and I was getting an empty result. I Googled for it but couldn’t find much. The only thing was that the Restriction should work given the date. Well, I was in a hurry and didn’t try to dig it through. As a workaround, I tried writing HQL query to get the results but that didn’t work either.

This is what worked. I created the date using SimpleDateFormat and parsing the date. Here’s what I did:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date startDate = format.parse("2011-11-09 00:00:00");
Date endDate = format.parse("2011-11-017 00:00:00");

c.add(Restrictions.between("createdAt", startDate, endDate));	

List<StatusDto> statuses = c1.list(); // It works fine now

Its a quick hack and did work out for me. I was in bit of a hurry and didn’t try to dig up the reason for it now working earlier. Maybe, someone can point my mistake out in the comment. Anyway, I will update the post if I find the reason for it.

Published 22 Jan 2012

I build mobile and web applications. Full Stack, Rails, React, Typescript, Kotlin, Swift
Pulkit Goyal on Twitter