Search code examples
javahibernatejpalocaldate

LocalDate comparison, getting orders between two dates


    public List<WorkItem> getWorkItemsByDate(String startDate, String endDate) throws ParseException {
    LocalDate parsedStartDate = LocalDate.parse(startDate);
    LocalDate parsedEndDate = LocalDate.parse(endDate);
    return workItemRepository.findAll().stream().filter(w -> w.getUpdateDate().isAfter(parsedStartDate) &&
                                                w.getUpdateDate().isBefore(parsedEndDate))
                                                .collect(Collectors.toList());
}

I have two dates that I want to compare between and find all the workitems(has LocalDate) for the dates. I have one problem though I can't figure out how to check for the same date. When you run a date in my code it works fine untill you write the date that the item was created, then it does not work.

How do I make this work with say 2018-05-28 - 2018-05-28, if the items were created on this day it will not work in my lambda.


Solution

  • If the day is the same day it is not before, nor after, so it will return false in these cases.

    You can replace the isAfter and isBefore with a call to compareTo and check the int return value. Less clear in code, but still understandable.

    .filter(w -> w.getUpdateDate().compareTo(parsedStartDate) >= 0 && w.getUpdateDate().compareTo(parsedEndDate) <= 0)