我需要以泰文本地格式解析日期(例如,应该将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.chrono.ThaiBuddhistDate
完成此操作,请参见以下示例:
public static void main(String[] args) throws ParseException {
ThaiBuddhistDate tbd = ThaiBuddhistDate.now(ZoneId.systemDefault());
System.out.println(tbd.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
}
我在系统上得到的输出是
2562-10-24