Java 在Android中使用泰式日历解析特定格式的日期
对于Android应用程序,我需要以泰国本地格式解析日期(就像2019年应该返回2562年一样)。我不明白我怎么能这样做。当前正在使用Java 在Android中使用泰式日历解析特定格式的日期,java,android,kotlin,localdate,thai,Java,Android,Kotlin,Localdate,Thai,对于Android应用程序,我需要以泰国本地格式解析日期(就像2019年应该返回2562年一样)。我不明白我怎么能这样做。当前正在使用SimpleDataFormatter以默认本地格式解析日期 fun adjustTimePattern(dateString: String, oldPattern: String, newPattern: String): String? { val dateFormat = SimpleDateFormat(oldPattern, Locale.ge
SimpleDataFormatter
以默认本地格式解析日期
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()
),但由于SimpleDataFormat类本身使用公历,所以运气不错
也尝试使用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 {
""
}
}
有人能帮我解决这个问题吗?ThaiBuddhistDate
class
您可以使用来完成此操作,请参见以下示例:
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
在项目中,大多数java.time功能都向后移植到Java6和Java7。由于您已经在使用
java.util.Calendar
和java.text.SimpleDataFormat
,因此进一步适应了早期的Android()
如果您可以在实例化日历时更改区域设置,这应该可以:
val thaiCalendar = Calendar.getInstance(Locale("th", "TH"))
println(thaiCalendar.get(Calendar.YEAR)) // prints 2562
但是,如果您只是想更改格式,这对我很有用:
val notThaiCalendar = Calendar.getInstance()
val thaiFormatter = SimpleDateFormat("yyyy-MM-dd", Locale("th", "TH"))
println(thaiFormatter.format(notThaiCalendar.time)) // prints 2562-10-24
编辑
此解决方案没有在Android上测试过。您应该更喜欢来自的类。但是,
LocalDate
在ISO/proleptic Gregorian calendar中本质上是一个日期,因此不适用于泰国日期。答案显示了一个我认为很好的解决方案。@sudippoder是的,请参阅。您基本上必须使用支持库,这个问题是关于如何在Android中使用它。肯定会给你一个机会。如果它有效,会将你的答案标记为已接受的答案。你可以编辑你的答案,添加评论链接以及对API级别<26的支持。@BasilBourque OP已经这样做了,我删除了Android标记,因为我认为它只是关于java.time的。如果在一个问题下面可以写5个以上的标签。我在问题的开头提到了Android。@SudipPodder,只要你在1941年(gregorian)之前没有几年时间,这个解决方案(基于ThreetenABP)可以正常工作。仅供参考,有严重缺陷的日期时间类,如和java.text.SimpleDateFormat
,现在已被java 8和更高版本中内置的类所取代。我知道,但他在方法adjustTimePattern
的代码中使用了这些类,他将在@DiegoMagdalenoAndroid(在大多数移动平台上)上进行检查与旧Java相比有一个不同的日历
-实现,尤其是缺少佛教日历,所以这个答案可能不起作用。@MenoHochschild我真的没有在Android上测试它。我不知道有这么大的差异。