sam88 sam88 - 2 months ago 22
Android Question

Android Studio - Datepicker not showing calendar from current year

in my Android Project i have a DatePicker which directly starts from year 1900.

Here is the source code:-

private void selectDate()
{
dpd = new DatePickerDialog(getActivity(),
new DatePickerDialog.OnDateSetListener()
{
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
c.set(year, monthOfYear, dayOfMonth);
selDate=year+"/"+monthOfYear+"/"+dayOfMonth;
Toast.makeText(getActivity(), dayOfMonth + "-" + (monthOfYear + 1) + "-" + year, Toast.LENGTH_LONG).show();
}
}, mYear, mMonth, mDay);
dpd.show();
}


Here is a screenshot of the same:-

Android DatePicker

As you can see the calendar starts from 1900 but i want it to start from the current date

Also, you can see '2' written on the top left corner, on clicking '2' i can change the year to whatever i want to; but I don't want the '2' symbol in my Date Picker/ how i should i change the name '2' to 'Change year' text?

What should be done? Where do i need to incorporate the necessary changes?

Thanks in advance.

I have edited my code as follows and now i am getting the current date i.e oct 2016

private void selectDate()
{
dpd = new DatePickerDialog(getActivity(),
new DatePickerDialog.OnDateSetListener()
{
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, monthOfYear);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
selDate=year+"/"+monthOfYear+"/"+dayOfMonth;
Toast.makeText(getActivity(), dayOfMonth + "-" + (monthOfYear + 1) + "-" + year, Toast.LENGTH_LONG).show();
}
}, mYear, mMonth, mDay);
dpd.getDatePicker().setMinDate(System.currentTimeMillis());
dpd.show();
}


And here is the updated screenshot:

enter image description here

Answer

Check out this code snippet

   DatePickerDialog dpd = new DatePickerDialog(MainActivity.this,
                new DatePickerDialog.OnDateSetListener() {
                    final Calendar myCalendar = Calendar.getInstance();
                    @Override
                    public void onDateSet(DatePicker view, int year,
                                          int monthOfYear, int dayOfMonth) {
                        // TODO Auto-generated method stub
                        myCalendar.set(Calendar.YEAR, year);
                        myCalendar.set(Calendar.MONTH, monthOfYear);
                        myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                        String myFormat = "yyyy-MM-dd"; //In which you need put here
                        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

                     //   expiry.setText(sdf.format(myCalendar.getTime()));

                    }
                }, mYear, mMonth, mDay);
        dpd.getDatePicker().setMinDate(System.currentTimeMillis());
        dpd.show();