datetimekotlinjava-timedatetimeformatteroffsetdatetime

Kotlin DateTimeParseException


Getting date from https://api.spacexdata.com/v3/launches This date have format: 2006-03-25T10:30:00+12:00. I want convert it to "dd, mm, yyyy", but always getting error: "java.time.format.DateTimeParseException: Text '2006-03-25T10:30:00+12:00' could not be parsed, unparsed text found at index 10"

my code:

val formatter = DateTimeFormatter.ofPattern("dd, mm, yyyy", Locale.US)
val myDate = LocalDate.parse(launchDate, formatter)

var launchDateConverted: String=  myDate.toString()

i getting data at String, then i convert it to date for formatting, and after i converting date back to string thats to display at UI. i used different methods, but cannot find the correct way. My current locale is "RU".


Solution

    1. Your formatter does not match the input format. Basically you need two formatters: one for input and one for output.
    2. The format "dd, mm, yyyy" is wrong: mm stands for minute of hour, not for month. You should use "dd, MM, yyyy".
    val launchDate = "2006-03-25T10:30:00+12:00"
    
    val inputFormatter = DateTimeFormatter.ISO_DATE_TIME
    val myDate = LocalDate.parse(launchDate, inputFormatter)
    
    val outputFormatter = DateTimeFormatter.ofPattern("dd, MM, yyyy", Locale.US)
    println(outputFormatter.format(myDate))