如何从datepicker获取值?

时间:2013-02-18 12:17:09

标签: android datepicker

我的app中有一个DatePicker。我需要获取所选日期的值???

例如:

 dateDisplay=(EditText)findViewById(R.id.date);

正如我们在普通编辑文本中所做的那样:

final EditText Name = (EditText) this.findViewById(R.id.nametext); 
and we can cast the data of it by using `Name.getText().toString()`

所以我们怎样才能将日期选择器的值变为字符串?

2 个答案:

答案 0 :(得分:2)

检查一下:

Android: get DatePickerDialog in a fragment


很容易:

DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

    public void onDateSet(DatePicker view, int year,
            int monthOfYear, int dayOfMonth) {
        mYear = year;
        mMonth = monthOfYear;
        mDay = dayOfMonth;
        updateDisplay();
    }
};

DatePickerDialog d = new DatePickerDialog(getActivity(),
        R.style.MyThemee, mDateSetListener, mYear, mMonth, mDay);
d.show();

UpdateDisplay方法:

private void updateDisplay() {

    GregorianCalendar c = new GregorianCalendar(mYear, mMonth, mDay);
    SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy");

    editDate.setText(sdf.format(c.getTime()));

    sdf = new SimpleDateFormat("yyyy-MM-dd");

    transDateString=sdf.format(c.getTime());
}// updateDisplay

答案 1 :(得分:0)

这就像魅力一样。

 final Calendar cal = Calendar.getInstance();
       pYear = cal.get(Calendar.YEAR);
       pMonth = cal.get(Calendar.MONTH);
       pDay = cal.get(Calendar.DAY_OF_MONTH);
//----------To Open datePicker----------------
private DatePickerDialog.OnDateSetListener pDateSetListener = new DatePickerDialog.OnDateSetListener()
     {
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
            {
                pYear = year;
                pMonth = monthOfYear;
                pDay = dayOfMonth;
                updateDisplay();
            }
     };

//----------To display date in EditText----------------
private void updateDisplay()
     {
           final Calendar cal = Calendar.getInstance();
           currentYear = cal.get(Calendar.YEAR);

           displayBirthdayDate.setText(
                new StringBuilder()
                        // Month is 0 based so add 1
                        .append(pMonth + 1).append("/")
                        .append(pDay).append("/")
                        .append(pYear));
     }