LocalDate comparison, getting orders between two d

2019-08-27 03:27发布

问题:

    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.

回答1:

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)


回答2:

I usually use “not before” as a short way to say “on or after”. And the other way around:

    w -> ! w.getUpdateDate().isBefore(parsedStartDate)
            && ! w.getUpdateDate().isAfter(parsedEndDate)

Depending on taste you may of course use the more wordy but also more direct

    w -> (w.getUpdateDate().isEqual(parsedStartDate) || w.getUpdateDate().isAfter(parsedStartDate))
            && (w.getUpdateDate().isBefore(parsedEndDate) || w.getUpdateDate().isEqual(parsedEndDate))