简体   繁体   中英

SQL compare dates without time

I am using PostgreSQL 12.6. I would like to compare two dates in a WHERE clause, without the time.

eg

WHERE flight_date = (?1)

The flight_date is for example '2022-02-09 11:21:23' and the parameter is '2022-02-09 11:22:54', but I want them to be equal because they are on the same day (ignore the time).

I am using Java11 with Hibernate JPA.

        java.util.Date flightDate = ...
        Query query = entityManager.createNativeQuery(sql);
        query.setParameter(1, flightDate);
        List<Long> tripIds = query.getResultList();

Error:

PSQLException: ERROR: function to_date(timestamp without time zone, unknown) does not exist Hint: No function matches the given name and argument types. You might need to add explicit type casts.

One way is to cast the timestamp to a date:

where cast(flight_date as date) = ?1

However that won't be able to make use of an index on flight_date . If you need the performance, a range query is better:

where flight_date >= ?1
  and flight_date < ?1 + interval '1 day';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM