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