Home > OS >  Parse "dd/mm/yyyy" into Date Kotlin
Parse "dd/mm/yyyy" into Date Kotlin

Time:11-21

I use an GET API request and I receive a string with the format "dd/mm/yyyy". I would like to know how to parse it into Date type in Kotlin.

Here you have my code but I receive error ' java.time.format.DateTimeParseException: Text '04/10/2022' could not be parsed at index 2'

 val dateProduct = LocalDate.parse(
                    jsonArray.getJSONObject(i).getString("Date"),
                    DateTimeFormatter.ofPattern("d / M / yyyy")
                )
                val expirationDate = Date
                    .from(dateProduct
                        .atStartOfDay()
                        .atZone(
                            ZoneId
                                .systemDefault()
                        )
                        .toInstant())

CodePudding user response:

RESOLVED thx @Alex.T:

val dateProduct = LocalDate.parse(
                jsonArray.getJSONObject(i).getString("Date"),
                DateTimeFormatter.ofPattern("dd/MM/yyyy")
            )
            val expirationDate = Date
                .from(dateProduct
                    .atStartOfDay()
                    .atZone(
                        ZoneId
                            .systemDefault()
                    )
                    .toInstant())
  • Related