Datetime in HQL check only date - java

I've the following hql query:
Query query = session.createQuery("from Appointments where datetime < :now");
query.setDate("now", new Date());
listApps = query.list();
It return only the records before today (yesterday, 2 days ago and so on)
But not the record of today before than this time.
The datetime into the database is of type DateTime, so it contains both date and time.
Why is this query not returning the record of today before than the current time?
This is the way datetime is defined inside my entity:
#Temporal(TemporalType.TIMESTAMP)
private Date datetime;

Change from
query.setDate("now", new Date());
to
query.setTimestamp("now", new Date());
or to:
query.setParameter("now", new Date());
Bind the date (time is truncated) of a given Date object to a named query parameter.
public Query setDate(String name, Date date);
Bind the date and the time of a given Date object to a named query parameter.
public Query setTimestamp(String name, Date date);

Related

SQL query to return ongoing auctions

I have a table
Id AuctionName URL StartDate EndDate
1 auction1 image 2015-01-11 22:27:21 2015-01-12 14:25:22
2 auction2 video 2015-01-12 05:30:50.0 2015-01-14 08:18:10
I get the currentTimeStamp using Java like this:
public Timestamp getCurrentTimestamp(){
java.util.Date date= new java.util.Date();
SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDate=dateFormater.format(date);
Timestamp currentTimestamp=Timestamp.valueOf(currentDate);
System.out.println(currentTimestamp);
return currentTimestamp;
}
This is my output.
2015-01-12 05:30:50.0
What is the right SQLQuery to retrieve currentAuctions. I would appreciate some help.
SELECT id, AuctionName FROM auctiontable WHERE (NOW() BETWEEN StartDate AND EndDate);
You could altenatively replace NOW() with the string formed in your Java code, but this is cleaner.

Criteria for getting month from date in hibernate3

I have stored the date in my database (not months).i want to get the records from particular month.Is it possible to write criteria for this in hibernate3?
You can write like this
Date startDate = 2014-03-01
Date endDate = 2014-03-31
Criteria criteria = getSession().createCriteria(getDomainClass());
criteria.add(Restrictions.between("date", startDate, endDate));
(OR)
If your date format is "YYYY-MM-DD"
String date = "2014-03";
Criteria criteria = getSession().createCriteria(getDomainClass());
criteria.add(Restrictions.like("date", date));

Sqlite : Comparing timestamp value stored in a column to current Date

I store information in a sqlite database table as follows:
ActionDate column is of type : DEFAULT CURRENT_TIMESTAMP
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
I want to write an SQL query that returns all rows in my table having ActionDate value as today's date from sqlite DB. However as ActionDate is of type timestamp what is the most appropriate way to convert it to todays date.
If you want current date then use the following query :
SELECT date('now');
To get all columns in your table having ActionDate equal to todays date use the below query :
select * from table where strftime('%Y-%m-%d ', datetime(ActionDate, 'unixepoch')) = date('now)' ;
more info on SQLite Date & Time queries can be found here

Date - Java to Sql table and sql table to Java through Joda Time

I am looking for a way to get today's date and pass to sql table and save there. Call the saved date and do some task with JODA TIME API. The changed Joda time Date to sql table and save there and process continues..
I tried this way,
//prints todays date
java.sql.Date sqlDate = new java.sql.Date(new Date().getTime());
//passes wrong date to the table like 1970-07-01 instead of 2013-03-01
String insert = "INSERT INTO TEST_TABLE VALUES(1,"+sqlDate+")";
pStmt = conn.prepareStatement(insert);
pStmt.executeUpdate();
//converting to joda time
LocalDate ld = new LocalDate(sqlDate);
//some calculations, and how to convert back to sql date?
What I am trying to do here is, A table with 3 columns (id, startdate, finishdate). id will be entered by user, start date should be automatically entered todays date. after some calculations with joda time and finish date will be set to date it is finished.
Code
String insert = "INSERT INTO TEST_TABLE VALUES(2,'"+timestamp+"')";
Error
Data type mismatch in criteria expression
//I have created table using MS access
//the format of the date column is Date/Time.
You Can use Timestamp here. java.sql.Timestamp extends java.util.Date, so anything you can do with a java.util.Date you can also do with a java.sql.Timestamp.
To convert LocalDateTime to Timestamp
Timestamp timestamp = new Timestamp(localDateTime.toDateTime().getMillis());
But if You still want to convert Timestamp into java.sql.Date then use this
java.sql.Date date = new java.sql.Date(timeStamp.getTime());

Criteria query for fetching the data after particular date and time

I am using the criteria query as follows:I want to fetch the reservations after the time and date I have passed.but now i am getting the reservation before the time which i have passed for the same date.Please help..
#GET
#Path("/getReservationByUserIdAndTypeAndDateTime/{userid}/{type}/{date}/{time}")
public List<Reservation> getReservationByAndUserIdAndTypeAndDateTime(#PathParam("userid") int uid, #PathParam("type") int tid,#PathParam("date") Date date,#PathParam("time") Time time) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Reservation> criteria = builder.createQuery(Reservation.class);
Root<Reservation> r = criteria.from(Reservation.class);
TypedQuery<Reservation> query = em.createQuery(
criteria.select(r).where(new Predicate[]{
builder.equal(r.get(Reservation_.usersId), uid),
builder.equal(r.get(Reservation_.reservationsType), tid),
builder.greaterThanOrEqualTo(builder.concat(r.get(Reservation_.date), " "+r.get(Reservation_.time)), date.toString()+" "+time.toString())}));
return query.getResultList();
}
Comparing dates and times formatted as string is not advisable, results can depend on the format. It would be better having a unique Date field in the Reservation class:
#Temporal(TIMESTAMP) Date date;
and using date comparison in the query:
builder.greaterThanOrEqualTo(r.get(Reservation_.date), date)
This way the time parameter in the getReservationByAndUserIdAndTypeAndDateTime method can be omitted, since the date parameter would hold both date and time.

Categories