对于 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 的值(使用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 {
""
}
}
.
谁能帮我解决这个问题?