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

Kotlin:如何将"08/08/2019"格式化为"08, Aug 2019"?

简便实现日期格式转换的方案

嘿,你完全不需要用复杂的when语句手动映射月份!借助Java 8+的日期时间API(Kotlin可直接调用),几行代码就能搞定这个格式转换,而且更健壮、易维护。

具体实现步骤

  • 解析原日期字符串:用DateTimeFormatter定义原格式dd/MM/yyyy,把字符串转成LocalDate对象;
  • 格式化为目标样式:再定义一个目标格式的DateTimeFormatter(dd, MMM yyyy),调用format方法就能得到想要的结果。

Kotlin代码示例

import java.time.LocalDate
import java.time.format.DateTimeFormatter

fun convertDateFormat(originalStr: String): String {
    // 定义输入格式的解析器
    val inputFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy")
    // 解析为LocalDate对象
    val date = LocalDate.parse(originalStr, inputFormatter)
    // 定义输出格式的格式化器(指定英文Locale确保月份缩写是英文)
    val outputFormatter = DateTimeFormatter.ofPattern("dd, MMM yyyy", java.util.Locale.ENGLISH)
    // 返回格式化后的字符串
    return date.format(outputFormatter)
}

// 测试一下
fun main() {
    println(convertDateFormat("08/08/2019")) // 输出: 08, Aug 2019
}

关键说明

  • MMM是日期格式符,会自动生成月份的英文缩写(比如Aug代表August);如果不指定Locale,会根据系统默认语言生成,加上Locale.ENGLISH可以确保输出的是英文月份,避免系统语言影响结果;
  • 这种方法比when语句更靠谱,不用手动维护月份和缩写的映射表,API已经帮我们处理了所有边界情况(比如不同月份的缩写、闰年等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:31:31