首页 > 解决方案 > 在 Kotlin 中距离 X 小时还有多少时间

问题描述

我想在 Kotlin for Android Studio 中执行以下操作:计算上午 10:00 还剩多少小时和分钟(始终是西班牙时间)。所以:

我怎样才能做到这一点?

标签: androiddatetimekotlin

解决方案


我使用 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

推荐阅读