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 ?

1

1 Answer 1

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)

0

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.