2

I would like to compare a date to a timestamp in the database. I currently use

predicates.add(criteriaBuilder.between(eventRoot.<Date>get("time"), dBegin, dEnd));
  • dBegin = Thu Feb 04 00:00:00
  • dEnd = Thu Feb 04 23:59:59

eventRoot

private Date time;

I also tried formatting the date with the following format, to no success.

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

And changing

predicates.add(criteriaBuilder.equal(eventRoot.<String>get("time"), curDformat));

where curDformat is the formatted date to

2025-08-05

And changing the type to String in my eventRoot.

How would I go about only checking the date with the database? And would this improve performance or is it fine doing it with between?

2 Answers 2

2
SimpleDateFromat dateFormat = new SimpleDateFromat("yyyy-MM-dd hh:mm:ss");
Date dBegin = dateFormat.parse("2025-08-05 00:00:00");
Date dEnd = dateFormat.parse("2025-08-05 23:59:59");

predicates.add(criteriaBuilder.between(<Date>get("time"), dBegin, dEnd));

You could use between, it works too.

1

The criteriaBuilder predicate for date comparison without time

cb.equal(cb.function("date", Date.class, myObj.get("createdAt")), cb.function("date", Date.class, cb.literal(new Date())));

It produces the following SQL where clause.

where date(myObj0_.created_at)=date(?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.