1

I have a two strings values that represent opening hours of a shop like :

val startHour = "08:00"
val endHour = "19:00"

I want to check if shop is open by comparing current time between these two times. I tried like below :

val hourFormat = SimpleDateFormat("HH:mm:ss")
val startTime = hourFormat.parse(startHour)
val endTime = hourFormat.parse(endHour )

but I get parse exception.

Any one has an idea ?

Mohamed Jihed Jaouadi
  • 1,427
  • 4
  • 25
  • 44
  • https://stackoverflow.com/questions/17697908/check-if-a-given-time-lies-between-two-times-regardless-of-date – IntelliJ Amiya Jun 17 '20 at 17:42
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use java.time, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Jun 17 '20 at 17:58
  • `val now = LocalTime.now(ZoneId.systemDefault())` and then `if (now.isAfter(LocalTime.parse("08:00")) && now.isBefore(LocalTime.parse("19:00"))) { /* shop is open */ }`. – Ole V.V. Jun 17 '20 at 18:01
  • I posted a workable example in here: https://stackoverflow.com/a/68843482/4180169 Please, check it out. – protanvir993 Aug 19 '21 at 07:42

2 Answers2

1

Cant you say

val startHour = "08:00:00"

val endHour = "19:00:00"

?

0

Your variable doesn't contain :ss that why you have a parse error :) Then to compare time, I prefer to compare them as timestamp. Be careful to your GMT if you work in different country.