Search code examples
hibernatedatecriteria

How to write Hibernate Criteria to get records only between two date and month not year


I am creating an application, I am letting user to enter their date of Birth(dd/mm/yyyy).

What I need is to get the records dependent on month and day not year.

Ex:

  1. 01/01/1993

  2. 08/01/1995

  3. 30/01/2015

If user searches for the next date of birth between two dates

  • from Date 01/01/1993

  • to Date 01/10/1999

I need to display first two records.

Can anybody help.


Solution

  • Need to use DATE_FORMAT, and SqlRestriction.

    String sqlWhere = " DATE_FORMAT( " + "{alias}.date_of_birth"+ ",'%m-%d') BETWEEN '" + 
    String.format("%02d", fromMonth) + "-" + 
    String.format("%02d", fromDate)  +  "' and  '" + 
    String.format("%02d", endMonth) + "-" +
    String.format("%02d",  endDate )+ "'" ;
    criteria.add(Restrictions.sqlRestriction(sqlWhere )  );