如果我有一个本地日期列表,并且我需要将一个本地日期与该列表进行比较,并返回该日期之前的最后一个日期,那么最好的方法是什么。
例如,给定列表:
2019 01/01/2020 01/01/2021 01/01/2022
如果输入日期为30/12/2021,则希望返回01/01/2021
我想我应该迭代列表,直到找到给定日期不在之前的第一个日期,然后返回列表中的前一个条目(除非这是第一个条目,在这种情况下,我将不返回任何内容)
日期列表已按升序排序:
for (int i = 0; i < dates.size{}; i++)
{
if (myDate.before(dates[i]) {
if (i==0) {
return null;
}
else {
return dates[i-1];
}
}}
发布于 2019-09-22 07:09:26
尝试如下所示:
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// create list with some random dates
List<LocalDate> list = new ArrayList<>();
list.add(LocalDate.of(2019, 3, 12));
list.add(LocalDate.of(2019, 4, 11));
list.add(LocalDate.of(2019, 8, 10));
list.add(LocalDate.of(2019, 6, 9));
System.out.println(getMostRecentBeforeDate(LocalDate.now(), list));
}
// this is our comparing/filtering method
private static LocalDate getMostRecentBeforeDate(LocalDate targetDate, List<LocalDate> dateList) {
// we filter the list so that only dates which are "older" than our targeted date remain
// then we get the most recent date by using compareTo method from LocalDate class and we return that date
return dateList.stream().filter(date -> date.isBefore(targetDate)).max(LocalDate::compareTo).get();
}
}如果运行上面的代码,应该会得到2019-08-10作为输出,因为这是当前日期(LocalDate.now())之前的最近日期。
https://stackoverflow.com/questions/58036002
复制相似问题