Dion Ng
Dion Ng

Reputation: 26

Date format using kotlin

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

Upvotes: 0

Views: 2307

Answers (1)

Dirk Hoffmann
Dirk Hoffmann

Reputation: 1563

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

Upvotes: 1

Related Questions