26

Hello I am using hibernate in my example.For bean Table Audit Trial I want to fetch audit trial between a date range with inclusion of upper & lower limits. My code is like below

Criteria criteria = session.createCriteria(AuditTrail.class);

criteria.add(Restrictions.between("auditDate", sDate, eDate));

My starting date is 25/11/2010. and end date is 25/05/2011.But it is only giving the result up to 24/05/2011.It is not performing inclusive search.Any other way to do this. I am using SQL server.

4 Answers 4

46

I assume your auditDate is in fact a timestamp. If it's the case, then this is normal, because 25/05/2011 means 25/05/2011 at 0 o'clock (in the morning). So, of course, every row having an audit timestamp in the date 25/05/2011 is after 0 o'clock in the morning.

I would add 1 day to your end date, and use auditDate >= sDate and auditDate < eDate.

criteria.add(Restrictions.ge("auditDate", sDate)); 
criteria.add(Restrictions.lt("auditDate", eDate));
1
  • Protip: if you don't have to deal with the time component like the OP above, you could just use le(..) (instead of lt(..) + messy date arithmetic). Commented Apr 28, 2020 at 13:08
2

criteria.add(Restrictions.between("DATE(auditDate)", sDate, eDate)); use this for ignoring time from date.

1
  • 1
    This gives error: "could not resolve property: DATE(auditDate)" Commented Mar 1, 2020 at 6:37
1
 criteria.add(Restrictions.ge("fromDate", DateUtil.persianToGregorian(currentDate)));
 criteria.add(Restrictions.le("toDate",  DateUtil.persianToGregorian(currentDate)));

 return criteria.list();
1

add one more day to end date

 @Autowired
 private SessionFactory sessionFactory;

 String startDate = "2025-08-05 ";
 String endDate = "2025-08-05 ";

 Date fromDate = format.parse(fromDate);

 /* Add one more day to the end date*/

 Date to =format.parse(endDate);
 Calendar today = Calendar.getInstance();
 today.setTime(dateto);
 today.add(Calendar.DAY_OF_YEAR, 1);

 Date toDate= format.parse(format.format(today.getTime()));

 Criteria crit = sessionFactory.getCurrentSession().createCriteria(model.class);
 crit.add(Restrictions.between("dateFieldName", fromDate, toDate));
 List result = crit.list();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.