Reputation: 11
I have Array of String dates. i need to fill in 3 ListViews, Today list ,dates from this week and dates from this month. Format is : dd //mm // yy. example:
{"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.
there is a way to sort date like that in java/android?
Upvotes: 1
Views: 1623
Reputation: 6419
This is an implementation using JSR-310. On Android, you can use Jake Wharton's port 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;
}
Update: you can also find the implementation here.
Upvotes: 2