Skip to content
Advertisement

Show the current date in a Datepicker

I have two questions; my app has 2 textview datepickers, both of which I will use for a record.

My problem is:

1.- How can I do so that when displaying the datepicker (the box to choose the date); the current date is selected.

2.-How can I validate the start date with the end date according to my code; or in what way can I do it.

[enter image description here][1] [1]: https://i.stack.imgur.com/nYhiq.jpg

Start date

public void StartDate(View view){
    Calendar FI= Calendar.getInstance();
    diaI=FI.get(Calendar.DAY_OF_MONTH);
    mesI=FI.get(Calendar.MONTH);
    anioI=FI.get(Calendar.YEAR);

    DatePickerDialog datePickerDialog= new DatePickerDialog(this,new DatePickerDialog.OnDateSetListener() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            editTextFechaInicio.setText(dayOfMonth+"/"+(monthOfYear+1)+"/"+year);
        }
    }, diaI,mesI,anioI);
    datePickerDialog.show();
}

End Date

public void EndDate(View view){
    final Calendar FF= Calendar.getInstance();
    diaF=FF.get(Calendar.DAY_OF_MONTH);
    mesF=FF.get(Calendar.MONTH);
    anioF=FF.get(Calendar.YEAR);

    DatePickerDialog datePickerDialog= new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            editTextFechaFinal.setText(dayOfMonth+"/"+(month+1)+"/"+year);
        }
    }, diaF,mesF,anioF);
    datePickerDialog.show();
}

Advertisement

Answer

Answer of 1: Use GregorianCalendar instead of Calender like following:

GregorianCalendar gc = new GregorianCalendar()
int defaultDay = gc.get(Calender.DAY_OF_MONTH)
int defaultMonth = gc.get(Calender.MONTH)
int defaultYear = gc.get(Calender.YEAR)

String startDate;
DatePickerDialog dpd = new DatePickerDialog(ctx, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                        startDate = day + "/" + (month+1) + "/" + year
                        btndate.setText(startDate);
                    }
                },DefaultYear,DefaultMonth,DefaultDate);
dpd.show();

Answer of 2: Hide older date from start date into end date DatePicker

endDatePickerDialog.getDatePicker().setMinDate(startDate)

Hope this is helpful.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement