【问题标题】:How to check if the current time is after or before a certain time in kotlin如何检查当前时间是在kotlin中的某个时间之后还是之前
【发布时间】:2020-05-22 14:39:18
【问题描述】:

我正在尝试检查当前时间(小时和分钟)是否在某个时间之后或之前,我该如何在 kotlin 中做到这一点

【问题讨论】:

  • 你确定你的问题很清楚吗?我找不到匹配的两个词条
  • @LucaMurra 举个例子,我想检查一下当前时间是在 13:59 之后,所以我可以做一个动作
  • @7mood 问题仍未明确。您想与当前时间比较的时间的数据类型是什么?它是字符串、Java Date 实例、JavaScript Date 实例还是其他什么?您是在 JVM 上还是在其他地方使用 kotlin?
  • 请不要在标题中添加[SOLVED] 之类的内容,这不是系统的工作方式。此外,在您接受答案后不要更改问题。
  • 我只是把问题说得更清楚了

标签: kotlin


【解决方案1】:

您可以使用Calendar 类:

val currentTime = Calendar.getInstance()
val timeToMatch = Calendar.getInstance()

timeToMatch[Calendar.HOUR_OF_DAY] = hourToMatch
timeToMatch[Calendar.MINUTE] = minuteToMatch

when {
    currentTime == timeToMatch -> // the times are equals
    currentTime < timeToMatch -> // currentTime is before timeToMatch
    currentTime > timeToMatch -> // currentTime is after timeToMatch
}

【讨论】:

  • 我建议你反过来做,即从当前时间提取一天中的小时和分钟(另请参阅我答案的最后一部分)......否则在同一小时/分钟你会因为毫秒(和/或秒)偏差而产生差异......
  • 仅在使用时有效:timeToMatch.set(Calendar.HOUR_OF_DAY, HOUR)
【解决方案2】:

如果您有LocalDateTime 或类似名称,您可以提取MINUTE_OF_DAY(基本上是小时+分钟)来比较时间并忽略其余部分,例如:

val now = LocalDateTime.now()
val dateToCompare : LocalDateTime = TODO()

val minutesOfDayNow = now.get(ChronoField.MINUTE_OF_DAY)
val minutesOfDayToCompare = dateToCompare.get(ChronoField.MINUTE_OF_DAY)

when {
  minutesOfDayNow == minutesOfDayToCompare -> // same hour and minute of day
  minutesOfDayNow > minutesOfDayToCompare -> // hours and minutes now are after the time to compare (only in regards to hours and minutes... not day/month/year or whatever)
  minutesOfDayNow < minutesOfDayToCompare -> // hours and minutes now are before the time to compare... same conditions apply
}

如果您有 Date,您可能有兴趣将其转换为之前的 java.time 类型的实例,例如:

fun Date.minutesOfDay() = toInstant().atZone(ZoneId.systemDefault()).get(ChronoField.MINUTE_OF_DAY)

val now = Date()
val dateToCompare : Date = TODO()

if (now.minutesOfDay() > dateToCompare.minutesOfDay()) // ...etc. pp.

最后,如果您想使用Calendar,请确保只比较您感兴趣的内容,即小时和分钟,仅此而已,例如:

val now = Calendar.getInstance()
val nowInMinutes = now[Calendar.HOUR_OF_DAY] * 60 + now[Calendar.MINUTE]

val dateInMinutesToCompare = hours * 60 + minutes

when {
  nowInMinutes == dateInMinutesToCompare -> // equal
  nowInMinutes > dateInMinutesToCompare -> // now after given time
  else -> // now before given time
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多