Home > database >  Converting Timestamp value to 12/24 hour Time value in Kotlin
Converting Timestamp value to 12/24 hour Time value in Kotlin

Time:12-16

I have to convert particular Timestamp value to Time. I can convert it to 24 hour format successfully. But getting minor issue in displaying or converting it to 12 hour format.

For the Timestamp : 1639588870 I am getting,

  1. 24 Hour format : 22:51 (correct)

  2. 12 Hour format : 22:51 PM (incorrect)

The 12 Hour format should be 10:51 PM instead of 22:51 PM

I am using below function to convert Timestamp value to my specific Time format display value :

fun getDateTime(timeStamp: String): String? {
    var sdf = SimpleDateFormat("HH:mm")
    try {
        if (prefManager.getDefaultTimeSelection().equals(TIME_24_HOUR)) {
            sdf = SimpleDateFormat("HH:mm")
        } else {
            sdf = SimpleDateFormat("HH:mm aa")
        }
        val netDate = Date(timeStamp.toLong() * 1000)
        return sdf.format(netDate)
    } catch (e: Exception) {
        return e.toString()
    }
}

What might be the issue in converting Timestamp to 12 Hour format ?

Thanks.

CodePudding user response:

The 12-hour format is hh (lowercase). HH is the 24-hour format.

You have to change this line

sdf = SimpleDateFormat("HH:mm aa")

to

sdf = SimpleDateFormat("hh:mm aa")

From the docs:

Letter  Date or Time Component
H       Hour in day (0-23)
h       Hour in am/pm (1-12)

Docs for the SimpleDateFormat class https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

  • Related