开发者

Using Hibernate's MatchMode for a Date object

开发者 https://www.devze.com 2023-03-16 22:08 出处:网络
I have a Date object for a date \"26/12/2007\" which I want to compare with my date in my MySQL database \"26/12/2007 12:00:00\". Like if I send a date \"26/12/2007\" it should retrieve values against

I have a Date object for a date "26/12/2007" which I want to compare with my date in my MySQL database "26/12/2007 12:00:00". Like if I send a date "26/12/2007" it should retrieve values against the date in MySQL database.

It works if I remove this "12:00:00", but if I add "12:00:00"- it gives no results.

I am using Hibernate Criteria like

criteria.add(Restrictions.like("dateinsql", date));

I tried using

criteria.add(Restrictions.like("dateinsql", date,MatchMode.AnyWhere));

but it only works for String not Date.

Any solutions 开发者_C百科for that?


Basically you need to reformat your date variable's pattern, i.e., get its string format according to a specified date pattern and and then convert it back to date object."dd MMM yyyy" is the format that works for hibernate.

try this:-

    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(your_input_date);
    calendar.add(Calendar.DATE, 1); // this is needed to if you want to deal with 12 hrs difference.

    SimpleDateFormat sdf    =   new SimpleDateFormat("dd MMM yyyy");
    Date formattedDate = sdf.parse(org.apache.commons.lang.time.DateFormatUtils.format(calendar.getTime(),"dd MMM yyyy"));

Using this formatted date,

criteria.add(Restrictions.like("dateinsql", formattedDate ));

should work fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号