Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

java - How to compare dates in hibernate

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 current date in there date field. I mean i need to match only 2012-04-09' . How can i do it using hibernate criteria.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...