简体   繁体   中英

JPQL - Calculate difference between Timestamps

I want to calculate the difference between the TIMESTAMP saved in the Database with the CURRENT_TIMSTAMP and verify if the number of days between them is less than a given number.

TypedQuery<Person> q = entityManager.createQuery("SELECT p FROM Person p WHERE (p.createdOn - CURRENT_TIMESTAMP <= :constant))", Person.class);

The p.createdOn is automatically set by the Database.

The constant would be the number of days the difference has to be less than.

q.setParameter("constant", 14);

The query is compiling but not retrieving what it needs to and I am unable to get the number of days between them working in my query.

An alternative (inefficient) approach is getting all and looping through them and calculating.

First, you need to subtract createdOn from the current date, not vice versa (otherwise, result is always negative and condition always evaluates to true ).

Secondly, if date operations don't work as expected, you can always calculate the date limit before query execution and pass it as parameter:

Date date = // current date minus three days

TypedQuery<Person> q = entityManager.createQuery("SELECT p FROM Person p WHERE p.createdOn >= :date", Person.class);
q.setParameter("date", date);

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