Home > Enterprise >  kotlin SimpleDateFormat Unparseable date
kotlin SimpleDateFormat Unparseable date

Time:08-02

How to format date from String in kotlin?

I tried to parse it with a SimpleDateFormat but it always throws an Exception saying Unparseable date: "21 Agt 2022" when I try to parse the String.

This my code:

var spf = SimpleDateFormat("dd MMM yyyy")
val newDate = spf.parse("21 Agt 2022")  // <- always error in this line
spf = SimpleDateFormat("yyyy-MM-dd")
val result = newDate?.let { it1 -> spf.format(it1) }.toString()

My app is running on API 21, so can't use a java.time.LocalDate.

CodePudding user response:

You can use java.time and its LocalDate, you have two options so far:

The reason for the error is the missing Locale, which would be a problem in java.time as well:

The abbreviation Agt for August is only used in two Locales: Indonesia (where you seem to be from, at least judging from your profile page) and Kenia.

That means you can use your code, you just have to apply an Indonesian Locale:

fun main(args: Array<String>) {
    // prepare the locale your input was created in
    val indonesia = Locale.forLanguageTag("id-ID")
    // use it in your SimpleDateFormat
    var spf = SimpleDateFormat("dd MMM yyyy", indonesia)
    // parse the value
    val newDate = spf.parse("21 Agt 2022")
    // print the value
    println(newDate)
}

Output:

Sun Aug 21 00:00:00 CEST 2022

This will create a java.util.Date which is in fact more than day of month, month of year and year… It has a time of day, too, but your input String does not contain any. That means it will add one, the start of day, most likely.


Better / Newer / Date only: java.time

fun main(args: Array<String>) {
    // your input String
    val input = "21 Agt 2022"
    // prepare the locale your input uses
    val indonesia = Locale.forLanguageTag("id-ID")
    // prepare a DateTimeFormatter that considers Indonesian months
    val dtf = DateTimeFormatter.ofPattern("dd MMM uuuu", indonesia)
    // parse the String using the DateTimeFormatter
    val localDate = LocalDate.parse(input, dtf)
    // print the result
    println(localDate)
}

Output:

2022-08-21
  • Related