[英]Birthdays in the scope of java.time.LocalDate
I'm trying to select birthdays (independent of the year) within a Collection of java.time.LocalDate
.我正在尝试在
java.time.LocalDate
的集合中选择生日(与年份无关)。 Why LocalDate ?为什么是 LocalDate ? because this type seems the best for birthday.
因为这种类型似乎最适合生日。
Let's say I want to filter the birthdays between March 6 and April 30 irrespective of the year.假设我想过滤 3 月 6 日和 4 月 30 日之间的生日,而不考虑年份。 How to do this ?
这该怎么做 ?
If I were to do it, I would replace the year in LocalDate and use the method isAfter
and isBefore
.如果我要这样做,我会替换 LocalDate 中的年份并使用
isAfter
和isBefore
方法。 The fact that I have to change the year is just a plain hack.我必须更改年份这一事实只是一个简单的技巧。 Or I used the wrong data type (LocalDate)
或者我使用了错误的数据类型 (LocalDate)
I would rather use the type MonthDay which is the "date-without-year" and which is also comparable and offers methods like isAfter()
or isBefore()
.我宁愿使用类型MonthDay ,它是“没有年份的日期”,它也具有可比性,并提供诸如
isAfter()
或isBefore()
。 Furthermore, a MonthDay
can be extended to a LocalDate
using the method atYear(int)
.此外,可以使用
atYear(int)
方法将MonthDay
扩展为LocalDate
。
If you insist on LocalDate
then you should only use leap years because otherwise the 29th of February would be a problem.如果您坚持使用
LocalDate
那么您应该只使用闰年,否则 2 月 29 日将是一个问题。
List<LocalDate> birthdays = Arrays.asList(
LocalDate.of(1990, Month.JANUARY, 5),
LocalDate.of(1992, Month.MARCH, 7),
LocalDate.of(1995, Month.MAY, 5));
MonthDay filterFrom = MonthDay.of(Month.MARCH, 6);
MonthDay filterTo = MonthDay.of(Month.APRIL, 30);
List<LocalDate> filteredDates = birthdays.stream()
.filter(date -> {
MonthDay md = MonthDay.from(date);
return md.compareTo(filterFrom) >= 0 && md.compareTo(filterTo) <= 0;
})
.collect(Collectors.toList());
System.out.println(filteredDates);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.