как отключить предыдущую дату в средстве выбора даты?

Я использую григорианский календарь, и мне нужно отключить предыдущую дату до текущей даты в Android. Я уже проверил метод setMinDate, но он не работает. Кто-нибудь может мне помочь? вот мой код..

 public void SelectDateTime() {
        final View dialogView = View.inflate(getApplicationContext(), R.layout.date_picker_activate, null);
        DateTimeDialog = new AlertDialog.Builder(getApplicationContext()).create();
        dialogView.findViewById(R.id.cancelBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DateTimeDialog.dismiss();
            }
        });
        dialogView.findViewById(R.id.date_time_set).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.datePicker1);
                TimePicker timePicker = (TimePicker) dialogView.findViewById(R.id.timePicker);
                Calendar calendar = new GregorianCalendar(datePicker.getYear(),
                        datePicker.getMonth(),
                        datePicker.getDayOfMonth(),
                        timePicker.getCurrentHour(),
                        timePicker.getCurrentMinute());

                datePicker.getMinDate();

                final long today1 = System.currentTimeMillis() - 1000;

                calendar.after(System.currentTimeMillis());

               // datePicker.setMinDate(calendar.getTimeInMillis());

person Jameel Ahamed    schedule 08.06.2018    source источник
comment
вы можете использовать -github.com/wdullaer/MaterialDateTimePicker, а также установить минимальную и максимальную дату и время   -  person Adil    schedule 08.06.2018
comment
stackoverflow.com/questions/33051236/   -  person Adil    schedule 08.06.2018


Ответы (3)


Используйте этот код

    public static class DatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
        // dialog.getDatePicker().setMaxDate(c.getTimeInMillis());
        dialog.getDatePicker().setMinDate(c.getTimeInMillis());
        return dialog;
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        txt_date.setText(String.format(Locale.ENGLISH, "%02d/%02d/%d", day, month + 1, year));
    }
}

Вызовите этот метод, нажав боковую кнопку, как

DialogFragment newFragment = new DatePickerFragment();
            newFragment.show(getActivity().getSupportFragmentManager(), "datePicker");

Эта строка устанавливает минимальную дату - dialog.getDatePicker().setMinDate(c.getTimeInMillis());

и используйте это, чтобы установить максимальную дату

dialog.getDatePicker().setMaxDate(c.getTimeInMillis());

person Sanwal Singh    schedule 08.06.2018
comment
Удалите свой код и попробуйте этот код. Это работает в моем случае. - person Sanwal Singh; 08.06.2018
comment
Братан, мне нужен счетчик времени вместе с этим календарем .. не могли бы вы мне помочь? - person Jameel Ahamed; 08.06.2018
comment
Но здесь txt_date должен быть статическим, и я не хочу устанавливать его статическим. пожалуйста, дайте мне решение для этого - person Parth Patel; 15.06.2018

Это отключит предыдущие даты

public void showDateToSelect() {
        // Get Current Date
        final Calendar c = Calendar.getInstance();
        int mYear = c.get(Calendar.YEAR);
        int mMonth = c.get(Calendar.MONTH);
        int mDay = c.get(Calendar.DAY_OF_MONTH);
        /*DatePicker dialog to select date*/
        DatePickerDialog datePickerDialog = new DatePickerDialog(mContext,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        textView.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
                    }
                }, mYear, mMonth, mDay);
        /*To show only dates from today to future*/
        datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
        datePickerDialog.show();
    }
person Rakesh R    schedule 08.06.2018

Пользователь этой библиотеки

implementation 'com.github.florent37:singledateandtimepicker:1.2.1' 

И инициируйте со следующим кодом

 startSingleDateAndTimePickerDialog = new SingleDateAndTimePickerDialog.Builder(context);
            startSingleDateAndTimePickerDialog
                    .bottomSheet()
                    .curved()
                    .displayHours(true)
                    .displayMinutes(true)
                    .minDateRange(new Date(minDate))
                    .defaultDate(new Date(defaultDate))
                    .mustBeOnFuture()
.displayListener(new SingleDateAndTimePickerDialog.DisplayListener() {
                    @Override
                    public void onDisplayed(SingleDateAndTimePicker picker) {
                        //retrieve the SingleDateAndTimePicker
                    }
                })

                .title("Date & Time")
                .listener(new SingleDateAndTimePickerDialog.Listener() {
                    @Override
                    public void onDateSelected(Date date) {

                        Date currentDate = new Date(System.currentTimeMillis());



     String dateTime = getDate(date.getTime() / 1000);
textview.settext(dateTime);

                    }
                }).display();






 public static String getDate(long timeStamp) {
        Date time = new Date(timeStamp*1000);
        SimpleDateFormat df2 = new SimpleDateFormat("MMM dd,yyy h:mm a");
        return df2.format(time);
    }
person Ejaz Ahmad    schedule 08.06.2018
comment
привет братан, здесь я должен установить дату просмотра текста - person Jameel Ahamed; 08.06.2018