我有字符串日期数组。 我需要填写3个ListViews, 今天列表,从本周开始的日期和从这个月开始的日期。 格式为:dd//mm//yy。 示例:
{"03.02.16","02.03.16","03.03.16","29.02.16"}
"03.03.16"-is today. "29.02.16"- is from last month but it was this week so i need to add it to this week list. "02.03.16"- need to be in this week and this month list.
在java/android中有一种方法可以对日期进行排序吗?
最佳答案
这是一个使用 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 .
关于java - 如何按今天/本周/本月对日期数组进行排序 - android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35779545/