0

I would like to reformat a string from 14 Sep 2021 to 14 Sep using the SimpleDateFormat or any other APIs.

Currently my code looks like this:

 private fun convertToDayAndMonth(date: String): String{
   val dateFormat: Date = SimpleDateFormat("dd MMM yyyy").parse(date)!!
   return SimpleDateFormat("d MMM").format(dateFormat)

but i am getting an error that says "14 Sep 2021" cannot be parsed

Dion Ng
  • 26
  • 3
  • Works for me: https://pl.kotl.in/oPr-MrazZ what's your environment? – Foo L Jul 18 '22 at 06:58
  • 1
    It's probably a locale thing. Set your default locale or explicitly specify one for the formatter. – Jorn Jul 18 '22 at 07:56
  • I used loca.US but am still facing the same issue. I read from another stackoverflow post that it is due to Java 17 update? https://stackoverflow.com/questions/69267710/septembers-short-form-sep-no-longer-parses-in-java-17-in-en-gb-locale – Dion Ng Jul 21 '22 at 01:20

1 Answers1

1

must be just syntax errors in your code.

both of these work for me:

println(myConvertToDayAndMonth("14 Sep 2021"))
fun myConvertToDayAndMonth(dateString: String): String {
    val sdf: SimpleDateFormat = SimpleDateFormat("dd MMM yyyy")
    val date: Date = sdf.parse(dateString)
    return SimpleDateFormat("d MMM").format(date)
}

println(convertToDayAndMonth("14 Sep 2021"))
fun convertToDayAndMonth(date: String): String {
    val javaDate: Date = SimpleDateFormat("dd MMM yyyy").parse(date)!!
    return SimpleDateFormat("d MMM").format(javaDate)
}
Dirk Hoffmann
  • 1,444
  • 17
  • 35