Search code examples
androiddatetimetimezonesimpledateformat

Get time in specific format from timestamp including TimeZone


I have a simple function to extract time from timestamp which is String.

timestamp(input)  : "2020-08-13T09:33:17Z"
outputTime(output): "09:33"
desired output    : "12:33"

function:

fun getTimeFromTimestamp(timestamp: String): String {
    val inputFormat: DateFormat = SimpleDateFormat("yyyy-MM-dd\'T\'HH:mm:ss\'Z\'", Locale.getDefault())
    val time = inputFormat.parse(timestamp) ?: Date()
    val outputFormat: DateFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
    val outputTime = outputFormat.format(time)

    return outputTime
}

Problem is that it does not take in effect of timezone in the output, which is GMT+3 in this case.

You can see my debug screenshot

How can I make sure that time is displayed including timezone that comes with it (GMT+3)?


Solution

  • The outputtime is in that format because you specified it as so ( HH:mm ) in this line

    val outputFormat: DateFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
    

    if you want it to include the time zone append the time zone to the output string

    edit

    "HH:mm zZ" seems to be doing the trick for me check out this fiddle