'How to check if the current time is after or before a certain time in kotlin
I am trying to check if the current time (hours and minute) is after or before a certain time, how can I do it in kotlin
Solution 1:[1]
If you have a LocalDateTime or similar, you can extract the MINUTE_OF_DAY (which is basically hours + minutes) to compare the time and ignoring the rest, e.g.:
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
}
If you instead have a Date you may be interested in transforming it to an instance of a java.time-type before, e.g.:
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.
Finally if you want to use Calendar just be sure to compare only the things you are interested in, i.e. the hours and minutes and nothing more, e.g.:
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
}
Solution 2:[2]
You must first specify now and then the future time in two variables for comparison. You can then compare them with isBefore and isAfter to determine true/false on either.
val timeNow = LocalTime.now()
val timeTo = LocalTime.parse("15:00:00")
timeTo.isBefore(timeNow) // boolean for `before`
timeTo.isAfter(timeNow) // boolean for `after`
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Grant |
