Android DatePicker change to only Month and Year

how to get month name from datepicker in android
how to set custom date in datepicker in android
android date picker
android-datepicker style
android:datepickermode
how to set default date in datepicker in android
datepicker android github
android material datepicker

I have a DatePickerDialog and I want view only Month and Year. How can I change this code?

public void chooseDate2(View v) {
    new DatePickerDialog(
        act.this,
        d1,
        dateAndTime1.get(Calendar.YEAR) + 2,
        dateAndTime1.get(Calendar.MONTH),
        dateAndTime1.get(Calendar.DAY_OF_MONTH)
    ).show();
}
private void updateLabel2() {
    scadenza.setText(fmtDateAndTime.format(dateAndTime1.getTime()));           
}
DatePickerDialog.OnDateSetListener d1=new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        dateAndTime1.set(Calendar.YEAR, year);
        dateAndTime1.set(Calendar.MONTH, monthOfYear);
        dateAndTime1.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        updateLabel2();
    }
};

Thanks

Try the following code. It will show a DatePicker with only the year and month (without day)

private DatePickerDialog createDialogWithoutDateField() {
        DatePickerDialog dpd = new DatePickerDialog(this, null, 2014, 1, 24);
        try {
            java.lang.reflect.Field[] datePickerDialogFields = dpd.getClass().getDeclaredFields();
            for (java.lang.reflect.Field datePickerDialogField : datePickerDialogFields) {
                if (datePickerDialogField.getName().equals("mDatePicker")) {
                    datePickerDialogField.setAccessible(true);
                    DatePicker datePicker = (DatePicker) datePickerDialogField.get(dpd);
                    java.lang.reflect.Field[] datePickerFields = datePickerDialogField.getType().getDeclaredFields();
                    for (java.lang.reflect.Field datePickerField : datePickerFields) {
                        Log.i("test", datePickerField.getName());
                        if ("mDaySpinner".equals(datePickerField.getName())) {
                            datePickerField.setAccessible(true);
                            Object dayPicker = datePickerField.get(datePicker);
                            ((View) dayPicker).setVisibility(View.GONE);
                        }
                    }
                }
            }
        } 
        catch (Exception ex) {
        }
        return dpd;
    }

This method returns a date picker dialog. So , in your button's onClick method add the following code to display your dialog.

createDialogWithoutDateField().show();

Android DatePicker change to only Month and Year, I have a DatePickerDialog and I want view only Month and Year How can I change this codepublic void chooseDate2View v new DatePicker You could also use some simple reflection to hide the day and month NumberPickers of a DatePicker widget. Do note that this may stop working if Google decides to rename the member field names.

As i recently stumbled across this problem myself, i tested multiple solutions from this post and similar questions on Stackoverflow.

Unfortunately i found no working solution especially for Android 5+

I ended up with implementing my own simple DialogFragment embedding two NumberPickers. This should be compatible with all versions from 3.0 and upwards.

Here is the code:

  public class MonthYearPickerDialog extends DialogFragment {

  private static final int MAX_YEAR = 2099;
  private DatePickerDialog.OnDateSetListener listener;

  public void setListener(DatePickerDialog.OnDateSetListener listener) {
    this.listener = listener;
  }

  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    // Get the layout inflater
    LayoutInflater inflater = getActivity().getLayoutInflater();

    Calendar cal = Calendar.getInstance();

    View dialog = inflater.inflate(R.layout.date_picker_dialog, null);
    final NumberPicker monthPicker = (NumberPicker) dialog.findViewById(R.id.picker_month);
    final NumberPicker yearPicker = (NumberPicker) dialog.findViewById(R.id.picker_year);

    monthPicker.setMinValue(0);
    monthPicker.setMaxValue(11);
    monthPicker.setValue(cal.get(Calendar.MONTH));

    int year = cal.get(Calendar.YEAR);
    yearPicker.setMinValue(year);
    yearPicker.setMaxValue(MAX_YEAR);
    yearPicker.setValue(year);

    builder.setView(dialog)
        // Add action buttons
        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int id) {
            listener.onDateSet(null, yearPicker.getValue(), monthPicker.getValue(), 0);
          }
        })
        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int id) {
            MonthYearPickerDialog.this.getDialog().cancel();
          }
        });
    return builder.create();
  }
}

And the layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="horizontal">

        <NumberPicker
            android:id="@+id/picker_month"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="20dp"
            android:layout_marginRight="20dp">

        </NumberPicker>

        <NumberPicker
            android:id="@+id/picker_year"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

        </NumberPicker>

    </LinearLayout>
</LinearLayout>

To show the layout use:

MonthYearPickerDialog pd = new MonthYearPickerDialog();
pd.setListener(this);
pd.show(getFragmentManager(), "MonthYearPickerDialog");

How to display date picker for android with only month and year fields?, This code will be used for showing the name of month and hiding date. Hide Expand Copy Code. et1.setOnClickListener(new View. Android default DatePicker show day/month/year fields but you have to customize this DatePicker as your requirements. Suppose that you want to show only month and year fields in android datepicker . To do this, you have to customize the Dialog DatePicker source code but it is not an easy task.

I don't recommend using Reflection to do this kind of thing.

There is a simpler and more pretty way to do so:

((ViewGroup) datePickerDialog.getDatePicker()).findViewById(Resources.getSystem().getIdentifier("day", "id", "android")).setVisibility(View.GONE);

Be aware that .getDatePicker() method from DatePickerDialog works on API LEVEL >= 11.

In addition it does not work on API LEVEL >= 21.

DatePicker, DatePicker : This value cannot be null . year, int : The year that was set. month  How to display date picker for android with only month and year fields? this change but I'm building for android 4.0.3 right now. Date picker with only month

More Advance form of Stephan Klein Answer .

As I have a requirement to make Year optional. And I have also handled date like february 28 and also handle leap year.

MonthYearPickerDialog

public class MonthYearPickerDialog extends DialogFragment {

    private DatePickerDialog.OnDateSetListener listener;
    private int daysOfMonth = 31;

    private NumberPicker monthPicker;
    private NumberPicker yearPicker;
    private NumberPicker dayPicker;

    private Calendar cal = Calendar.getInstance();

    public static final String MONTH_KEY = "monthValue";
    public static final String DAY_KEY = "dayValue";
    public static final String YEAR_KEY = "yearValue";

    int monthVal = -1 , dayVal = -1 , yearVal =-1 ;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle extras = getArguments();
        if(extras != null){
            monthVal = extras.getInt(MONTH_KEY , -1);
            dayVal = extras.getInt(DAY_KEY , -1);
            yearVal = extras.getInt(YEAR_KEY , -1);
        }
    }

    public static MonthYearPickerDialog newInstance(int monthIndex , int daysIndex , int yearIndex) {
        MonthYearPickerDialog f = new MonthYearPickerDialog();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt(MONTH_KEY, monthIndex);
        args.putInt(DAY_KEY, daysIndex);
        args.putInt(YEAR_KEY, yearIndex);
        f.setArguments(args);

        return f;
    }

    public void setListener(DatePickerDialog.OnDateSetListener listener) {
        this.listener = listener;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        //getDialog().setTitle("Add Birthday");

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // Get the layout inflater
        LayoutInflater inflater = getActivity().getLayoutInflater();

        View dialog = inflater.inflate(R.layout.month_year_picker, null);
        monthPicker = (NumberPicker) dialog.findViewById(R.id.picker_month);
        yearPicker = (NumberPicker) dialog.findViewById(R.id.picker_year);
        dayPicker = (NumberPicker) dialog.findViewById(R.id.picker_day);

        monthPicker.setMinValue(1);
        monthPicker.setMaxValue(12);


        if(monthVal != -1)// && (monthVal > 0 && monthVal < 13))
            monthPicker.setValue(monthVal);
        else
            monthPicker.setValue(cal.get(Calendar.MONTH) + 1);

        monthPicker.setDisplayedValues(new String[]{"Jan","Feb","Mar","Apr","May","June","July",
                "Aug","Sep","Oct","Nov","Dec"});


        dayPicker.setMinValue(1);
        dayPicker.setMaxValue(daysOfMonth);

        if(dayVal != -1)
            dayPicker.setValue(dayVal);
        else
            dayPicker.setValue(cal.get(Calendar.DAY_OF_MONTH));

        monthPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                switch (newVal){
                    case 1:case 3:case 5:
                    case 7:case 8:case 10:
                    case 12:
                        daysOfMonth = 31;
                        dayPicker.setMaxValue(daysOfMonth);
                        break;
                    case 2:
                        daysOfMonth = 28;
                        dayPicker.setMaxValue(daysOfMonth);
                        break;

                    case 4:case 6:
                    case 9:case 11:
                        daysOfMonth = 30;
                        dayPicker.setMaxValue(daysOfMonth);
                        break;
                }

            }
        });

        int maxYear = cal.get(Calendar.YEAR);//2016
        final int minYear = 1916;//1997;
        int arraySize = maxYear - minYear;

        String[] tempArray = new String[arraySize];
        tempArray[0] = "---";
        int tempYear = minYear+1;

        for(int i=0 ; i < arraySize; i++){
            if(i != 0){
                tempArray[i] = " " + tempYear + "";
            }
            tempYear++;
        }
        Log.i("", "onCreateDialog: " + tempArray.length);
        yearPicker.setMinValue(minYear+1);
        yearPicker.setMaxValue(maxYear);
        yearPicker.setDisplayedValues(tempArray);

        if(yearVal != -1)
            yearPicker.setValue(yearVal);
        else
            yearPicker.setValue(tempYear -1);

        yearPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                try {
                    if(isLeapYear(picker.getValue())){
                        daysOfMonth = 29;
                        dayPicker.setMaxValue(daysOfMonth);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });


        builder.setView(dialog)
                // Add action buttons
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        int year = yearPicker.getValue();
                        if(year == (minYear+1)){
                            year = 1904;
                        }
                        listener.onDateSet(null, year, monthPicker.getValue(), dayPicker.getValue());
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        MonthYearPickerDialog.this.getDialog().cancel();
                    }
                });

        return builder.create();
    }

    public static boolean isLeapYear(int year) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
    }
}

And I call it like

Calendar calendar = Calendar.getInstance();

        if(etBirthday.getText().length()> 0  ){
            if(checkIsYearAvailable(etBirthday.getText().toString().trim()))
                calendar = DateTimeOp.getCalendarFromFormat(etBirthday.getText().toString().trim(), Constants.dateFormat21);
            else
                calendar = DateTimeOp.getCalendarFromFormat(etBirthday.getText().toString().trim() + ", 1917",Constants.dateFormat21);
        }

        MonthYearPickerDialog pd = MonthYearPickerDialog.newInstance(calendar.get(Calendar.MONTH) + 1,
                calendar.get(Calendar.DAY_OF_MONTH),calendar.get(Calendar.YEAR));

        pd.setListener(new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) {

                String formatedDate = "";

                if(selectedYear == 1904)
                {
                    String currentDateFormat = selectedMonth + "/" + selectedDay;// + "/" + selectedYear;  //"MM/dd/yyyy"
                    formatedDate = DateTimeOp.oneFormatToAnother(currentDateFormat, Constants.dateFormat20, Constants.dateFormat24);
                }
                else{
                    String currentDateFormat = selectedMonth + "/" + selectedDay + "/" + selectedYear;  //"MM/dd/yyyy"
                    formatedDate = DateTimeOp.oneFormatToAnother(currentDateFormat, Constants.dateFormat0, Constants.dateFormat21);
                }

                etBirthday.setText(formatedDate);
            }
        });
        pd.show(getFragmentManager(), "MonthYearPickerDialog");

month_year_picker.xml

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">



    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="horizontal">

        <NumberPicker
            android:id="@+id/picker_month"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="20dp"
            android:layout_marginRight="20dp" />


        <NumberPicker
            android:id="@+id/picker_day"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="20dp"
            android:layout_marginRight="20dp" />

        <NumberPicker
            android:id="@+id/picker_year"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>
</LinearLayout>

DatePickerDialog, I can only traverse only through months. imagine setting dob for a 30+ yr old guy. date picker image. Android 8.0. Oxygen OS 5.0.2. @aniruddha simple date picker is created , but i have to show only year option to pick in android ICS . – user2021938 Jun 30 '14 at 9:58

Change default behaviour of date picker, We can define android DatePicker to show only a calendar view by using If we want to show the DatePicker in spinner format like showing day, month and year separately to To get only spinner mode date selection, then we need to set  I have two activities, in Activity A, I have datePicker which only display month and year. In Activity B, I want datePicker display only date, but can't find any solutions from internet. ScreenShot of Activity A. Assume user select Jun 2018. Then in Activity B, the datePicker will show Jun 2018 as the dialog title and only allow user to select the date.

Android DatePicker with Examples, Android Date Picker allows you to select the date consisting of day, month and year int arg2, int arg3) { // arg1 = year // arg2 = month // arg3 = day } }; Set Date. MonthAndYearPicker. Month and Year Picker allow user to pick only month and year or only month or only year as required. You will get notified for all action's such as on selection of date, on selection of month and on section of year.

Android - Date Picker, Picker dialog to pick only month and year OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int year, int month, int i2) { Toast. The above code will display the full month name and year like "August 2018" DateTimerPicker.CustomFormat = "MMMM yyyy"; The above code will display the full month name, date and year like "08 August 2018" DateTimerPicker.CustomFormat = "dd MM yyyy"; This line will give the date in the specified format with out forward slash "08 08 2018"

abhinav011085/MonthYearPicker: Picker dialog to pick only month , Android DatePicker is a user interface control which is used to select the date by day, We can use android:datePickerMode to show only calendar view. In the We can also show the DatePicker in spinner format like selecting the day, month and year In this file, we will add the DatePicker and Button widget and set their​  In the last step, you have to register the DatePickerDialog listener and override its onDateSet method. This onDateSet method contains the updated day, month and year. Its syntax is given below − Apart form date attributes, DatePicker object is also passed into this function.

Comments
  • Please see this link. This question has been asked before. stackoverflow.com/questions/10673842/…
  • Possible duplicate of Android - Hide date field in datepickerdialog
  • Look you my edit answer i test code and making some changing on it and it working with me well try it and feed me back
  • Thank you very much. Please can see my other question?[stackoverflow.com/questions/21343408/…
  • let us continue this discussion in chat
  • Reflection invokes methods which are available in the class. This method could disappear into thin air in the next version of Android. Reflection is not good choice.
  • Reflection, or modifying the layout to hide the column is always a hacky solution and is prone to break over the long term. Instead one should really make their own component. See Stephan's answer to this question: stackoverflow.com/a/31653048/1026805
  • Perfect for me. The only problem is that the default onDateSet is on this format: onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) | but on your custom dialog it's listener.onDateSet(null, 0, monthPicker.getValue(), yearPicker.getValue()); | So you're setting the year in "dayOfMonth"
  • Thanks! Working fine on Android 6.0.
  • For API 28 you should use getSupportFragmentManager() instead of getFragmentManager().
  • Not sure why, but I couldn't set listener.onDateSet(null, yearPicker.getValue(), monthPicker.getValue(), 0); I had to change the first parameter to DatePicker(context). It kept showing me a non-null value set to null error. Hope it helps
  • For those of us new to DatePickers, you must apply android:calendarViewShown="false" before using this.
  • Its not working in Android Studio but working fine on Eclipse any reason??