Android DatePicker Fragment returns date one month prior

懵懂的女人 提交于 2020-01-21 18:52:46

问题


OK, this is bizarre. I have a DatePicker dialog that is really simple. The problem is that no matter what date I choose, the value that comes back is exactly one month prior to the date selected. Here is my code:

ACTIVITY

btnEventDate.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }
});

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    DateTime dt = new DateTime(year, monthOfYear, dayOfMonth, 0, 0, 0, 0);
    Log.d(Constants.TAG, "dt: " + dt.toString());
    Log.d(Constants.TAG, "str: " + dateHandler.convertDateToYYYY_MM_DDString(dt));
}

DatePickerFragment

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        return new DatePickerDialog(getActivity(), (OnDateSetListener)getActivity(), year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {}
}

When the dialog appears, it is clearly set to today's date. Say that I select October 12, 2015, the log output shows this:

dt: 2015-09-12T00:00:00.000-06:00
str: 2015-09-12

I must be missing something. Anyone know what I'm doing wrong?


回答1:


Months go from 0 to 12. From January to Undecimber.

Try comparing them against Calendar."MONTH".

Example: Calendar.OCTOBER == 9

Link: http://developer.android.com/reference/java/util/Calendar.html#MONTH.

Note: In case you use GregorianCalendar, you can ignore the thirteenth month.




回答2:


Please visit this link, i think month starts from 0 to 11, Please ignore if I am wrong.

Get date from datepicker using dialogfragment



来源:https://stackoverflow.com/questions/33073286/android-datepicker-fragment-returns-date-one-month-prior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!