Android DatePickerDialog产生的值不正确

时间:2012-04-30 11:39:09

标签: android android-datepicker

我目前的问题是,当我将它们发送到Date构造函数时,从DatePickerDialog获取的值无法正确解析。

获取日期值(根据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);
    }
};

以上日志记录语句产生:

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

日期设置为....

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

我用....验证了截止日期

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);

导致....

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.

修改

设置初始DatePickerDialog值...

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

我应该/不应该做什么吗?

1 个答案:

答案 0 :(得分:4)

使用Calendar及其上的各种set()方法更新日期。

例如,this sample project的代码如下:

 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();
    }
  };

其中dateAndTimeCalendar