Search code examples
androidkotlintimesimpledateformatutc

How to get the current time in UTC, add some minutes to it and the convert it to a specified format in Kotlin


I found different topics on this subject but couldn't find a proper solution to my problem yet. How can I get the current UTC time, add for example 60 minutes to it, and the display it in this format: HH:mm:ss ? Is it possible? Thanks

I used this to get the UTC time, but I don't know how to add minutes to it and the change the format to display:

val df: DateFormat = DateFormat.getTimeInstance()
df.timeZone = TimeZone.getTimeZone("utc")
val utcTime: String = df.format(Date())

I also tried this function but it displays the current time from the device:

fun getDate(milliSeconds: Long, dateFormat: String?): String? {
    val formatter = SimpleDateFormat(dateFormat)
    val calendar = Calendar.getInstance()
    calendar.timeInMillis = milliSeconds
    return formatter.format(calendar.time)
}

Solution

  • Use java.time here, you can get the current time of a specific offset or even time zone and output it afterwards using the desired pattern:

    import java.time.format.DateTimeFormatter
    import java.time.ZoneOffset
    import java.time.OffsetDateTime
    
    fun main() {
        val dateTime = getDateTimeFormatted(50, "HH:mm:ss")
        println(dateTime)
    }
    
    fun getDateTimeFormatted(minutesToAdd: Long, pattern: String): String {
        // get current time in UTC, no millis needed
        val nowInUtc = OffsetDateTime.now(ZoneOffset.UTC)
        // add some minutes to it
        val someMinutesLater = nowInUtc.plusMinutes(minutesToAdd)
        // return the result in the given pattern
        return someMinutesLater.format(
            DateTimeFormatter.ofPattern(pattern)
        )
    }
    

    The output of an execution some seconds before posting this was:

    09:43:00
    

    If you are supporting older API versions than 26, you might find out Java 8 features are not directly available there.
    You can use them anyway, just read the answers to this question, the most recent way is API Desugaring