這是一個使用JSR-310的實施。在Android上,您可以使用傑克沃頓的端口ThreeTenABP。
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("dd.MM.yy");
final List<String> yourDates = someDates();
final List<LocalDate> dates = parseDates(yourDates);
final LocalDate today = getToday(dates);
final List<LocalDate> thisWeek = getDatesThisWeek(dates);
final List<LocalDate> thisMonth = getDatesThisMonth(dates);
...
@Nullable
private LocalDate getToday(List<LocalDate> dates) {
final LocalDate today = LocalDate.now();
for (LocalDate date : dates) {
if (today.equals(date)) {
return date;
}
}
return null;
}
private List<LocalDate> getDatesThisWeek(List<LocalDate> dates) {
final TemporalField dayOfWeek = WeekFields.of(Locale.getDefault()).dayOfWeek();
final LocalDate start = LocalDate.now().with(dayOfWeek, 1);
final LocalDate end = start.plusDays(6);
return getDatesBetween(dates, start, end);
}
private List<LocalDate> getDatesThisMonth(List<LocalDate> dates) {
final LocalDate now = LocalDate.now();
final LocalDate start = now.withDayOfMonth(1);
final LocalDate end = now.withDayOfMonth(now.lengthOfMonth());
return getDatesBetween(dates, start, end);
}
private List<LocalDate> getDatesBetween(List<LocalDate> dates, LocalDate start, LocalDate end) {
final List<LocalDate> datesInInterval = new ArrayList<>();
for (LocalDate date : dates) {
if (start.equals(date) || end.equals(date) || (date.isAfter(start) && date.isBefore(end))) {
datesInInterval.add(date);
}
}
return datesInInterval;
}
private List<LocalDate> parseDates(List<String> stringDates) {
final List<LocalDate> dates = new ArrayList<>(stringDates.size());
for (String stringDate : stringDates) {
dates.add(LocalDate.parse(stringDate, FORMATTER));
}
return dates;
}
更新:你還可以找到執行here。