Kotlin日期格式化:如何显示月份缩写(如Jan代表January)
解决方案
直接借助DateTimeFormatter的模式符号生成月份缩写,替代手动字符串处理,代码更简洁可靠:
修改后的代码:
private fun joinedDate(date: String): String { val parsedDate = LocalDateTime.parse( date, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX") .withLocale(Locale.getDefault()) ) // 用MMM模式获取月份缩写,输出"月份缩写, 年份"格式 val outputFormatter = DateTimeFormatter.ofPattern("MMM, yyyy") .withLocale(Locale.getDefault()) return parsedDate.format(outputFormatter) }
说明
MMM是DateTimeFormatter的标准模式符号,代表月份的缩写形式(例如January转为Jan,February转为Feb)。- 如果需要强制显示英文缩写(不受系统默认地区设置影响),可以把
Locale.getDefault()替换为Locale.ENGLISH。
内容的提问来源于stack exchange,提问作者user20108370
相关产品推荐
相关产品推荐

