How to compare dates in hibernate

后端 未结 8 697
予麋鹿
予麋鹿 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:25

    fromDate.setTime(new Date());
    fromDate.set(Calendar.HOUR_OF_DAY, 0);
    fromDate.set(Calendar.MINUTE, 0);
    fromDate.set(Calendar.SECOND, 0);
    fromDate.set(Calendar.MILLISECOND, 0);
    

    This code is extremely dangerous ... if the day is switch to daylight saving time (e.g. 06.04.1980) you end up in following exception!!!

     java.lang.IllegalArgumentException: HOUR_OF_DAY: 0 -> 1day
    
    
    HQL: from human pat where year(pat.birthdate) = :start_day and month(pat.birthdate) = :start_month and year(pat.birthdate) = :start_year ");
    
    params.put("start_day", startDate.get(Calendar.DAY_OF_MONTH));
    params.put("start_month", startDate.get(Calendar.MONTH) + 1);
    params.put("start_year", startDate.get(Calendar.YEAR));
    

    The year/month/day functions use the underlying db functions (extract, ...) and compares only these values. Therefore I did not need to set the time to 0 which leads to the above described exception. just an example out of my mind how I solved the problem! Maybe it helps

提交回复
热议问题