我有数组字符串日期。 我需要填写3个ListViews, 今天列表,本周的日期和本月的日期。 格式为:dd // mm // yy。 例如:
{"03.02.16","02.03.16","03.03.16","29.02.16"}
" 03.03.16" - 今天。 " 29.02.16" - 来自上个月,但就是这样 这周我需要将它添加到本周列表中。 " 02.03.16" - 需要进来 本周和本月名单。
有一种方法可以在java / android中对日期进行排序吗?
答案 0 :(得分:1)
这是使用JSR-310的实现。在Android上,您可以使用Jake Wharton的端口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。