2

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?

AndroidDev
  • 20,466
  • 42
  • 148
  • 239
  • try with this DateTime dt = new DateTime(year, monthOfYear+1, dayOfMonth, 0, 0, 0, 0) – Ravi Oct 12 '15 at 04:30
  • Well, certainly that will fix the problem, but is that the correct thing to do? If the month is zero-based, why aren't the year and day also? – AndroidDev Oct 12 '15 at 04:31

2 Answers2

0

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

Get date from datepicker using dialogfragment

Community
  • 1
  • 1
Akber
  • 521
  • 4
  • 10
0

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.

gian1200
  • 3,670
  • 2
  • 30
  • 59
  • You're right. Seems weird that the months are zero-based, but the other parameters are not. Live and learn, I guess. Thanks! – AndroidDev Oct 12 '15 at 04:35