I have written some code for my Android app which checks if an event registration is in the next hour. To do this, I got the current time, and added 60 minutes to that to get the end time for the hour slot. This code works fine and all, but I see it doesn't work if the 60 minute time slot laps into the next day (if the start time is 23:11 and the end time is 00:11). Upon inspecting my date objects, I noticed Android Studio says my Date objects have some date information (1 Jan.. ). This is weird because I specified my time format to only have time information. Here is some of the code:
DateFormat timeFormat = new SimpleDateFormat("hh:mm aa", Locale.ENGLISH);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
DateFormat scanDateFormat = new SimpleDateFormat("yyyy/MM/dd");
//Some logic has been cut out
if (currentEventRegistrations.size() > 0) {
//We need to check for the earliest events
Event earliestEvent = null; //Keep a reference to the earlist event
for (int a = 0; a < currentEvents.size(); a++) {
Event thisEvent = currentEvents.get(a);
if (a == 0) {
earliestEvent = thisEvent;
} else {
Date nextEventDate = timeFormat.parse(thisEvent.getTime());
Date currentEventDate = timeFormat.parse(earliestEvent.getTime());
if (nextEventDate.compareTo(currentEventDate) <= 0) {
earliestEvent = thisEvent;
}
}
}
//Now that we have the earliest event happening today, we need to check if it is within 30 minutes
earliestEvent.setTime(earliestEvent.getTime().toUpperCase());
Date earlyEventDate = timeFormat.parse(earliestEvent.getTime());
Calendar now = Calendar.getInstance();
Date later = now.getTime();
String time = timeFormat.format(later);
now.add(Calendar.MINUTE, 60);
String timeEnd = timeFormat.format(now.getTime());
Date laterStart = timeFormat.parse(time);
Date laterEnd = timeFormat.parse(timeEnd);
if (earlyEventDate.compareTo(laterStart) >= 0 && earlyEventDate.compareTo(laterEnd) <= 0)
{ //If the event is in the next 30 minute time frame, save all the event data
finalEvent = earliestEvent;
finalEventRegistration = getEventRegistration(earliestEvent.getEventId());
finalRoute = getRoute(finalEventRegistration.getSelectedRoute());
if (finalEvent!= null && finalEventRegistration != null && finalRoute != null) {
return true;
} else {
return false;
}
}
What would be the best way of converting a time string into a time object? Also, what would the best way be around dealing with time frames that may overlap into the next day?