Android DatePicker:如何在EditText中设置DatePicker的值,格式为dd-mm-yyyy

时间:2014-03-25 06:17:42

标签: android android-datepicker

EditText设置DatePicker中的值时,如何设置为25-03-2014而不是25-3-2014。

它显示25-3-2014,缺少' 0'每月之前(mm)。

感谢。

4 个答案:

答案 0 :(得分:1)

YourEditText = (EditText) findViewById(R.id.your_edittext);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String date = sdf.format(new Date(System.currentTimeMillis()));
    if (date.contains("/")) {
        date = date.replace("/", "-");
    }
YourEditText.setText(date);

在xml:

中的YourEditText上添加Click事件

android:onClick="onTime"

代码段:

请从Activity

延长FragmentActivity
public void onTime(View v) {
    DialogFragment newFragment = new FromDatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "From Date");
}


    class FromDatePickerFragment extends DialogFragment implements
        OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int yr = c.get(Calendar.YEAR);
        int mnth = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        // Create a new instance of TimePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, yr, mnth, day); 
    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        // TODO Auto-generated method stub
        String date;
        monthOfYear++;
        if (dayOfMonth < 10) {
            date = "0" + dayOfMonth + "-";
        } else {
            date = dayOfMonth + "-";
        }
        if (monthOfYear < 10) {
            date += "0" + monthOfYear + "-";
        } else {
            date += monthOfYear + "-";
        }

        date += year;
        YourEditText.setText(date);
    }
}

答案 1 :(得分:0)

您可以使用SimpleDateFormat作为&#34; dd / MM / yyyy&#34;。

查看文档。

http://developer.android.com/reference/java/text/SimpleDateFormat.html

答案 2 :(得分:0)

使用下面给出的代码可以解决你的问题...

 DatePicker dp = (DatePicker)dialog.findViewById(R.id.datePicker1);
     dp.getDayOfMonth();
     dp.getMonth();
     dp.getYear();    
     if(dp.getMonth()+1<10)
         editText.setText(dp.getDayOfMonth()+"-"+"0"+(dp.getMonth() + 1 )+"-"+dp.getYear());
     if(dp.getDayOfMonth()<10)
         editText.setText("0"+dp.getDayOfMonth()+"-"+(dp.getMonth() + 1 )+"-"+dp.getYear() );
     if(dp.getMonth()+1<10 && dp.getDayOfMonth()<10)
         editText.setText("0"+dp.getDayOfMonth()+"-"+"0"+(dp.getMonth() + 1 )+"-"+dp.getYear() );
     if(dp.getMonth()+1>9 && dp.getDayOfMonth()>9)
         editText.setText( dp.getDayOfMonth()+"-"+(dp.getMonth() + 1 )+"-"+dp.getYear());

 dialog.dismiss();

答案 3 :(得分:0)

简单地说就是这样,

final String DATE_FORMAT = "dd-MM-yyyy";
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);