Android:如何将当前时间与上一个时间选择器进行比较?

时间:2018-07-13 06:54:12

标签: android android-datepicker android-date

如果用户选择的时间小于当前时间,我想通知用户,我不想在时间选择器UI上显示它,仅通知用户。 以下是我当前的代码。

     final int mHour, mMinute;
        final Calendar c = Calendar.getInstance();
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);
        hour = c.get(Calendar.HOUR);
//if()
        // Launch Time Picker Dialog
        TimePickerDialog timePickerDialog = new TimePickerDialog(mainActivity, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
               if (hourOfDay >= mHour) {
                    String strTime = hourOfDay + ":" + minute + ":00";
                    renewalTime.setText(strTime);
                } else {
                    Toast.makeText(mainActivity, "Time cannot be lesser than current time", Toast.LENGTH_LONG).show();
                }

            }
        }, mHour, mMinute, false);

        timePickerDialog.show();

    }

所以当前正在发生的事情是,如果当前时间是12 PM或以后,它将取值为12,1,依此类推;对于11上午,则取值为23,依此类推。.那么在两种情况下如何进行比较? 谢谢。

2 个答案:

答案 0 :(得分:0)

public static boolean isTimeWith_in_Interval(String valueToCheck, String endTime, String startTime) {
    boolean isBetween = false;
    try {
        Date time1 = new SimpleDateFormat("HH:mm:ss").parse(endTime);

        Date time2 = new SimpleDateFormat("HH:mm:ss").parse(startTime);

        Date d = new SimpleDateFormat("HH:mm:ss").parse(valueToCheck);

        if (time1.after(d) && time2.before(d)) {
            isBetween = true;
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return isBetween;
}

答案 1 :(得分:0)

  

尝试此代码

  public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            Calendar datetime = Calendar.getInstance();
            Calendar c = Calendar.getInstance();
            datetime.set(Calendar.HOUR_OF_DAY, hourOfDay);
            datetime.set(Calendar.MINUTE, minute);
            if(datetime.getTimeInMillis() > c.getTimeInMillis()){
    //            it's after current
            }else{
    //            it's before current'
            }
        }