在我的应用程序中,我在活动中设置了2个TimePickers。当前,这是我从2个TimePickers中获取值的方式:

int hour1 = mFirstWakeUpTimePicker.getCurrentHour();
int min1 = mFirstWakeUpTimePicker.getCurrentMinute();
int hour2 = mSecondWakeUpTimePicker.getCurrentHour();
int min2 = mSecondWakeUpTimePicker.getCurrentMinute();

GregorianCalendar calendar1 = new GregorianCalendar();
GregorianCalendar calendar2 = new GregorianCalendar();

calendar1.set(Calendar.HOUR_OF_DAY, hour1);
calendar1.set(Calendar.MINUTE, min1);
calendar2.set(Calendar.HOUR_OF_DAY, hour2);
calendar2.set(Calendar.MINUTE, min2);


之后,我需要比较它们以检查它们是否至少相距3分钟。我该如何实现?另外,编写此代码的更好方法是什么?

任何帮助表示赞赏。

最佳答案

假设您希望calendar2相对于calendar1晚三分钟,您可以在从Timepickers获得小时数和分钟数后立即这样做:

GregorianCalendar calendar1 = new GregorianCalendar();
GregorianCalendar calendar2 = new GregorianCalendar();

calendar1.set(Calendar.HOUR_OF_DAY, hour1);
calendar1.set(Calendar.MINUTE, min1);
calendar2.set(Calendar.HOUR_OF_DAY, hour2);
calendar2.set(Calendar.MINUTE, min2);

long millisCal1 = calendar1.getTimeInMillis();
long millisCal2 = calendar2.getTimeInMillis();

if (millisCal2 - millisCal1 >= 1000 * 60 * 3){
    // They differ of at least three mins
} else {
    // They not differ of at least three mins
}


其中三分钟以毫秒为单位转换1000 * 60 * 3。
如果要在calendar2之后检查calendar1,只需在if语句中切换顺序即可。

再见

07-28 12:37