我正在尝试交叉检查我选择的日历结束时间是否早于我在12小时时间段内选择的日历开始时间。目前我使用2个不同的属性来存储选定的日历开始时间和结束时间,如下所示:
@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;
}
我只想比较选择的这些开始和结束时间,结束时间不能早于或等于starttime。 (它必须在开始时间之后,比如说开始时间是下午2点,结束时间应该是至少下午2点01分或更晚,而不能是上午11点等)。甚至布尔函数显示所选择的结束时间早于或晚于开始时间就足够了,但我不知道如何根据我的代码在12小时的时间范围内进行此操作,如上所示。有任何想法吗?提前致谢!
我用于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");
}
在你的结束时间timepicker onTimeSet()
检查时间设置在开始时间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
}
您需要使用Date.after
或Date.before
功能
//Compare Date
if (endDate.before(startDate)) {
//End date is before start date
} else {
//End date is after start date
}