I am trying to cross check if my selected calendar endtime is earlier than my selected calendar starttime on a 12 hour time period. Currently I am using 2 different attributes to store selected calendar starttime and endtime as follows:
@Override
public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
String am_pm = "";
Calendar datetime = Calendar.getInstance();
datetime.set(Calendar.HOUR_OF_DAY, hourOfDay);
datetime.set(Calendar.MINUTE, minute);
if (datetime.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (datetime.get(Calendar.AM_PM) == Calendar.PM)
am_pm = "PM";
String strHrsToShow = (datetime.get(Calendar.HOUR) == 0) ?"12":datetime.get(Calendar.HOUR)+"";
String strMinsToShow = minute < 10 ? "0"+minute : ""+minute;
if (isStartTimeClicked) {
starttime.setText(String.format("%s:%s %s", strHrsToShow, strMinsToShow, am_pm));
} else {
endtime.setText(String.format("%s:%s %s", strHrsToShow, strMinsToShow, am_pm));
}
isStartTimeClicked = false;
}
I just want to compare both of these start and end times selected such that, end time cannot be earlier or equal to starttime. (it has to be after start time, say starttime is 2pm, endtime should be atleast 2:01pm or later and cant be 11am etc). even a boolean function showing that the selected end time is earlier or later than start time will suffice, but i am not sure how to go about this on a 12 hour time period scale based on my code as shown above. Any ideas? Thanks in advance!
Function I use for timepicker:
public void openMyTimePicker() {
Calendar now = Calendar.getInstance();
TimePickerDialog tpd = TimePickerDialog.newInstance(
this,
now.get(Calendar.HOUR_OF_DAY),
now.get(Calendar.MINUTE),
false
);
tpd.show(getFragmentManager(), "Timepickerdialog");
}
In your end-time timepicker onTimeSet()
check time set in start-time timepicker
//You will need to declare enddatetime and startdatetime at class level
if (enddatetime.getTimeInMillis() >= startdatetime.getTimeInMillis()) {
int hour = hourOfDay % 12;
btnPickStartTime.setText(String.format("%02d:%02d %s", hour == 0 ? 12 : hour,
minute, hourOfDay < 12 ? "am" : "pm"));
} else {
Toast.makeText(getApplicationContext(), "Invalid Time", Toast.LENGTH_LONG).show(); // before time
}