Kotlin中用SimpleDateFormat转换日期字符串14 Sep 2021报错
解决日期字符串解析失败问题
问题原因
SimpleDateFormat默认依赖当前系统的Locale,若系统Locale不是英文,就无法识别Sep这类英文月份缩写,进而导致解析失败。
解决方案1:为SimpleDateFormat指定英文Locale
修改代码时,在创建SimpleDateFormat实例时传入Locale.ENGLISH,确保能正确解析英文月份缩写:
private fun convertToDayAndMonth(date: String): String { val inputFormat = SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH) val dateObj: Date = inputFormat.parse(date)!! val outputFormat = SimpleDateFormat("d MMM", Locale.ENGLISH) return outputFormat.format(dateObj) }
注意:!!可能引发空指针异常,若输入日期格式不合法,建议替换为更安全的异常处理逻辑:
private fun convertToDayAndMonth(date: String): String? { return runCatching { val inputFormat = SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH) val dateObj = inputFormat.parse(date) ?: return null val outputFormat = SimpleDateFormat("d MMM", Locale.ENGLISH) outputFormat.format(dateObj) }.getOrNull() }
解决方案2:使用Java 8+新日期API(推荐)
SimpleDateFormat存在线程不安全问题,Java 8及以上版本推荐使用java.time包下的API,安全性和功能性更优:
import java.time.LocalDate import java.time.format.DateTimeFormatter import java.util.Locale private fun convertToDayAndMonth(date: String): String? { val inputFormatter = DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.ENGLISH) return runCatching { val localDate = LocalDate.parse(date, inputFormatter) val outputFormatter = DateTimeFormatter.ofPattern("d MMM", Locale.ENGLISH) localDate.format(outputFormatter) }.getOrNull() }
内容的提问来源于stack exchange,提问作者Dion Ng
相关产品推荐
相关产品推荐

