Skip to content Skip to sidebar Skip to footer

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

Solution 1:

try this code:

TimePickerFragmenttimePickerFragment=newTimePickerFragment();
            timePickerFragment.setOnTimeSetListener(newOnTimeSetListener() {
                publicvoidonTimeSet(TimePicker view, int hourOfDay, int minute) {
                    Calendardatetime= Calendar.getInstance();
                    Calendarc= Calendar.getInstance();
                    datetime.set(Calendar.HOUR_OF_DAY, hourOfDay);
                    datetime.set(Calendar.MINUTE, minute);
                    if (datetime.getTimeInMillis() >= c.getTimeInMillis()) {
                        //it's after currentinthour= 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

Solution 2:

The best solution for you will be to use this material design library to pick time or date and set min value.

    TimePickerDialog tpd = TimePickerDialog.newInstance(
        new TimePickerDialog.OnTimeSetListener() {
            @Override
            publicvoidonTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
                //put some interesting code
            }
        },
        now.get(Calendar.HOUR_OF_DAY),
        now.get(Calendar.MINUTE),
        true
    );
    tpd.setMinTime(10, 0, 0); // MIN: hours, minute, secconds
    tpd.show(getFragmentManager(), "TimePickerDialog");

The easiest way to add the Material DateTime Picker library to your project is by adding it as a dependency to your build.gradle

dependencies {
    compile'com.wdullaer:materialdatetimepicker:3.0.0'
}

Hope this will help you.

Post a Comment for "Android: Timepickerdialog Prevent User Select Past Time And Can Select Future Time With New Date"