如何计算 android 中日期范围 material 选择器之间的天数

How to count number of days between date range material picker in android

如何计算日期范围选择器之间的天数

我正在尝试但没有解决方案请任何人帮助我

我急需数天 当用户 select 日期范围形成日期选择器范围时 然后设置文本总天数。

    try {

        String valu1 = String.valueOf(constraintsBuilder.setStart(calendar.getTimeInMillis()));
        String valu2 = String.valueOf(constraintsBuilder.setEnd(calendar.getTimeInMillis()));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy");
        Date date1 = simpleDateFormat.parse(valu1);
        Date date2 = simpleDateFormat.parse(valu2);
        long difference = Math.abs(date1.getTime() - date2.getTime());

        Log.i("Testing","days" +difference);
        textView.setText("days" +difference);

    }
    catch(Exception ex)
    {

        ex.printStackTrace();
    }

主要代码是

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    showDatePicker= findViewById(R.id.showDatepicker);
    textView=findViewById(R.id.textView);

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

    MaterialDatePicker.Builder builder = MaterialDatePicker.Builder.dateRangePicker();
    builder.setTitleText("Select Date");
  


    final MaterialDatePicker materialDatePicker = builder.build();

    showDatePicker.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            materialDatePicker.show(getSupportFragmentManager(),"DATE_PICKER");

        }
    });


    materialDatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener() {
        @Override
        public void onPositiveButtonClick(Object selection) {

            showDatePicker.setText(materialDatePicker.getHeaderText());


        }
    });
}

您可以使用类似的东西:

    MaterialDatePicker<Pair<Long, Long>> picker = builder.build();
    picker.show(getSupportFragmentManager(), picker.toString());

    picker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener<Pair<Long, Long>>() {
        @Override public void onPositiveButtonClick(Pair<Long,Long> selection) {
            Long startDate = selection.first;
            Long endDate = selection.second;

            long msDiff = endDate - startDate;
            long daysDiff = TimeUnit.MILLISECONDS.toDays(msDiff);
            

        }
    });