Reputation: 838
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?
Upvotes: 2
Views: 10156
Reputation: 841
Since you're already using java.util.Calendar
and java.text.SimpleDateFormat
.
If you can change locale while instantiating your Calendar, this should work:
val thaiCalendar = Calendar.getInstance(Locale("th", "TH"))
println(thaiCalendar.get(Calendar.YEAR)) // prints 2562
But, if you just want to change the format, this worked for me:
val notThaiCalendar = Calendar.getInstance()
val thaiFormatter = SimpleDateFormat("yyyy-MM-dd", Locale("th", "TH"))
println(thaiFormatter.format(notThaiCalendar.time)) // prints 2562-10-24
EDIT
This solution was not tested on Android
Upvotes: 0
Reputation: 18568
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….
Upvotes: 4