简体   繁体   中英

Converting Timestamp value to 12/24 hour Time value in Kotlin

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.

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

Try these functions:

fun convertLongToTime(time: Long): String {
    val date = Date(time)
    val format = SimpleDateFormat("yyyy.MM.dd hh:mm aa")
    return format.format(date)
}

fun currentTimeToLong(): Long {
    return System.currentTimeMillis()
}

fun convertDateToLong(date: String): Long {
    val df = SimpleDateFormat("yyyy.MM.dd hh:mm aa")
    return df.parse(date).time
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM