如何获取 UTC 的当前时间,添加一些分钟并将其转换为 Kotlin 中的指定格式

Raz*_*n22 2 time android utc simpledateformat kotlin

我发现了关于这个主题的不同主题,但尚未找到解决我的问题的正确方法。如何获取当前 UTC 时间,添加例如 60 分钟,并以这种格式显示:HH:mm:ss?是否可以?谢谢

我用它来获取 UTC 时间,但我不知道如何添加分钟并更改显示格式:

val df: DateFormat = DateFormat.getTimeInstance()
df.timeZone = TimeZone.getTimeZone("utc")
val utcTime: String = df.format(Date())
Run Code Online (Sandbox Code Playgroud)

我也尝试过这个功能,但它显示设备的当前时间:

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

deH*_*aar 7

使用java.time此处,您可以获取特定偏移量甚至时区的当前时间,然后使用所需的模式输出:

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)
    )
}
Run Code Online (Sandbox Code Playgroud)

在发布此消息之前几秒钟执行的输出是:

09:43:00
Run Code Online (Sandbox Code Playgroud)

如果您支持早于 26 的 API 版本,您可能会发现 Java 8 功能无法直接使用。无论如何你都可以使用它们,只需阅读这个问题
的答案,最新的方法是API Desugaring