java - 如何按今天/本周/本月对日期数组进行排序 - android

标签 java android date collections

我有字符串日期数组。 我需要填写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/

相关文章:

java - Nutch 爬虫只能找到给定页面上的链接子集?

java - 更新 API Manager 2.0 和 IDS 5.2 的自定义声明 jar 文件

android - 无法在 getView 中选中/取消选中 CheckedTextView

android - 自定义 AlertDialog ScrollView,在 2.3 中太大,缺少确定按钮

c# - 如何将 javascript 数字日期转换为 C# 日期(使用 C#,而不是 javascript!)

Java 8 : Difference between two LocalDateTime in multiple units

java - JSF convertDateTime 呈现前一天

java - ReplaceAll Java方法从字符串中删除 "\\n"

android - AlarmManager.AlarmClockInfo 的 PendingIntent 是如何工作的?

r - 根据id和date-R合并数据集