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

Kotlin开发:如何在TextView中展示格式化本地日期

Android TextView 本地化日期格式化实现方案

实现思路

  • 优先使用官方提供的日期格式化工具,避免手动拼接字符串带来的适配问题
  • 格式化时指定系统本地语言配置,自动适配不同地区的日期显示习惯
  • 格式化完成后直接将结果字符串设置给TextView即可

具体代码实现

方案1:推荐方案(兼容全Android版本)

基于java.time包实现,是Android官方目前推荐的日期处理方案,minSdk低于26的项目开启core library desugaring即可使用:

  1. 先在Module级build.gradle中开启desugaring支持:
android {
    compileOptions {
        coreLibraryDesugaringEnabled true
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
}
dependencies {
    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.0.4'
}
  1. 业务代码实现
    Kotlin示例:
// 获取当前日期实例,如需处理时间戳可使用LocalDate.ofEpochDay()方法转换
val localDate = LocalDate.now()
// 配置格式化规则,Locale.getDefault()自动适配系统当前语言
val formatter = DateTimeFormatter.ofPattern("yyyy年M月d日 EEEE", Locale.getDefault())
// 格式化后直接设置给TextView
findViewById<TextView>(R.id.target_textview).text = localDate.format(formatter)

Java示例:

LocalDate localDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年M月d日 EEEE", Locale.getDefault());
String formatResult = localDate.format(formatter);
TextView targetTv = findViewById(R.id.target_textview);
targetTv.setText(formatResult);

方案2:低版本兼容方案(无需desugaring)

基于SimpleDateFormat实现,适合minSdk非常低的旧项目使用:
Kotlin示例:

val simpleDateFormat = SimpleDateFormat("yyyy年M月d日 EEEE", Locale.getDefault())
// 如处理时间戳可传入 Date(时间戳)
val formatResult = simpleDateFormat.format(Date())
findViewById<TextView>(R.id.target_textview).text = formatResult

Java示例:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年M月d日 EEEE", Locale.getDefault());
String formatResult = simpleDateFormat.format(new Date());
TextView targetTv = findViewById(R.id.target_textview);
targetTv.setText(formatResult);

常用格式化规则说明

  • yyyy:4位完整年份,如2024
  • M:1-2位月份,如9、12,使用MM则显示为09、12
  • d:1-2位日期,如3、15,使用dd则显示为03、15
  • EEEE:完整星期名称,如星期二,使用E则显示为简写周二
  • 如需展示时分秒,可在pattern中增加HH:mm:ss(HH为24小时制,hh为12小时制)

注意事项

  • 如需固定显示中文日期格式,将Locale.getDefault()替换为Locale.CHINA即可
  • 禁止手动拼接年、月、日、星期字符串,多语言环境下会出现不符合用户使用习惯的问题
  • 处理后端返回的时间戳时,注意单位转换:java中Date默认接收毫秒级时间戳,如后端返回秒级时间戳需要先乘以1000再转换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 15:06:02