Search code examples
androidkotlinsimpledateformatandroid-calendartimezone-offset

How to change timezone of date android kotlin [HH:mm]


As input, I get a string like HH:mm, which is UTC. But I need to convert the time to +3 hours (i.e. UTC +3).

For example, it was 12:30 - it became 15:30.

I tried this code, but its not working :(

fun String.formatDateTime(): String {
    val sourceFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
    sourceFormat.timeZone = TimeZone.getTimeZone("UTC")
    val parsed = sourceFormat.parse(this)

    val tz = TimeZone.getTimeZone("UTC+3")
    val destFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
    destFormat.timeZone = tz

    return parsed?.let { destFormat.format(it) }.toString()
}

How can i do this?


Solution

  • You can use java.time for this and if you just want to add a specific amount of hours, you can use LocalTime.parse(String), LocalTime.plusHours(Long) and DateTimeFormatter.ofPattern("HH:mm"). Here's a small example:

    import java.time.LocalTime
    import java.time.format.DateTimeFormatter
    
    fun String.formatDateTime(hoursToAdd: Long): String {
        val utcTime = LocalTime.parse(this)
        val targetOffsetTime = utcTime.plusHours(hoursToAdd)
        return targetOffsetTime.format(DateTimeFormatter.ofPattern("HH:mm"))
    }
    
    fun main() {
        println("12:30".formatDateTime(3))
    }
    

    Output is simply 15:30.

    Try it with "22:30" and you'll get "01:30" as output.

    Please note that daylight saving time may cause problems if you are not supposed to just add three hours but consider a real time zone whose offset from UTC may change.