android - 在 Kotlin 中距离 X 小时还有多少时间
问题描述
我想在 Kotlin for Android Studio 中执行以下操作:计算上午 10:00 还剩多少小时和分钟(始终是西班牙时间)。所以:
- 如果是上午 8:45,则返回 1h45m
- 如果是 12:00 PM,则返回 22h0m
我怎样才能做到这一点?
解决方案
我使用 JVM 编写了这个,所以我不确定它是否适用于 Android,但我认为算法是正确的:
fun timeUntilInMadrid(hour: Int): Duration {
val timezone = ZoneId.of("Europe/Madrid")
val now = ZonedDateTime.now(timezone).truncatedTo(ChronoUnit.MINUTES)
val targetTime = LocalTime.of(hour, 0)
val targetDate =
if (now.toLocalTime() <= targetTime) now.toLocalDate()
else now.toLocalDate().plusDays(1)
val then = ZonedDateTime.of(targetDate, targetTime, timezone)
return Duration.between(now, then)
}
然后,您可以随意格式化Duration
。例如:
fun main() {
val duration = timeUntilInMadrid(10)
println("${duration.toHoursPart()}h${duration.toMinutesPart()}m")
}
发布时的输出:
18h40m
推荐阅读
- javascript - 处理 HTTP 请求时加载屏幕卡住
- python - 当 blob url 中有“En Dash”(–) 时,copy_blob 函数失败
- java - 用新的 WebClient API 替换 Spring KerberosRestTemplate
- python - 识别新的圆形图案,Python
- python - 如何确保从 csv 文件加载的数据框中的列被格式化为整数(没有十进制字符)
- node.js - 如何对连接数据进行排序?
- vst - 如何将我的 .vst3 插件提供给其他人?
- scala - Any 和 Unit 有什么区别?
- javascript - 如何使用 dc.js 和 crossfilter 使用动态数据创建面积图?
- r - Recursively import data from nested csv files and create a ID column with month and year from file name