DatePickeDialog displays one month greater in android
当我按下按钮以显示DatePickerDialog时,对话框将显示一个月。 例如,如果我以这样的当前日期(使用joda库的DateTime)启动:
1 2 3 4 5 6 7 8 | DateTimeZone zone = DateTimeZone.forID("Europe/Athens"); DateTime dt = new DateTime(zone); int year = dt.getYear(); int month = dt.getMonthOfYear(); int day = dt.getDayOfMonth(); |
这是2014年8月8日,日期对话框将显示2014年9月9日一个月。
我不明白为什么会这样。
代表datePickerFragment的片段是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | @SuppressLint("ValidFragment") public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{ @SuppressLint("ValidFragment") TextView txtDate; GlobalData appState; public DatePickerFragment(TextView txtDate) { super(); this.txtDate = txtDate; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current date as the default date in the picker DateTimeZone zone = DateTimeZone.forID("Europe/Athens"); DateTime dt = new DateTime(zone); int year = dt.getYear(); int month = dt.getMonthOfYear(); int day = dt.getDayOfMonth(); Log.i("DatePickerFragment day month year", day +""+ month +""+ year +""); // Create a new instance of DatePickerDialog and return it return new DatePickerDialog(getActivity(), this, year, month, day); } public void onDateSet(DatePicker view, int year, int month, int day) { appState.setDateUserFrom(year, month, day); Log.i("Date day month yerar","Date changed." + day+"" + month +"" +year); txtDate.setText(new StringBuilder().append(day) .append("-").append(month).append("-").append(year) .append("")); } } |
DatePickerDialog接受
用这个:
1 | return new DatePickerDialog(getActivity(), this, year, month - 1, day); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current date as the default date in the picker DateTimeZone zone = DateTimeZone.forID("Europe/Athens"); DateTime dt = new DateTime(zone); int year = dt.getYear(); int month = dt.getMonthOfYear()-1; int day = dt.getDayOfMonth(); Log.i("DatePickerFragment day month year", day +""+ month +""+ year +""); // Create a new instance of DatePickerDialog and return it return new DatePickerDialog(getActivity(), this, year, month, day); } |
日期选择器中的月份从零开始。因此,您应该从getMonthOfYear()中减去一个以在datepicker上进行设置。
只是一个猜测。乔达月1月1日开始,但Java日期为0?因此,如果您将当前日期初始化与joda一起使用,则日期选择器将显示错误的月份。简单的解决方案:
1 | month = dt.getMonthOfYear() - 1; |
我很确定这背后的原因是因为Android DatePickerDialog期望基于0的月份值。 Jodatime如您所愿返回了它们(更加人性化)。因此,只需从月份中减去1。
需要澄清的是,大多数日期函数/库默认情况下都设计为基于0的月份值。明确指出的地方或第三方库(如Jodatime)例外,它们使处理日期变得很有趣。
尝试此希望它起作用:
1 2 3 4 5 6 7 8 | DateTimeZone zone = DateTimeZone.forID("Europe/Athens"); DateTime dt = new DateTime(zone); int year = dt.getYear(); int month = dt.getMonth(); int day = dt.getDayOfMonth(); |
要么
1 2 3 4 5 6 7 8 | DateTimeZone zone = DateTimeZone.forID("Europe/Athens"); DateTime dt = new DateTime(zone); int year = dt.getYear(); int month = dt.getMonthOfYear() - 1; int day = dt.getDayOfMonth(); |