For an Android app, I need to parse date in Thai local format (as like, year 2019 should be returned as 2562). I do not understand how can I do so. Currently using SimpleDateFormatter
to parse the date in default local format.
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
}
}
Tried to hardcode the value of locale (used Locale("th", "TH")
instead of Locale.getDefault()
), but got luck since SimpleDateFormat class uses Gregorian Calendar itself.
Have tried to use LocalDate
& DateTimeFormatter
as well, but the year value doesn't change by any means.
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 {
""
}
}
.
Can anyone help me out on this?
ThaiBuddhistDate
classYou can use a java.time.chrono.ThaiBuddhistDate
to get this done, see the following example:
public static void main(String[] args) throws ParseException {
ThaiBuddhistDate tbd = ThaiBuddhistDate.now(ZoneId.systemDefault());
System.out.println(tbd.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
}
The output I get on my system is
2562-10-24
Most java.time functionality is back-ported to Java 6 & Java 7 in the ThreeTen-Backport project. Further adapted for earlier Android (<26) in ThreeTenABP. See How to use ThreeTenABP….