Comparing Java dates with DateTime Column in a database table using SQL

I have two Java Date objects that will be assigned to some variables in the sql query (because I use Hibernate) to compare them with a DateTime type column to get rows with a given time range, for example:

  WHERE event_date >= :startDate and event_date < :finishDate 

I could not directly compare the date and date, so I thought of two possible solutions:

  • Try converting the event_date field using the query to date field before comparing.
  • Or try converting a date java object to dateTime, which I think is impossible.

What would you advise me?

+4
source share
1 answer

I think you have problems because you are using the setDate (correct me if I am wrong) and the setDate method:

Binds the date (time truncated) of this Date object to the named query parameter.

Use setTimestamp instead, which binds the date and time of this Date object:

 java.util.Date startDate = … ; java.util.Date finishDate = … ; Query query = session.createQuery("from YourTable where event_date >= :startDate and event_date < :finishDate"); query.setTimestamp("startDate", startDate); query.setTimestamp("finishDate", finishDate); 


ps: don't forget to use the java.util.Date and NOT java.sql.Date objects.

+3
source

Source: https://habr.com/ru/post/1382652/


All Articles