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.
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));
Like this?
criteria.add(Expression.eq("yourDate", aDate))
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
How-to do it in Hibernate has already been said. You can prepare the Timestamp objects in the Java code using, for example, the following aproach:
Calendar cFrom = Calendar.getInstance();
cFrom.setTime(new Date()); /* today */
cFrom.set(Calendar.HOUR_OF_DAY, 0);
cFrom.set(Calendar.MINUTE, 0);
cFrom.set(Calendar.SECOND, 0);
cFrom.set(Calendar.MILLISECOND, 0);
Timestamp from = new Timestamp(cFrom.getTime().getTime());
Calendar cTo = Calendar.getInstance();
cTo.setTime(new Date()); /* today */
cTo.set(Calendar.HOUR_OF_DAY, 23);
cTo.set(Calendar.MINUTE, 59);
cTo.set(Calendar.SECOND, 59);
cTo.set(Calendar.MILLISECOND, 999);
Timestamp to = new Timestamp(cTo.getTime().getTime());
final String QUERY = ""
+ "SELECT tr "
+ "FROM Type tr "
+ "WHERE tr.timestamp >= :timestampFrom AND tr.timestamp <= :timestampTo";
Query query = entityManager.createQuery(QUERY);
query.setParameter("timestampFrom", from);
query.setParameter("timestampTo", to);
#SuppressWarnings("unchecked")
List<Type> ts = (List<Type>)query.getResultList();
The easiest way is to fetch all records having date between the beginning and end of a given day:
WHERE date BETWEEN :from AND :to
And compute from and to in your Java code.
For computing midnights:
import static org.apache.commons.lang.time.DateUtils.ceiling;
import static org.apache.commons.lang.time.DateUtils.truncate;
Date someDay = new Date();
Date from = truncate(someDay, Calendar.DAY_OF_MONTH);
Date to = new Date(ceiling(someDay, Calendar.DAY_OF_MONTH).getTime() - 1);
Restrictions.between("dateColumn", midnight1, midnight2)
The following code will work
Calendar fromDate = Calendar.getInstance();
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);
Calendar toDate = Calendar.getInstance();
toDate.setTime(new Date());
toDate.set(Calendar.HOUR_OF_DAY, 23);
toDate.set(Calendar.MINUTE, 59);
toDate.set(Calendar.SECOND, 59);
toDate.set(Calendar.MILLISECOND, 999);
criteria.add(Restrictions.between("loadDate", fromDate.getTime(),
toDate.getTime()));
// datetime comparison Hibernate 4.3
Select c from Customer c where c.date<{d '2000-01-01'}
Related
Calendar cal;
String sql = "INSERT INTO ttable (dt) values (?);"
//dt is a dateTime field in ttable
PreparedStatement stmt = connection.prepareStatement(sql);
stmt = setDate(1,cal); //not working
stmt.execute();
stmt.close();
I would like to convert cal to a Date type to insert into table.
There is a getTime() method (unsure why it's not called getDate).
Edit: Just realized you need a java.sql.Date. One of the answers which use cal.getTimeInMillis() is what you need.
Did you try cal.getTime()? This gets the date representation.
You might also want to look at the javadoc.
Use stmt.setDate(1, new java.sql.Date(cal.getTimeInMillis()))
Converting is easy, setting date and time is a little tricky. Here's an example:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2000);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 1);
cal.set(Calendar.MINUTE, 1);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
stmt.setDate(1, new java.sql.Date(cal.getTimeInMillis()));
Here is a simple way to convert Calendar values into Date instances.
Calendar C = new GregorianCalendar(1993,9,21);
Date DD = C.getTime();
System.out.println(DD);
stmt.setDate(1, new java.sql.Date(cal.getTime().getTime()));
Calendar cal = Calendar.getInstance(); //This to obtain today's date in our Calendar var.
java.sql.Date date = new Date (cal.getTimeInMillis());
I found this code works:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
Calendar calendar = new GregorianCalendar(2013,0,31);
System.out.println(sdf.format(calendar.getTime()));
you can find the rest in this tutorial:
http://www.mkyong.com/java/java-date-and-calendar-examples/
I want to fetch the results which occurred on a particular date from the database. The problem is the database contains date+time but I require result on the basis of date part only.
#Query("from TableA where traveller = ?1 and direction = ?2 and targetDate = ?3")
List<TableA> findListOfRequestsWithDateAndTraveller(String traveller, String direction, Date date);
Try with the date function, found here: date(timestamp_field)
#Query("from TableA where traveller = ?1 and direction = ?2 and date(targetDate) = ?3")
List<TableA> findListOfRequestsWithDateAndTraveller(String traveller, String direction, Date date);
I resolved this problem by handling it under java instead of query.
#Query("from TableA where traveller = ?1 and direction = ?2 and targetTime >= ?3 and targetTime <= ?4")
List<PBillableRequest> findListOfRequestsWithDateAndTraveller(String traveller, String direction, Date startDate, Date endDate);
for getting the startDate and endDate, i used this functions.
public Date getEndOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTime();
}
public Date getStartOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
I have a hql to show my data based on between(to_date), but i got Could not locate named parameter error
this is my code
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");
Date date1 = Calendar.getInstance().getTime();
String tgl1 = sdf1.format(date1);
String Tanggal_awal = tgl1+" 00:00:00";
System.out.println(Tanggal_awal);
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy");
Date date2 = Calendar.getInstance().getTime();
String tgl2 = sdf2.format(date2);
String Tanggal_akhir = tgl2+" 23:59:59";
System.out.println(Tanggal_akhir);
Query LoadSource = session_source.createQuery("select CLIENT,SERVICE,SERVICE_TYPE,PROVIDER_CODE,COUNT(*) FROM SwitcherServiceSource" +
" where TIMESTAMP between to_date(':awal','dd-MM-yyyy HH24:MI:SS') and to_date(':akhir','dd-MM-yyyy HH24:MI:SS')" +
" and PROVIDER_CODE is not null group by CLIENT,SERVICE,SERVICE_TYPE,PROVIDER_CODE order by CLIENT,SERVICE,SERVICE_TYPE,PROVIDER_CODE");
LoadSource.setParameter("awal", Tanggal_awal);
LoadSource.setParameter("akhir", Tanggal_akhir);
any help will be pleasure :)
You do not need to quote your parameters. i.e.:
Instead of having where TIMESTAMP between to_date(':awal','dd-MM-yyyy HH24:MI:SS') and to_date(':akhir','dd-MM-yyyy HH24:MI:SS'), you should write where TIMESTAMP between to_date(:awal,'dd-MM-yyyy HH24:MI:SS') and to_date(:akhir,'dd-MM-yyyy HH24:MI:SS')
And even better, you can (and you should) even avoid binding a string to that parameter. You can bind a Date/Timestamp, so that the query is even more effective and readable: where TIMESTAMP between :awal and :akhir, and do something similar to this in your code:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date fromDate = cal.getTime();
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
Date toDate = cal.getTime();
Query loadSource = session_source.createQuery("select blablabla FROM SwitcherServiceSource" +
" where TIMESTAMP between :awal and :akhir " +
" and blablabla group by blabla order by blablabla");
loadSource.setParameter("awal", fromDate );
loadSource.setParameter("akhir", toDate);
I am trying to figure out how to get a date that is exactly one year less than the current date and pass it as a parameter to HQL.
I tried to use Calendar. But I am lost in converting this to right Date format required for Oracle.
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.YEAR, -1);
String dateLimit = cal.getTime().toString();
Date dateFormatter = new SimpleDateFormat("dd-MMM-yyyy").parse(dateLimit); // This one shows I need to either wrap it up in try catch or specify in throws.
//Date cutOffDate = dateFormatter.parse(dateLimit); //tried this. no avail
queryBuilder.append(" and c.dateOfContact >= :cutOffDate ");
parameters.put("cutOffDate", dateFormatter);
Alternatively, are there any Hibernate built-in function for date manipulation? All I want is to pass a date to the query, which is a year less than the current date.
Oracle date format is dd-MMM-yyyy. (ex: 21-Jun-2013)
i think this will work:
parameters.put("cutOffDate", cal.getTime());
If the type of c.dateOfContact is java.util.Date or java.sql.Date than cal.getTime() has to work.
Date d = cal.getTime();
Query query = em.createQuery(QUERYSTRING)setParameter("cutOffDate", d);
The above should work, don't format your date as a string, because then you will be comparing a String and a Date.
I need to get actual date with custom hour so I create this code:
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
Calendar output = Calendar.getInstance();
output.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), 1, 0);
output.getTime();
I hope it works but it seems a litle bit complicated.
Is there some other way how to get date with custom hour?
Is there some other way how to get date with custom hour ?
Personally I'd use Joda Time instead:
// Ideally use an injectable clock...
LocalDate today = new LocalDate();
// If this is effectively constant, extract it to a final static field
LocalTime time = new LocalTime(1, 0);
// Or use toDateTime(...) depending on what you're trying to accomplish
LocalDateTime todayAtTime = today.toLocalDateTime(time);
Joda Time has a much more pleasant API than java.util.{Date, Calendar}
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 1);
cal.set(Calendar.MINUTE, 0);
cal.getTime()
what about this :
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, your_custom_hour);
your_custom_hour : 0-23
Other than use Joda time I'd do it slightly cleaner:
int hour = 1;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, hour);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar.getInstance() returns the current date and time anyway so setTime(new Date()) is unnecessary.