I want to parse this date in this format 2021-11-03T14:09:31.135Z (message.created_at)
My code is this:
val dateFormat = SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS")
var convertedDate = Date()
try {
convertedDate = dateFormat.parse(message.created_at)
} catch (e: ParseException) {
e.printStackTrace()
}
It is failing to parse
Don't use SimpleDateFormat it's long outdated and troublesome.
Use DateTimeFormatter to parse the date.
fun parseDate() {
var formatter: DateTimeFormatter? = null
val date = "2021-11-03T14:09:31.135Z" // your date string
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX") // formatter
val dateTime: ZonedDateTime = ZonedDateTime.parse(date, parser) // date object
val formatter2: DateTimeFormatter =
DateTimeFormatter.ofPattern("EEEE, MMM d : HH:mm") // if you want to convert it any other format
Log.e("Date", "" + dateTime.format(formatter2))
}
}
Output: Wednesday, Nov 3 : 14:09
To use this below android 8 , use desugaring
Well, the format not entirely what the string looks like:
T literal between the date and the timehh, which is 12-hour format. Use HH instead.This format should do it:
yyyy-MM-dd'T'HH:mm:ss.SSSX
However, note that Date and SimpleDateFormat are obsolete and troublesome. Use java.time instead. If your Android API level appears to be too low, you could use ThreeTen Backport.
If your minimum API level is 21, you can use API Desugaring, find some nice explanations about it here.
As soon as you have enabled API Desugaring, you can directly parse your ISO String to an OffsetDateTime:
val convertedDate = OffsetDateTime.parse(message.created_at)