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

问题描述

我在这个主题上找到了不同的主题,但还没有找到合适的解决方案来解决我的问题。如何获取当前的 UTC 时间,例如添加 60 分钟,并以这种格式显示它:HH:mm:ss?是否可以?谢谢

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

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

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

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

标签: androidkotlintimesimpledateformatutc

解决方案


在这里使用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)
    )
}

在发布前几秒钟执行的输出是:

09:43:00

如果您支持比 26 更早的 API 版本,您可能会发现 Java 8 功能在此处不直接可用。
无论如何您都可以使用它们,只需阅读此问题的答案即可,最近的方法是API Desugaring


推荐阅读