LocalDate comparison, getting orders between two dates

China☆狼群 提交于 2020-01-25 07:13:05

问题


    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))


来源:https://stackoverflow.com/questions/50563774/localdate-comparison-getting-orders-between-two-dates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!