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

Android Studio中兼容API21+的Java安全日期格式转换方案

安全兼容API21+的日期格式化方案

针对你的需求,推荐使用Java 8+的java.time日期时间API(通过AndroidX兼容包支持API21+)替代存在安全隐患的Calendar和DateFormat。这套API线程安全、设计更合理,完全适配FirebaseUI的异步监听场景。

实现步骤

  1. 添加依赖(若未引入)
    在模块级build.gradle中添加AndroidX core-ktx依赖,它内置了java.time API的兼容层:

    implementation "androidx.core:core-ktx:1.12.0" // 可使用最新稳定版
    
  2. 完整格式化代码
    以下代码将Firebase的毫秒时间戳转换为「Thursday, 11th November 2022, 14:42」格式:

    // 1. 将毫秒时间戳转换为带时区的日期时间(使用系统默认时区,可按需指定)
    Instant instant = Instant.ofEpochMilli(model.sentOnDateInMilliseconds);
    ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
    
    // 2. 处理日期序数词(st/nd/rd/th)
    int dayOfMonth = zonedDateTime.getDayOfMonth();
    String daySuffix = getDaySuffix(dayOfMonth);
    
    // 3. 分别格式化日期和时间部分
    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("EEEE, d MMMM yyyy", Locale.getDefault());
    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm", Locale.getDefault());
    
    // 4. 拼接成目标格式
    String datePart = dateFormatter.format(zonedDateTime).replace(String.valueOf(dayOfMonth), dayOfMonth + daySuffix);
    String timePart = timeFormatter.format(zonedDateTime);
    String formattedDate = datePart + ", " + timePart;
    
    // 5. 设置到TextView
    textView.setText(formattedDate);
    

    辅助方法:获取日期序数后缀

    private String getDaySuffix(int day) {
        if (day >= 11 && day <= 13) {
            return "th";
        }
        switch (day % 10) {
            case 1: return "st";
            case 2: return "nd";
            case 3: return "rd";
            default: return "th";
        }
    }
    

方案优势

  • 线程安全:java.time下的所有类都是不可变线程安全的,避免了旧DateFormat/Calendar在多线程场景(如Firebase异步回调)中的格式化错误。
  • API21+兼容:通过AndroidX core-ktx无需额外引入重型库,适配范围完全符合需求。
  • 时区友好:使用ZonedDateTime确保时间转换遵循用户设备的时区,避免跨时区显示错误。
  • 格式可控:通过DateTimeFormatter可以灵活调整格式,自定义序数词处理完全匹配你需要的样式。

替代方案(可选)

如果不想手动处理序数词,也可以使用android.icu.text.DateFormatSymbols获取本地化的序数词,但需要注意部分低版本设备的ICU库兼容性,稳定性不如java.time方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 22:35:22