In Kotlin, using the new Time
library this is how i would do it.
Also don't forget to change the pattern strings to match your specific case. In your case the string pattern should be val dateTimePattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
, but please check other approaches if it does not match.
fun formatDateTime(dateString: String): String {
//change this to match your specific string
val dateTimePattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
val formatter = DateTimeFormatter.ofPattern(dateTimePattern).withZone(
ZoneOffset.UTC
)
val timeFormatter = DateTimeFormatter.ofPattern("hh:mm a")
val dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
// \u00A0 is used to prevent the view from breaking line between "10:10" and "PM"
val dateTime =
ZonedDateTime.parse(dateString, formatter).withZoneSameInstant(ZoneId.systemDefault())
val eventDateString = dateTime.format(dateFormatter)
val formattedTime = dateTime.format(timeFormatter)
.replace(" ", "\u00A0")
return "$eventDateString $formattedTime"
}
This question is a more complete discussion around this topic for anyone interested.