If you are looking for a general use of filtering by date range (eg. from today until tomorrow).
I use it that way:
YourService.java
Date fromTimestamp = new Date();
Date toTimestamp = new Date();
Date fromDate = DateHelper.getDateWithoutTime(fromTimestamp);
Date toDate = DateHelper.getDateWithoutTime(DateHelper.getTomorrowDate(toTimestamp));
YourDAO.java
criteria.add(Restrictions.ge(TIMESTAMP_FIELD, fromDate));
criteria.add(Restrictions.le(TIMESTAMP_FIELD, toDate));
DateHelper.java
public static Date getDateWithoutTime(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);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
public static Date getTomorrowDate(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 1);
return cal.getTime();
}
And of course - there is always space for refactoring in every code.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…