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();
}

No comments:

Post a Comment