2017-09-01 96 views
0

我想從datepicker中獲取所選日期,但無法獲得正確的值。我的代碼如下。Android的DatePicker值顯示錯誤的值

View mView = getLayoutInflater().inflate(R.layout.set_date_layout, null); 

    dialog = new MaterialDialog.Builder(RemainderActivity.this); 
    dialog.title(R.string.set_date); 

    datePicker = (DatePicker) mView.findViewById(R.id.datePickerRemainder); 


    dialog.customView(mView, true); 
    dialog.positiveText(R.string.confirm_date); 
    dialog.negativeText(android.R.string.cancel); 
    dialog.cancelable(false); 
    dialog.onPositive(new MaterialDialog.SingleButtonCallback() { 
     @Override 
     public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { 

      DateFormat df = new SimpleDateFormat("dd-MM-yyyy"); 
      Log.d("YEAR", datePicker.getYear()+""); //Shows correct year as 2017 
      Date date = new Date(datePicker.getDayOfMonth(), (datePicker.getMonth() + 1),datePicker.getYear()); // Wrong date as 09-04-1907 
      String dateString = df.format(date); 
      txt_remainder_date_add.setText(dateString); 
     } 
    }); 
    dialog.build(); 
    dialog.show(); 
+0

你想什麼日期選擇和你包括兩個! – phpdroid

+0

我想選擇2017年9月2日它顯示08年8月8日..如果我選擇01年9月01日它顯示04年9月1907 –

+0

因爲在日期選擇器月從0開始而不是從1開始,請參閱我的代碼如下,並嘗試使用它,希望它適用於你 –

回答

0
private void datepicker() { 
    // Get Current Date 
    final Calendar c = Calendar.getInstance(); 
    int mYear = c.get(Calendar.YEAR); 
    int mMonth = c.get(Calendar.MONTH); 
    int mDay = c.get(Calendar.DAY_OF_MONTH); 

    DatePickerDialog datePickerDialog = new DatePickerDialog(this, R.style.DialogTheme, 
      new DatePickerDialog.OnDateSetListener() { 

       @Override 
       public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { 

        date_time = dayOfMonth + "-" + (monthOfYear + 1) + "-" + year; 
txt_remainder_date_add.setText(date_time); 
       } 
      }, mYear, mMonth, mDay); 
    datePickerDialog.show(); 
} 

凡在樣式定義我DialogTheme:

<style name="DialogTheme" parent="Theme.AppCompat.Light.Dialog"> 
    <item name="colorAccent">@color/colorPrimary</item> 
</style> 

調用此方法在任何你想

+0

這是否適用於23以下的api? –

+0

是@SharaafNazeer它將工作完全良好api15至25 –

+0

我得到的這裏是2-9-2017 ..我怎樣才能使它成爲02-09-2017? –

0

根據這一Link

您使用過時的代碼在下面的行中:

Date date = new Date(datePicker.getDayOfMonth(), (datePicker.getMonth() + 1),datePicker.getYear()); 

而不是使用日期類嘗試日曆類對象是這樣的...

Calendar cal = Calendar.getInstance(); 
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
System.out.println(sdf.format(cal.getTime())); 

你可以參考這個Link例如...