Search code examples
datekotlinparsinglocaldatedate-parsing

Parse "dd/mm/yyyy" into Date Kotlin


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())

Solution

  • 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())