从2个TimePickers获取值并进行比较

时间:2016-03-02 09:21:18

标签: java android android-timepicker

在我的应用程序中,我在我的活动中设置了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分钟。我该如何实现这一目标?另外,编写此代码的更好方法是什么?

感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

您可以使用方法“calendar.getTimeInMillis()”将calendar1与calendar2进行比较,如下所示:

int minutes =(int)((calendar2.getTimeInMillis() - calendar1.getTimeInMillis())/(1000 * 60));

答案 1 :(得分:1)

假设你希望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语句中切换顺序。

再见

答案 2 :(得分:0)

如果您有两个日期,可以通过以下条件检查这些日期:

  

如果(calendar1.isBefore(CALENDAR2)){   //条件在这里   }

你也可以检查isAfter

OR 如果你想检查至少3分钟添加日期,然后将它们拼凑为:

  

日历日历= Calendar.getInstance();           calendar.setTime(DAT1);           calendar.add(Calendar.MINUTE,dat2);

试试这个并告诉我它是否有帮助。