【发布时间】:2020-02-20 16:19:22
【问题描述】:
对于 Android 应用,我需要以泰语本地格式解析日期(例如,2019 年应返回为 2562)。我不明白我该怎么做。当前使用SimpleDateFormatter 以默认本地格式解析日期。
fun adjustTimePattern(dateString: String, oldPattern: String, newPattern: String): String? {
val dateFormat = SimpleDateFormat(oldPattern, Locale.getDefault())
dateFormat.timeZone = TimeZone.getTimeZone("UTC")
return try {
val calendar = Calendar.getInstance()
calendar.time = dateFormat.parse(dateString)
val newFormat = SimpleDateFormat(newPattern, Locale.getDefault())
newFormat.format(calendar.time)
} catch (e: ParseException) {
return null
}
}
尝试硬编码语言环境的值(使用 Locale("th", "TH") 而不是 Locale.getDefault()),但由于 SimpleDateFormat 类使用公历本身,所以很幸运。
也尝试过使用LocalDate & DateTimeFormatter,但年份值没有任何变化。
fun formatTime(pattern: String): String {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val formatter = DateTimeFormatter.ofPattern(pattern, Locale("th", "TH"))
LocalDate.now().format(formatter)
} else {
""
}
}
.
谁能帮我解决这个问题?
【问题讨论】:
-
您应该更喜欢java.time, the modern Java date and time API 中的课程。但是
LocalDate本质上是 ISO/proleptic 公历中的日期,因此不适用于泰语日期。答案显示了一个我认为很棒的解决方案。
标签: java android kotlin localdate thai