Android Joda-Time 与 Kotlin

Android Joda-Time with Kotlin

我正在尝试创建一个函数来检查给定的字符串时间 HH:mm 与现在相比在另一个范围内。

示例:如果当前小时在 12:35 和 15:00 之间 return true

但我总是得到 false 即使当前时间在范围内..

fun isTimeInRange(before: String, after: String): Boolean {
    val now = DateTime.now()
    val format = DateTimeFormat.forPattern("HH:mm")
    return now >= DateTime.parse(before, format) && now <= DateTime.parse(after, format)
}

您需要做的:

fun isTimeInRange(before: String, after: String): Boolean {
    val now = DateTime.now()
    val format = DateTimeFormat.forPattern("HH:mm")
    return now.isAfter(DateTime.parse(before, format)) && now.isBefore(DateTime.parse(after, format))
}

或使用intervals.

您必须将 before/after 日期设置为今天的日期。试试这个:

fun isTimeInRange(start: String, end: String): Boolean {
    val now = DateTime.now()
    val format = DateTimeFormat.forPattern("HH:mm")
    val startTime: LocalTime = format.parseLocalTime(start)
    val endTime: LocalTime = format.parseLocalTime(end)
    val timeZone = DateTimeZone.getDefault()
    val today: LocalDate = LocalDate.now(timeZone)
    val startMoment: DateTime = today.toLocalDateTime(startTime).toDateTime(timeZone)
    val endMoment: DateTime = today.toLocalDateTime(endTime).toDateTime(timeZone)
    return now.isAfter(startMoment) && now.isBefore(endMoment)
}