androidmaterial-components-androidandroid-datepickermaterialdatepicker

How to change the format of Material Date Picker in YYY.MM-DD


I want to change the format of Material Date Picker. I am getting it from String its like 13 Apr 2021.But I want to change in 2021-04-13 format.

    Calendar calendar=Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    calendar.clear();

    Long today= MaterialDatePicker.todayInUtcMilliseconds();
    //materialDatePicker
    MaterialDatePicker.Builder start_builder=MaterialDatePicker.Builder.datePicker();
    start_builder.setTitleText("SELECT A  START DATE");
    start_builder.setSelection(today);

    
    start_DatePicker=start_builder.build();

    start_date.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            start_DatePicker.show(getSupportFragmentManager(),"Date_Picker");
        }
    });


    start_DatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener() {


        @Override
        public void onPositiveButtonClick(Object selection) {
            start_date.setText(start_DatePicker.getHeaderText());

           String get_start_date=start_date.getText().toString();
    DateFormat formatter = new SimpleDateFormat("yyyy MM dd");
    String today = formatter.format(get_start_date);

    String get_end_date=end_date.getText().toString();

    Toast.makeText(this, "Start Date"+today + "End date" +get_end_date, Toast.LENGTH_SHORT).show();
           
        }
    });

}

I have got an error below. Cannot format given Object as a Date


Solution

  • The addOnPositiveButtonClickListener listener returns the selected date as Long value.
    Don't use the HeaderText.

        start_DatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener<Long>() {
            @Override public void onPositiveButtonClick(Long selection) {
                Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
                calendar.setTimeInMillis(selection);
                SimpleDateFormat format = new SimpleDateFormat("yyyy MM dd");
                String formattedDate  = format.format(calendar.getTime());
    
            }
        });