将日期的月份格式化为 3 个首字母的字符串-Kotlin

ofi*_*471 0 date formatdatetime kotlin

我有这个日期“08/08/2019”,我希望它看起来像这样:“2019 年 8 月 8 日”,我尝试使用when但想知道是否有更简单的方法来做到这一点?我知道这是一个小问题,但我试图通过互联网找到答案,但我找不到。

tam*_*tom 5

首先,您需要将字符串转换为 Date 对象,然后使用新的java.time将其转换为您的格式

更新

val firstDate = "08/08/2019"
val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy")
val date = formatter.parse(firstDate)
val desiredFormat = DateTimeFormatter.ofPattern("dd, MMM yyyy").format(date)
println(desiredFormat) //08, Aug 2019
Run Code Online (Sandbox Code Playgroud)

旧答案

val firstDate = "08/08/2019"
val formatter = SimpleDateFormat("dd/MM/yyyy")
val date = formatter.parse(firstDate)
val desiredFormat = SimpleDateFormat("dd, MMM yyyy").format(date)
println(desiredFormat) //08, Aug 2019
Run Code Online (Sandbox Code Playgroud)