javaandroidandroid-studioandroid-fragmentsandroid-timepicker

android: TimePickerDialog prevent user select past time and can select future time with new date


I am using this link Android TimePickerDialog set max time.

I am new in android. With the help of this code, I cannot select past time but we cannot select future time. When 12 is selected in timepickerdialog mode change to am automatically according to the next day not past day.


Solution

  • try this code:

    TimePickerFragment timePickerFragment = new TimePickerFragment();
                timePickerFragment.setOnTimeSetListener(new OnTimeSetListener() {
                    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
                             int hour = hourOfDay % 12;
                        btnPickStartTime.setText(String.format("%02d:%02d %s", hour == 0 ? 12 : hour,
                                minute, hourOfDay < 12 ? "am" : "pm"));
                        } else {
                            //it's before current'
                            Toast.makeText(getApplicationContext(), "Invalid Time", Toast.LENGTH_LONG).show();
                        }
                    }
                });
                timePickerFragment.show(getSupportFragmentManager(), "TIME");
    

    it will show the timepicker dialog and if user select any time before current time... it will show invalid time..

    EDIT You need to import:

    import android.app.TimePickerDialog;
    import android.app.Fragment;
    import android.app.DialogFragment;
    import java.util.Calendar;
    import android.widget.TimePicker;
    

    Here is a Good Example