Wednesday, 9 July 2014

How to compare dates in hibernate using criteria if DB Field contains both Date and Time values

Here is the small code snippet from my current project to retrieve the records between two date. User will just enter the date part with year, month and date, but the DB Contains date and time value.

if (laborderConditions.getFromDOE() != null) {
criteria.add(Restrictions.ge("createdDate",
getFormattedFromDateTime(laborderConditions.getFromDOE())));
}

if (laborderConditions.getToDOE() != null) {
criteria.add(Restrictions.le("createdDate",
getFormattedToDateTime(laborderConditions.getToDOE())));
}




private Date getFormattedFromDateTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}

private Date getFormattedToDateTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
return cal.getTime();
}

3 comments:

  1. It worked great! Thanks a lot!

    ReplyDelete
  2. can you please explain in DB already date column available with the mix of date and time.
    Now i want to compare another Date field (like sysdate).
    How can i test only dates with 'eq' constraint..?

    ReplyDelete