1

I am trying to check if 'toDate' lies within the range , for that i tried 2 approaches but both haven't worked for me

approach 1:

if (MyEntity.getFromDate() != null
                        && MyEntity.getToDate() != null)) {
                    predicate.getExpressions()
                            .add(criteriaBuilder.between((root.<Date>get("toDate")), MyEntity.getFromDate(),MyEntity.getToDate()));

approach 2

if(MyEntity.getFromDate() != null
    && MyEntity.getToDate() != null) {
    DateFormat dateFormat = new SimpleDateFormat(Constants.DBDATEFORMAT);
     String fromDateInString = dateFormat.format(MyEntity.getFromDate());
    String toDateInString = dateFormat.format(MyEntity.getToDate());
    String[] fromDateSplitation = fromDateInString.split(" ");
    String[] toDateSplitation = toDateInString.split(" ");
    StringBuilder startLimit = new StringBuilder();
    StringBuilder endLimit = new StringBuilder();
    startLimit.append(fromDateSplitation[0]).append(" ").append("00:00:00");
    endLimit.append(toDateSplitation[0]).append(" ").append("23:59:59");
    Date fromDate;
    try {
    fromDate = dateFormat.parse(startLimit.toString());
    Date toDate = dateFormat.parse(endLimit.toString());
    MyEntity.setFromDate(fromDate);
    MyEntity.setToDate(toDate);
    predicate.getExpressions().add(criteriaBuilder.between(root.get("toDate"),
    MyEntity.getFromDate(), MyEntity.getToDate()));
    } catch (ParseException e) {
    e.printStackTrace();
    }

Can anyone tell me how to properly use Between and Equal for date with criteria builder ?

TJ32
  • 293
  • 2
  • 7
  • 20
  • 1
    Does this answer your question? [Add CriteriaBuilder.between(Date) to Predicate?](https://stackoverflow.com/questions/41806152/add-criteriabuilder-betweendate-to-predicate) – Arvind Kumar Avinash Jul 03 '20 at 22:40

1 Answers1

0

I've always used your first approach, but not specifying the generic on the Path. Could you maybe try:

.add(criteriaBuilder.between(root.get("toDate"),
MyEntity.getFromDate(),MyEntity.getToDate()));

and most importantly, are you certain that the toDate field of your Entity is Annotated with @Temporal(TemporalType.TIMESTAMP)

Luiz Damy
  • 216
  • 2
  • 9