Home > other >  Is it possible to check if LocalTime.now is 9pm in Kotlin?
Is it possible to check if LocalTime.now is 9pm in Kotlin?

Time:11-06

It might be a stupid question but I'mm trying to do something like, if LocalTime.now is 9pm, do something. Is there a solution or any leads that might help me?

CodePudding user response:

You need to check if now is in a range of time close to 9pm. Otherwise, it will only be true if the code happens to be called during the 1 nanosecond that it is exactly 9pm. Something like:

if (LocalTime.now() in LocalTime.of(21, 0)..LocalTime.of(21, 1)) {
    //TODO
}

Or you could check if the hour and minute match if you just want to check if we are in the first minute of the hour:

if (LocalTime.now().run { hour == 21 && minute == 0 }) {
    //TODO
}

CodePudding user response:

Tenfour04's answer is fine. If you want to be less fancy (or more, depending who you ask)...

If you want to make this abstract and later harder to find by new developers, you can do something like:

fun LocalTime.isOclockAt(hour: Int) = this.hour == hour && this.minute == 0

And then confuse developers who are new to your team and leave them wondering how is this magic working when they see:

val now = LocalDate.Now()
if (now.isOclockAt(hour = 21)) {
  //...
}
  • Related