Reputation:
I'm searching for an example with a function comparing a date and hours range for example in a restaurant for opening hours , the function return true if I put in parameters Sunday - Tuesday from 10:00 AM - 23:00 PM, What is the best way to do it? there is multiples date instances in Java/Kotlin I'm a little bit confused...
Upvotes: 1
Views: 1430
Reputation: 11
fun checkIfInRangeOfHours(startHour: String, endHour: String): Boolean {
val currentTime = Calendar.getInstance().time
val currentDate = SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).format(currentTime)
val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH)
val startDate: Date? = simpleDateFormat.parse("$currentDate $startHour")
val endDate: Date? = simpleDateFormat.parse("$currentDate $endHour")
return Date().after(startDate) && Date().before(endDate)
}
Upvotes: 0
Reputation: 355
I don't know if you no longer looking for an answer but this is the answer anyway
fun isNowInRange(start: LocalTime, stop: LocalTime, now: LocalTime): Boolean{
return ( ! now.isBefore( start ) ) && ! now.isAfter( stop )
}
and this is how to use it
isNowInRange(LocalTime.of(9, 0), LocalTime.of(23, 0) // opne
!isNowInRange(LocalTime.of(9, 0), LocalTime.of(23, 0) // closed
and if there is any restaurant that's open after 24 midnight you can write this
if (isNowInRange(LocalTime.of(9, 0), LocalTime.of(23, 0) && isNowInRange(LocalTime.of(0, 0), LocalTime.of(4, 0)){
// restaurant is open from 9am till 4am
// do stuff here
}else{
// restaurant closed from 4am till 9am
// do stuff here
}
Upvotes: 0
Reputation: 19605
The Kotlin-idiomatic way to do this would be to define your restaurant opening hours as a ClosedRange<T>
(where T
is some kind of date/time value, see further discussion below), and then use the in
operator to determine if your given time falls within that range. See Ranges and Progressions in the Kotlin documentation.
To define the range you use the rangeTo
function (or ..
operator) e.g.:
val range = start..end
You can then use the contains
function (or in
operator) e.g.
anInstant in range
to determine if the given instant anInstant
falls into the range or not.
As to the actual representation of the date/time values, it depends on your target platforms. If you are targeting JVM or Android, you can use any of the classes in java.time
. For example, you can use a zone-aware date representation like ZonedDateTime
, or one that ignores zones all-together like LocalDateTime
, or one that represents a particular Instant
in time regardless of zone, depending on your application's business rules for handling time zones.
If you are targeting multi-platform (e.g. native or JavaScript), then you'll probably want to look into a cross-platform library with date/time representations, like kotlinx-datetime.
Upvotes: 4