我的列表中有一堆日期对象(其中 20 个),我想知道每个日期是否在两个日期间隔之间,即 startdate = 2005-09 和 enddate = 2009-07
如何检查这些条件?
List<DateObject> myDates = new ArrayList<>();
DateObject dates = new DateObject("1990-05-19,");
mydatesDates.add(dates);
dates = new DateObject("2004-07-25");
myDates.add(dates);
...这种模式持续了大约 20 个日期
最佳答案
本地日期
使用 LocalDate
类来表示不含日期时间和时区的纯日期值。
LocalDate ld = LocalDate.parse( "1990-05-19" );
将其收集到列表
中。
List<LocalDate> dates = new ArrayList<>(); // Pass an initialCapacity argument if you have one.
dates.add( ld ); // Repeat for all your `LocalDate` objects.
年月
为了进行比较,您似乎只关心年月。您可以使用 YearMonth
为此类。
YearMonth start = YearMonth.of( 2005 , 9 ); // Or pass Month.SEPTEMBER
YearMonth stop = YearMonth.of( 2009, 7 ); // Or pass Month.JULY
循环列表以查看其中任何一个是否太早或太晚。
List<LocalDate> tooEarly = new ArrayList<>();
List<LocalDate> tooLate = new ArrayList<>();
List<LocalDate> justRight = new ArrayList<>();
for (String date : dates) {
YearMonth ym = YearMonth.from( date );
if( ym.isBefore( start ) ) {
tooEarly.add( date );
} else if( ! ym.isBefore( stop ) ) { // Using Half-Open approach where ending is *exclusive*. Use “( ym.isAfter( stop ) )” if you want inclusive ending.
tooLate.add( date );
} else {
justRight.add( date );
}
System.out.println( "ERROR unexpectedly went beyond the if-else-else." );
}
关于Java 日期对象列表间隔检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40117308/