I want to get a list of objects from the database between a given date time range. How do I achieve that ? This is the solution I am currently using, but it doesn’t return anything… and the given values are correct.
public List getRegistrationsForUserOnDate(Date startdate, Date enddate){
Set<Date> dateSet = new HashSet<Date>();
Calendar calendar = new GregorianCalendar();
calendar.setTime(enddate);
while (calendar.getTime().before(startdate))
{
Date resultado = calendar.getTime();
dateSet.add(resultado);
calendar.add(Calendar.DATE, 1);
}
String query = "from Registration where date = '" + Validation.convertToValidDateTime(startdate, true) + "'";
for(Date date : dateSet){
query += " AND date = '" + Validation.convertToValidDateTime(date, true)+"'";
}
return em.createQuery(query).getResultList();
}
for example:
startdate = Fri Jun 15 12:07:31 CEST 2012
enddate = Wed Jun 13 12:07:31 CEST 2012
Then this methods query looks like this (data copied from debug mode):
from TimeRegistration where date = '2012-06-15 00:00:00' AND date = '2012-06-14 00:00:00' AND date = '2012-06-13 00:00:00'
These are some sample fields that are present in the database:
id | date |comment|FK|FK|FK
132|"2012-06-08 00:00:00"| "" | 6| 2| 1
133|"2012-06-15 00:00:00"| "" | 8| 1| 1
134|"2012-06-14 00:00:00"| "" | 3| 2| 1
135|"2012-06-13 00:00:00"| "" | 1| 3| 1
How can date equal two different dates? Not surprised you don’t get anything.
date = ‘2012-06-15 00:00:00’ AND date = ‘2012-06-14 00:00:00’ – so if todays date is thursday and friday return it?
Should you be using OR rather than AND, or better still, greater and less than or between?