Anna Lam
Anna Lam

Reputation: 807

Android DatePickerDialog yields incorrect values

My problem at present is that the values obtained from the DatePickerDialog are not getting parsed correctly when I send them to the Date constructor.

Getting the date values (as per the suggestions from another post)....

private DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        mYear = year;
        mMonth = monthOfYear + 1;
        mDayOfMonth = dayOfMonth;
        String t = "listener => mYear=" + mYear + "; mMonth=" + mMonth +
                "; mDayOfMonth=" + mDayOfMonth + ";";
        Log.i(TAG, t);
    }
};

The above logging statement yields:

04-30 21:34:10.548: I/TodosActivity(29510): listener => mYear=2012; mMonth=5; mDayOfMonth=2;

The date is set with....

todo.setDueDate(new Date(mYear, mMonth, mDayOfMonth));

I verified the due date with....

String t = "setNewDueDate(Todo) => #" + todo.getId() + ": " + todo.getTitle() + " (" +
            todo.getText() + "). Created on " + format.format(todo.getCreatedDate()) +
            ". Last modified on " + format.format(todo.getModifiedDate()) +
            ". Due on " + format.format(todo.getDueDate()) + ".";
Log.i(TAG, t);

which resulted in....

04-30 21:34:05.703: I/TodosActivity(29510): setNewDueDate(Todo) => #1: Test (Test). Created on 30 Apr 2012 20:07:51. Last modified on 30 Apr 2012 20:55:27. Due on 31 Dec 1899 00:00:00.

EDIT:

Setting the initial DatePickerDialog values...

        return new DatePickerDialog(this, listener, cal.get(Calendar.YEAR),
                cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));

Is there anything that I should/should not have done?

Upvotes: 0

Views: 1189

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006594

Use Calendar and the various set() methods on it to update the date.

For example, this sample project has code like this:

 DatePickerDialog.OnDateSetListener d=new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int year, int monthOfYear,
                          int dayOfMonth) {
      dateAndTime.set(Calendar.YEAR, year);
      dateAndTime.set(Calendar.MONTH, monthOfYear);
      dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
      updateLabel();
    }
  };

where dateAndTime is a Calendar.

Upvotes: 4

Related Questions