Search code examples
androiddatetimeandroid-timepicker

Not to allow time picker to pick past time values


I'm implementing a time picker dialog in my project. It should not pick past values with respect to current time. I mean to set minimum and maximum time for picking.

Below is the process for timepicker I have done:

 // Current Hour
 hour = cal.get(Calendar.HOUR_OF_DAY);

 // Current Minute
 minute = cal.get(Calendar.MINUTE);

 return new TimePickerDialog(this, timePickerListener, hour, minute, false);

I have done the below process to date picker dialog. It worked, but for time picker I can't find any process.

For date picker :

Calendar calendar = Calendar.getInstance();

dialog = new DatePickerDialog(this, onDateSet, cYear, cMonth, cDay);
dialog.getDatePicker().setMinDate(calendar.getTimeInMillis());

So please help how to achieve this in time picker dialog.


Solution

  • You can use this as a starting point.

    You extend TimePickerDialog and added 2 methods setMin and setMax.

    In the onTimeChanged method check that the new time is valid with respect to the min/max times.

    It still needs some polishing though...

    public class BoundTimePickerDialog extends TimePickerDialog {
    
        private int minHour = -1, minMinute = -1, maxHour = 100, maxMinute = 100;
    
        private int currentHour, currentMinute;
    
        public BoundTimePickerDialog(Context context, OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView) {
            super(context, callBack, hourOfDay, minute, is24HourView);
        }
    
        public void setMin(int hour, int minute) {
            minHour = hour;
            minMinute = minute;
        }
    
        public void setMax(int hour, int minute) {
            maxHour = hour;
            maxMinute = minute;
        }
    
        @Override
        public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
            super.onTimeChanged(view, hourOfDay, minute);
    
            boolean validTime;
            if(hourOfDay < minHour) {
                validTime = false;
            }
            else if(hourOfDay == minHour) {
                validTime = minute >= minMinute;
            }
            else if(hourOfDay == maxHour) {
                validTime = minute <= maxMinute;
            }
            else {
                validTime = true;
            }
    
            if(validTime) {
                currentHour = hourOfDay;
                currentMinute = minute;
            }
            else {
                updateTime(currentHour, currentMinute);
            }
        }
    }