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?
Asked
Active
Viewed 171 times
0
-
maybe answers in [this question](https://stackoverflow.com/questions/50363541/schedule-a-work-on-a-specific-time-with-workmanager) can give you some references – Alun Paranggi Wicaksono Nov 05 '21 at 01:43
2 Answers
2
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
}

Tenfour04
- 83,111
- 11
- 94
- 154
-
1I mean.. you can also check `LocalTime.now().hour == 21 && LocalTime.now().minute == 0` – Martin Marconcini Nov 05 '21 at 15:23
-
Yeah, that's simpler if we want the range to be a set number of minutes. The range is more flexible if you want to do +/- or something more specific, like a span of seconds. – Tenfour04 Nov 05 '21 at 15:26
-
0
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)) {
//...
}

Martin Marconcini
- 26,875
- 19
- 106
- 144
-
1Although i'm new to android dev and i'm not having a team, i will give it a try. Nevertheless thank you very much. – Zupermar Nov 08 '21 at 22:23
-
I was being a bit sarcastic of course. There's nothing inherently wrong with extending classes (Objective-C people have been doing it under the _disguise_ of **Categories** for years), but you have to be careful not to overdo it, because then it becomes a bit hard to know what's custom and what's part of the Foundation libraries of Kotlin/Android. (And also, too much smart logic tends to cause troubles in the future). If you have a use-case for this behavior, then by all means :) The hardest part is finding a good name. :) – Martin Marconcini Nov 09 '21 at 08:26