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
相关产品推荐
相关产品推荐

