Passing date to hql query from Java - java

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.

Related

Error when trying to cast from Calendar to Date then to sql.Date [duplicate]

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/

Calculating date in mysql with java

I'm having trouble, finding out how to calculate or get the date from mysql (using java program) after 1 month of the initial saved date given below:
Date rDate = new Date();
java.sql.Date regDate = new java.sql.Date(rDate.getTime());
I am saving the date into a date column in mysql and I want to have another column which contains the date but one month ahead. In other words I have a registration date and I want to have an expiration date calculated automatically which allows only 1 month. Is it possible?
Grabbing the current date and set it into the Calendar format and add 1 to the month.
You can give this a try.
Date rDate = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(rDate);
cal.add(Calendar.MONTH, 1);
You can use Calendar class to manipulate date fields:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
Date futureDate = cal.getTime();

set calendar object hour to 0

this is my code
TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
Timestamp start = new Timestamp(calendar.getTime().getTime());
but the timestamp result is for instance = 2014-09-30 02:00:00.0 I´m not able to set the hours to 0.
Any suggestions.
Once you call Calendar.getTime() you get a Date object which is an instant in time which has no timezone info.
When you want to print or present this instance, the formatter will use the default time zone if not explicitly specified, which in your case is not UTC but maybe CET.
When you convert this instant to a String, you also have to tell in which timezone you want it to present. You have to specify UTC timezone there as well.
For example if using SimpleDateFormat, you can use its setTimeZone() method.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(start));
Also if your result is from your database, you have to use a timestamp SQL type without timezone or with the UTC timezone.
I guest icza is right.
To be sure, try this :
Timestamp start = new Timestamp(calendar.getTime().getTime());
System.out.println(start.getTimezoneOffset());

How to send date and time to SQL using java

I am calling a stored procedure in a database.
Two of its parameters requires date and time in sql date format.
String x = new SimpleDateFormat("MM-dd-yyyy").format(new Date()) + " 00:00:00 AM";
String y = new SimpleDateFormat("MM-dd-yyyy").format(new Date()) + " 11:59:00 PM";
Date fromDate = null;
Date toDate = null;
try {
fromDate = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss a").parse(x);
toDate = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss a").parse(y);
} catch (ParseException ex) {
}
CallableStatement proc_stmt = con.prepareCall("{ call someproc(?,?) }");
proc_stmt.setDate(1, (java.sql.Date) fromDate);
proc_stmt.setDate(2, (java.sql.Date) toDate);
I believe if i send just the date(excluding time), the code works, but its of no use to me as the database does not generate correct results.
When i run the above code I get
ClassCastException:java.util.Date cannot be cast to java.sql.Date
Any solution?
Use java.sql.Timestamp class which holds date and time for sql fields, and CallableStatement#setTimestamp:
proc_stmt.setTimestamp(1, new java.sql.Timestamp(fromDate.getTime());
create new object of java.sql date and then pass the java.util date in it.
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
I usually go for along the lines of
proc_stmt.setDate(1, new java.sql.Date(fromDate.getTime()));
Why are you formatting a Date to a String and then parsing it again? You shouldn't need a string representation at all. Avoid string conversions as far as you can - you're not really interested in the text representation of the date; you're just trying to specify a value.
You should be able to use:
// TODO: Consider time zones
Calendar calendar = Calendar.getInstance();
// Clear the time part of the calendar (leaving you with "start of day")
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Timestamp start = new Timestamp(calendar.getTimeInMillis());
// Adjust to "end of day"
calendar.add(Calendar.DATE, 1);
calendar.add(Calendar.MILLISECOND, -1);
Timestamp end = new Timestamp(calendar.getTimeInMillis());
CallableStatement statement = con.prepareCall("{ call someproc(?,?) }");
statement.setTimestamp(1, start);
statement.setTimestamp(2, end);
Note that I've switched to using java.sql.Timestamp instead of java.sql.Date as it looks like you really do want a date and time whereas java.sql.Date only represents a date.
A couple of other points:
If you could use Joda Time, it would make the first part of the code simpler. Joda Time is a much better date/time API in general.
I would suggest you change your stored procedure to use an exclusive end time if possible. That way you can just specify the start of today and the start of tomorrow. You don't need to worry about the granularity of the value, because you can always create abutting but non-overlapping intervals. In particular, I've currently only set end to the end of the day down to the last millisecond - but java.sql.Timestamp

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.
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'}

Categories

Resources