Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jetpack Compose Format Date String

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.

like image 535
Trailblazer Avatar asked Feb 05 '26 01:02

Trailblazer


1 Answers

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
like image 96
ahmed nader Avatar answered Feb 07 '26 19:02

ahmed nader