如何获取datepicker中已更改的日期

时间:2011-10-28 13:49:30

标签: android android-datepicker

正在开发一个应用程序,它首先使用“Calendar.getInstance()”从DatePicker获取当前日期,然后用户更改日期。现在如何在更改后获取新日期?

2 个答案:

答案 0 :(得分:0)

Calendar cal = Calendar.getInstance();

DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener(){
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                cal.set(Calendar.YEAR, year);
                cal.set(Calendar.MONTH, monthOfYear);
                cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            }
        };
        return new DatePickerDialog(this, listener, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));

并将日期检索为字符串(星期五,28/10/2011 15:59:00:0)

SimpleDateFormat sdfDate = new SimpleDateFormat("EEEE, d/M/yyyy HH:mm:ss:S");
String date = sdfTime.format(new Date(cal.getTimeInMillis()));

答案 1 :(得分:0)

宣布这一点。

private static final int DATE_DIALOG_ID = 0;

在onCreate()

中添加此编码
 // add a click listener to the button
    date_text.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showDialog(DATE_DIALOG_ID);
        }
    });

    // get the current date      
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH); 
    String da = Integer.toString(mMonth)+"/"+Integer.toString(mDay)+"/"+Integer.toString(mYear);
    date_text.setText(da);

这是onCreate()

的一面
 private DatePickerDialog.OnDateSetListener mDateSetListener =
    new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        mYear = year;
        mMonth = monthOfYear;
        mDay = dayOfMonth;
        String selectedDate = Integer.toString(mMonth)+"/"+Integer.toString(mDay)+"/"+Integer.toString(mYear);
        date_text.setText(selectedDate);
        System.out.println("selected date is:"+selectedDate);
    }
};

@Override
protected Dialog onCreateDialog(int id)  {
    switch (id) {

    case DATE_DIALOG_ID:
        return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);        
    }
    return null;
}