android - 如何获取 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)
}
解决方案
在这里使用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
推荐阅读
- jenkins - 捕获组中的 Groovy 交换字符串
- java - Java:将 Float.MIN_NORMAL 除以 2,不得到 0.0f?
- python - re.findall() 查找所有包含负项的二元组
- postgresql - 为什么从数据库 postgresql 生成实体会引发很多错误?
- visual-studio - 从 Visual Studio 重新启动时测试过程未终止
- java - GPS位置的反距离加权插值
- ios - 如何使用 FBInstreamAdView 修复我的错误
- scichart - 使自定义 SciChart 注释在图形上可移动
- javascript - 单击其他菜单项时隐藏当前子菜单
- qt - QwtScaleWidget::scaleDivChanged 仅适用于旧语法