Cannot get the right date format in MaterialDatePicker android

Issue

I tried below code but i can not get the result which I want.

    MaterialDatePicker.Builder<Pair<Long, Long>> builder = MaterialDatePicker.Builder.dateRangePicker();
    builder.setTitleText("Select A Date");
    
    final MaterialDatePicker<Pair<Long, Long>> materialDatePicker = builder.build();
    
    date_picker.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            materialDatePicker.show(getActivity().getSupportFragmentManager(), "DATE_PICKER");
        }
    });
    
    materialDatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener<Pair<Long, Long>>() {
        @Override
        public void onPositiveButtonClick(Pair<Long, Long> selection) { 
        
            Long start = selection.first;
            Calendar start_cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
            start_cal.setTimeInMillis(start);
            SimpleDateFormat simpleDateFormat_start = new SimpleDateFormat("YYYY-MM-DD");
            start_date = simpleDateFormat_start.format(start_cal.getTime());
            
        
            Long end = selection.second;
            Calendar end_cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
            end_cal.setTimeInMillis(end);
            SimpleDateFormat simpleDateFormat_end = new SimpleDateFormat("YYYY-MM-DD");
            end_date = simpleDateFormat_end.format(end_cal.getTime());
            
            String final_text = start_date + "  to  " + end_date;
            date_picker.setText(final_text);
            Log.e("Check65", "Date : " + final_text);
            
        }
    });

I want
startdate: 2021-01-01
enddate: 2021-02-02

but i get
startdate: 2021-01-01
enddate: 2021-02-32

Solution

In your SimpleDateFormat you should use YYYY-MM-dd instead of YYYY-MM-DD as uppercase DD means day of the year and you want the day of the month. For reference

Answered By – Stoyan Milev

Answer Checked By – Dawn Plyler (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.