How to format the date and time?

Viewed 31

I'm writing a "Feed of posts" application on Kotlin. I faced with such a problem: The server sends the date and time of the post creation in such a format:

"2022-07-13T07:58:57.835201Z"

But I need something like this:

"13.07.2022 07:58"

I've tried something like this:

val pattern = "dd-MM-yyyy"
val simpleDateFormat = SimpleDateFormat(pattern)
val newDate = simpleDateFormat.format("2022-07-13T07:58:57.835201Z")

But when I do so, I get java.lang.IllegalArgumentException.

Can you please tell me how can I get the desired result?

1 Answers

If you can use java.time (introduced with Java 8), you can simply parse the input String to an OffsetDateTime, define a DateTimeFormatter for your desired output format and then apply it.

Here's how:

fun main(args: Array<String>) {
    // your example String
    val input = "2022-07-13T07:58:57.835201Z"
    // parse it to an OffsetDateTime
    val odt = OffsetDateTime.parse(input)
    // create the desired result String by applying the desired format
    val output = odt.format(DateTimeFormatter.ofPattern("dd.MM.uuuu HH:mm"))
    // print it
    println(output)
}

Output:

13.07.2022 07:58
Related