我正在尝试从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 :(得分: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>
在您想要的地方调用此方法
答案 1 :(得分: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例如......