Android DatePicker Fragment returns date one month

2020-04-21 06:32发布

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?

2条回答
家丑人穷心不美
2楼-- · 2020-04-21 06:46

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

Get date from datepicker using dialogfragment

查看更多
SAY GOODBYE
3楼-- · 2020-04-21 06:48

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.

查看更多
登录 后发表回答