计算日期,但日期来自具有getDateInstance方法的Date Picker

时间:2019-04-22 04:39:16

标签: android android-datepicker

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

代码

  

Details.java

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

        }
  

onDateSet

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

}

Screenshot of Date from Date Picker Dialog

1 个答案:

答案 0 :(得分:0)

找到一个解决方案:SimpleDateFormat myFormat = new SimpleDateFormat(“ MMMM dd,yyyy”,Locale.ENGLISH);

谢谢