Search code examples
kotlindatedatetimetimezoneddatetime

How to know pattern of string date in kotlin


I want to convert in ZonedDateTime. How can I recognise pattern to pass in DateTimeFormatter.ofPattern(????????).

val string = "May 9, 2020 8:09:03 PM"

private fun getFormatDate(date: String): ZonedDateTime {
     val dateTimeFormatter = DateTimeFormatter.ofPattern(????????)
     return ZonedDateTime.parse(date, dateTimeFormatter)
}

Many Thanks


Solution

  • You can do:

    private fun getFormatDate(date: String): ZonedDateTime {
        val dateTimeFormatter =
            DateTimeFormatter
                .ofPattern("MMM d, yyyy h:mm:ss a")
                .withZone(ZoneId.systemDefault()) // or some other zone that you would like to use
                .withLocale(Locale.ENGLISH)
        return ZonedDateTime.parse(date, dateTimeFormatter)
    }
    

    Note that it is important that you do .withZone which specifies the zone that the ZonedDateTime is going to have, and also .withLocale, so that the parser interprets things like "May" and "PM" in the correct language.

    Try It Online

    See all the pattern letters here