上个月带有 DatePicker 的日历总是 returns,即使我添加 + 1
Calendar with DatePicker always returns last month even if I add + 1
我试图从 Calendar 对象获取 Year-Month-Day,我知道月份从索引 0 开始。所以我向 month 对象添加了 +1。但它仍然给了我从选择器到日期选择器的最后一个月。
我哪里错了?
这就是我正在尝试的方式。
这是我的fragmentActivity
public class MyDatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH) + 1;
int year = calendar.get(Calendar.YEAR);
DatePickerDialog myDatePicker =
new DatePickerDialog(getActivity(), this, year, month, day);
return myDatePicker;
}
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
EditText et = (EditText) getActivity().findViewById(R.id.editTextDate1);
et.setText(year+"-"+month+"-"+day);
}
}
这是我的 MainActivity
EditText ed2;
ed2 = (EditText) findViewById(R.id.editTextDate2);
ed2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DialogFragment myDatePickerFragment = new MyDatePickerFragmentTo();
myDatePickerFragment.show(getSupportFragmentManager(),"datePicker");
}
});
如 documentation: 中所述,onDateSet()
以从零开始的月份调用
monthOfYear
The month that was set (0-11) for compatibility with Calendar
.
你也需要调整那里的月份值。
我试图从 Calendar 对象获取 Year-Month-Day,我知道月份从索引 0 开始。所以我向 month 对象添加了 +1。但它仍然给了我从选择器到日期选择器的最后一个月。
我哪里错了?
这就是我正在尝试的方式。
这是我的fragmentActivity
public class MyDatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH) + 1;
int year = calendar.get(Calendar.YEAR);
DatePickerDialog myDatePicker =
new DatePickerDialog(getActivity(), this, year, month, day);
return myDatePicker;
}
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
EditText et = (EditText) getActivity().findViewById(R.id.editTextDate1);
et.setText(year+"-"+month+"-"+day);
}
}
这是我的 MainActivity
EditText ed2;
ed2 = (EditText) findViewById(R.id.editTextDate2);
ed2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DialogFragment myDatePickerFragment = new MyDatePickerFragmentTo();
myDatePickerFragment.show(getSupportFragmentManager(),"datePicker");
}
});
onDateSet()
以从零开始的月份调用
monthOfYear
The month that was set (0-11) for compatibility withCalendar
.
你也需要调整那里的月份值。