I have to take an action if the time falls between start and stop time and on a specific day. I referred some existing threads on SO to check if the time falls within the specified time range.
Say if start time is 23:00pm, stop time is 7:00am and current time is 2:00am. Just the time validity function returns true. But if I include days in this code, the function returns false. Eg: user selects [Monday, Tuesday, Wednesday]. Even though Thursday is not in the list, but the end time 7:00am falls on Thursday, action can be taken anytime between 23:00pm Wed - 7:00am Thu, but action cannot be taken on 23:00pm Thu or any days not mentioned in the list.
Below is my code:
private fun isCurrentTimeBetweenProvidedTime(context: Context): Boolean {
var reg = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$".toRegex()
val startTime = getStartTime()
val endTime = getEndTime()
val currentTime = getCurrentTime()
if (reg.containsMatchIn(startTime) && reg.containsMatchIn(endTime) && reg.containsMatchIn(currentTime)) {
var valid = false
var startTime = SimpleDateFormat("HH:mm:ss").parse(startTime)
var startCalendar = Calendar.getInstance()
startCalendar.time = startTime
var currentTime = SimpleDateFormat("HH:mm:ss").parse(currentTime)
var currentCalendar = Calendar.getInstance()
currentCalendar.time = currentTime
var endTime = SimpleDateFormat("HH:mm:ss").parse(endTime)
var endCalendar = Calendar.getInstance()
endCalendar.time = endTime
if (currentTime.compareTo(endTime) < 0) {
currentCalendar.add(Calendar.DATE, 1)
currentTime = currentCalendar.time
}
if (startTime.compareTo(endTime) < 0) {
startCalendar.add(Calendar.DATE, 1)
startTime = startCalendar.time
}
if (currentTime.before(startTime)) {
valid = false
} else {
if (currentTime.after(endTime)) {
endCalendar.add(Calendar.DATE, 1)
endTime = endCalendar.time
}
if (currentTime.before(endTime)) {
valid = true
} else {
valid = false
}
}
// This won't work if day is Thursday and time is 2:00am, even though time falls between 23:00-7:00
var todayCalendar = Calendar.getInstance()
if ((currentTime >= startTime && todayCalendar.get(Calendar.DAY_OF_WEEK) in selectedDays.values) &&
(currentTime <= endTime && (todayCalendar.get(Calendar.DAY_OF_WEEK) in selectedDays.values || todayCalendar.get(Calendar.DAY_OF_WEEK)-1 in selectedDays.values))) {
Log.d(TAG, "Days are valid")
}
return valid
}
return false
}
How do I handle the days scenario?