1

我想更改 Material Date Picker 的格式。我从 2021 年 4 月 13 日的字符串中得到它。但我想更改为 2021-04-13 格式。

    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();
           
        }
    });

}

我在下面有一个错误。无法将给定对象格式化为日期

4

2 回答 2

3

addOnPositiveButtonClickListener侦听器将选定的日期作为Long值返回。
不要使用 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());

        }
    });

    
于 2021-04-13T14:28:35.580 回答
0

使用下面的代码

 @Override
    public void onPositiveButtonClick(Object selection) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy");

Date varDate=dateFormat.parse(start_DatePicker.getHeaderText());
dateFormat=new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Date :"+dateFormat.format(varDate));}
于 2021-04-13T14:06:44.440 回答