Android 计算日期,但日期来自日期选择器,其方法为getDateInstance

Android 计算日期,但日期来自日期选择器,其方法为getDateInstance,android,android-datepicker,Android,Android Datepicker,我需要计算两个日期之间的天数。但是,文本视图中日期的格式不同于SimpleDataFormat。例如,从对话框中拾取日期后,将显示的日期为2019年4月22日。但是,我无法计算天数,因为SimpleDataFormat的格式是“MM dd yyyy”,所以它应该是AP 22 2019 代码 Details.java onDateSet 找到了一个解决方案:SimpleDataFormat myFormat=新的SimpleDataFormat(“MMMM-dd,yyyy”,Locale.ENGL

我需要计算两个日期之间的天数。但是,文本视图中日期的格式不同于SimpleDataFormat。例如,从对话框中拾取日期后,将显示的日期为2019年4月22日。但是,我无法计算天数,因为SimpleDataFormat的格式是“MM dd yyyy”,所以它应该是AP 22 2019

代码

Details.java

onDateSet


找到了一个解决方案:SimpleDataFormat myFormat=新的SimpleDataFormat(“MMMM-dd,yyyy”,Locale.ENGLISH)

谢谢

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            l[0]= System.currentTimeMillis();
            datePicker.show(getSupportFragmentManager(),l[0]+"");
            startDateOrEndDate = true ;
        }
    });
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            datePicker.show(getSupportFragmentManager(),l[0]+"");
            startDateOrEndDate = false ;

            //SimpleDateFormat myFormat = new SimpleDateFormat("MM dd yyyy");
            SimpleDateFormat myFormat = new SimpleDateFormat("MM  dd yyyy");
            DateFormat.getDateInstance(DateFormat.LONG);
            String firstDate=chckIn.getText().toString();
            Date startDate = null;   // initialize start date
            String secondDate=chckOut.getText().toString();
            Date endDate   = null; // initialize  end date
            try {
                startDate = myFormat.parse(firstDate);
                endDate = myFormat.parse(secondDate);

                long duration  = endDate.getTime() - startDate.getTime();
                long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);

                String diffInDaysString = String.valueOf(diffInDays);

                beach_days.setText(diffInDaysString);

            } catch (ParseException e) {
                e.printStackTrace();
            }

        }
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
    Calendar c = Calendar.getInstance();
    c.set(Calendar.YEAR, year);
    c.set(Calendar.MONTH, month);
    c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
    l[0]= c.getTimeInMillis()+24*60*60*1000;
    String date = DateFormat.getDateInstance(DateFormat.LONG).format(c.getTime());
    System.out.println(date);

    /*MM dd yyyy*/
    TextView textView = (TextView) findViewById(R.id.checkInTV);
    TextView textView2 = (TextView) findViewById(R.id.checkOutTV);

    if (startDateOrEndDate) {
        textView.setText(date);
    } else {
        textView2.setText(date);
    }

}