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

标签 android kotlin time simpledateformat utc

我发现了有关此主题的不同主题,但尚未找到解决我的问题的正确方法。如何获取当前 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)
}

最佳答案

在这里使用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 功能无法直接使用。
无论如何,您都可以使用它们,只需阅读 this question 的答案即可,最近的方式是API Desugaring

关于android - 如何获取 UTC 的当前时间,添加一些分钟并将其转换为 Kotlin 中的指定格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67834076/

相关文章:

android - 使用 Jetpack Compose 登录 Facebook

android - generateSafeArgsDebug 任务执行时出错,XmlPullParserException 仅允许空白内容

java - 在kotlin中将接口(interface)定义为接口(interface)的属性并在接口(interface)实现中提供具体的实现是行不通的

c++ - 如何检测 LLVM pass 中的线程入口/生成点?

android - 为什么我不能回复 PlayStore 评论?

Android - 特定 View 上方的 PopupWindow

java - Android:如何在开关中使用 res/integers.xml 值?

kotlin - Ktor Websocket 身份验证

c++ - 如何在 C++ 中获得以毫秒为单位的系统启动时间?

javascript - new Date() vs Date() 为什么返回不同的时间(-2 小时)?