How to compare dates in hibernate

后端 未结 8 700
予麋鹿
予麋鹿 2020-12-10 11:39

In my Data base dates are as 2012-04-09 04:02:53 2012-04-09 04:04:51 2012-04-08 04:04:51, etc, I need to retrieve data which have curr

8条回答
  •  攒了一身酷
    2020-12-10 12:20

    Use Restrictions.between() to generate a where clause which the date column is between '2012-04-09 00:00:00' and '2012-04-09 23:59:59'

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date fromDate = df.parse("2012-04-09 00:00:00");
    Date toDate = df.parse("2012-04-09 23:59:59");
    
    criteria.add(Restrictions.between("dateField", fromDate, toDate));
    

    Please note that all the properties used in the Criteria API is the Java property name , but not the actual column name.


    Update: Get fromDate and toDate for the current date using JDK only

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    Date fromDate = calendar.getTime();
    
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 59);
    calendar.set(Calendar.SECOND, 59);
    Date toDate = calendar.getTime();
    
    criteria.add(Restrictions.between("dateField", fromDate, toDate));
    

提交回复
热议问题