-1

My extension function:

    fun String.formatDate(): String {
        val outputFormat: DateFormat = SimpleDateFormat("MMM dd, yyyy hh:mm a")
        return outputFormat.format(SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.US).parse(this))
    }

When I send "2021-11-03 12:02:12", I get "Nov 03, 2021 12:02 AM"

It should be "Nov 03, 2021 12:02 PM" instead. (refer image below)

enter image description here

Suryakant Bharti
  • 673
  • 1
  • 6
  • 24
  • 2
    Don’t use `SimpleDateFormat`. It makes such trouble as this, and many other kinds too. Switch to java.time, the modern Java date and time API, and its `DateTimeFormatter`. – Ole V.V. Nov 17 '21 at 06:30
  • 1
    `return LocalDateTime.parse(this, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH)).format(DateTimeFormatter.ofPattern("MMM dd, yyyy hh:mm a", Locale.ENGLISH))` to get `Nov 03, 2021 12:02 PM`. – Ole V.V. Nov 17 '21 at 06:54

1 Answers1

1

Got it fixed. There was a minor error.

I was using hh as input format, which is 12-hour format. I needed to use HH instead.

return outputFormat.format(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).parse(this))

Suryakant Bharti
  • 673
  • 1
  • 6
  • 24