I have the following date which we get from an API 2022-11-23 06:12:31
I am wondering if my approach is the best.
And I need to display in this format 23 November 2022
I am using substringbefore
to remove the time portion so I am left with the following: "2022-11-23"
I am using org.threeten.bp
val DAY_MONTH_YEAR_DISPLAY_FORMATTER =
DateTimeFormatter.ofPattern("dd MMMM yyyy").withZone(ZoneOffset.systemDefault())
fun formatAsFullMonthDisplayDate(localDateTime: String): String {
return try {
LocalDate.parse(localDateTime.substringBefore(" "), DAY_MONTH_YEAR_DISPLAY_FORMATTER).buildDate()
} catch (ignored: Exception) {
""
}
}
private fun LocalDate.buildDate(): String {
return buildString {
append(this@buildDate.dayOfMonth)
append(" ")
append(this@buildDate.month)
append(" ")
append(this@buildDate.year)
}
}
You can try this:
val inputDate = "2022-11-23 06:12:31"
val outputFormat = "dd MMMM yyyy"
val inputFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val outputFormatter = DateTimeFormatter.ofPattern(outputFormat)
val date = LocalDateTime.parse(inputDate, inputFormat)
val formattedDate = date.format(outputFormatter)
println(formattedDate) // "23 November 2022"