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();
}
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 reset java.util.Date to the beginning of the day
using
Date date = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
date = cal.getTime();
with
Date date = new Date();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String s=df.format(date);
try {
date = df.parse(s);
} catch (ParseException ex) {
}
Which one is better?
This one's better in terms of clarity and readability, though both gives same output.
Date date = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
date = cal.getTime();
With help of Apache Commons org.apache.commons.lang3.time.DateUtils you can also get the desired result like this:
DateUtils.truncate(new java.util.Date(), java.util.Calendar.DATE));
First solution (manipulation via Calendar) is definitly better. The second solution is just a rather ugly workaround using string-manipulation, that will most likely be slower than the first one.
You can for first approach and you need not set time in Calendar.
// Date date = new Date();
Calendar cal = new GregorianCalendar();
// cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date date = cal.getTime();
I want to fetch all the records which match the today date but ignoring the year Date in database is like this 1980-11-14. Want to fetch the record only comparing month and day not the year. I tried it using Criteria but its not working. Here is my code.
Date date = new Date(); // your date
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH,month);
calendar.set(Calendar.DAY_OF_MONTH, day);
Calendar fromDate = calendar.getInstance();
calendar.set(Calendar.MONTH,month);
calendar.set(Calendar.DAY_OF_MONTH, day);
Calendar toDate = calendar.getInstance();
Criteria criteria=session.createCriteria(Add_Follower.class);
criteria.add(Restrictions.eq("follow_uInfo.id", uid));
criteria.add(Restrictions.between("following_uInfo.dob",fromDate,toDate));
users=criteria.list();
I did it with a named query and using "EXTRACT",
in this example for birthdays:
SELECT p FROM Person p
WHERE EXTRACT(DAY FROM p.gebdat) = EXTRACT(DAY FROM NOW())
AND EXTRACT(MONTH FROM p.gebdat) = EXTRACT(MONTH FROM NOW())
ORDER BY p.nachname, p.vorname
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);
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'}