Please, how do I format these date strings: 2017-04-08T18:39:42Z or 2023-04-04T14:01:31-07:00 to get something like this: August 04, 2017 | 6:39pm. Thanks in advance.
I have tried something like this below:
@RequiresApi(Build.VERSION_CODES.O)
private fun formatDate(date: String): String {
return try {
val datePattern = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss", Locale.ENGLISH)
val offSetDateTime = OffsetDateTime.parse(date, datePattern)
val formattedDate = "${offSetDateTime.month} ${offSetDateTime.dayOfMonth}, ${offSetDateTime.year}"
Log.i("formattedDate", formattedDate)
formattedDate
} catch (e: Exception) {
date
}
}
It did not work. It's return the string passed as an argument, in order word, it's throwing an exception.
OffsetDateTime.parse requires a string containing an offset (+/-hh:mm)
Parse it using LocalDateTime.parse
val dateSt = "2017-04-08T18:39:42Z"
val dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
val formattedDate = LocalDateTime.parse(dateSt, dateFormatter)
val res = DateTimeFormatter.ofPattern("MMMM dd, yyyy | hh:mma").format(formattedDate) // August 04, 2017 | 6:39pm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With