You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android笔记App:按字符串日期时间排序ArrayList时thenComparing报错排查

问题分析与修复方案

核心错误点

  • 用LocalDate解析时间字符串
    你在thenComparing中调用LocalDate.parse(o.getTime(), t),但LocalDate仅用于处理日期(年/月/日),不包含时间维度。解析hh:mm格式的纯时间字符串必须使用LocalTime类,用LocalDate解析会直接抛出异常。

  • 排序方向不符合需求
    当前Comparator默认按日期、时间升序排列(旧条目在前),但你需要最新条目在顶部,必须对整个比较器做逆序处理。

  • 潜在格式歧义
    hh:mm是12小时制格式,需要配合AM/PM标记(如03:45 PM)才能正确解析。如果你的时间是24小时制存储(如15:45),必须把格式改为HH:mm(大写H对应24小时制),否则会解析失败。


修复后的代码

public static ArrayList<Note> loadAll(Context context) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(STORE_PREF, Context.MODE_PRIVATE);
    ArrayList<Note> notes = new ArrayList<>();
    Set<String> noteIds = sharedPreferences.getStringSet(ID_KEY, null);

    if (noteIds != null) {
        for (String noteId : noteIds) {
            notes.add(load(context, noteId));
        }
    }

    DateTimeFormatter dateFormatter;
    DateTimeFormatter timeFormatter;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        dateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
        // 若为24小时制时间用HH:mm,12小时制带AM/PM用hh:mm a
        timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
        
        notes.sort(Comparator
                .comparing(o -> LocalDate.parse(o.getDate(), dateFormatter))
                .thenComparing(o -> LocalTime.parse(o.getTime(), timeFormatter))
                // 逆序实现最新条目置顶
                .reversed());
    }
    return notes;
}

额外注意事项

  • 确保Note类的getTime()返回的字符串与timeFormatter格式完全匹配:
    • 24小时制时间必须是00:00至23:59格式
    • 12小时制时间需包含AM/PM标记(如03:45 PM),同时格式改为hh:mm a

内容的提问来源于stack exchange,提问作者amarradi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 13:30:24