I am dealing with the following problem. In my use case the user sets 2 dates upon first launch of the app, namely StartSleepingHours and StopSleepingHours.
For example, they could look like StartSleepingHours:Thu 2 Mar 20:00 2017
and StopSleepingHours:Thu 2 Mar 8:00 2017
(notice they are at the same date since this is the date they are set by the user). Now, my problem is that I have a periodic task that runs every 15 minutes to check if Now is between the interval StartSH and StopSH in order to determine whether or not to start an activity monitoring Service.
Obviously, I don't want my service to monitor the user's activity while sleeping. Currently, I am trying to extract only the Hour and Minute information from the StartSH and StopSH and create date objects from those in order to compare them with now but I am very confused and frustrated about how to check if now is within the interval Start/Stop SH in the future.
Currently I my code like that:
public static boolean isWithinSH(Date startSH, Date now, Date stopSH) {
boolean isSH = false;
Calendar calendar = Calendar.getInstance(Locale.UK);
calendar.set(Calendar.HOUR_OF_DAY, startSH.getHours());
calendar.set(Calendar.MINUTE, startSH.getMinutes());
Date sameDayStartSH = calendar.getTime();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
Date midnight = calendar.getTime();
calendar.add(Calendar.DAY_OF_WEEK, 1);
calendar.set(Calendar.HOUR_OF_DAY, stopSH.getHours());
calendar.set(Calendar.MINUTE, stopSH.getMinutes());
Date currentStopSH = calendar.getTime();
if (now.before(midnight) && now.after(sameDayStartSH)) {
System.out.println("SLEEPING HOURS");
isSH = true;
} else if (now.after(midnight) && now.before(currentStopSH)) {
System.out.println("SLEEPING HOURS");
isSH = true;
} else {
System.out.println("NOT SLEEPING HOURS");
}
return isSH;
}
I am trying to test the method in Java environment like that:
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance(Locale.UK);
calendar.add(Calendar.DAY_OF_WEEK, -1);
calendar.set(Calendar.HOUR_OF_DAY, 20);
calendar.set(Calendar.MINUTE, 0);
Date StartSH = calendar.getTime();
calendar.add(Calendar.DAY_OF_WEEK, 2);
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 45);
Date StopSH = calendar.getTime();
Date now = new Date(); // 9:42
if (isWithingSH(StartSH, now, StopSH)) {
System.out.println("SPEEPING HOURS");
} else {
System.out.println("NOT SPEEPING HOURS");
}
}
The console displays NOT SLEEPING HOURS but I think it should say SLEEPING HOURS since it is before 9:30