Skip to content

Instantly share code, notes, and snippets.

@usbportnoy
Created September 29, 2016 04:00
Show Gist options
  • Save usbportnoy/8227710eb280ffc8d33af9ae786e88c0 to your computer and use it in GitHub Desktop.
Save usbportnoy/8227710eb280ffc8d33af9ae786e88c0 to your computer and use it in GitHub Desktop.
public class OnlineStatus {
private int recentOnlineThresholdDays;
private int onlineThresholdHrs;
public enum States {Unknown, Online, Recent}
public void setOnlineThresholdHrs(int hours) {
this.onlineThresholdHrs = hours;
}
public void setRecentOnlineThresholdDays(int days) {
this.recentOnlineThresholdDays = days;
}
public States getStatus(Date lastOnline, Calendar calendar) {
if (onlineThresholdHrs <= 0) {
throw new IllegalArgumentException("Requires online threshold in hours");
}
int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
int currentDay = calendar.get(Calendar.DAY_OF_YEAR);
States state = States.Unknown;
if (hitsThreshold(
Calendar.DAY_OF_YEAR,
currentDay - recentOnlineThresholdDays,
lastOnline)) {
state = States.Recent;
}
if (hitsThreshold(
Calendar.HOUR_OF_DAY,
currentHour - onlineThresholdHrs,
lastOnline)) {
state = States.Online;
}
return state;
}
private boolean hitsThreshold(int calenderField, int value, Date time) {
Calendar calendar = Calendar.getInstance();
calendar.set(
calenderField,
value
);
Date threshold = calendar.getTime();
return time.after(threshold);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment