如何从EditText输入日期(不是自动的,而是手动的)

时间:2015-11-26 06:57:54

标签: android date input android-edittext

这是我的代码

EditText txtdate;

这是我的XML

<EditText
        android:id="@+id/txtdate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="date" />

这是我的班级

txtdate = (EditText)findViewById(R.id.txtdate);

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

我该怎么做?

1 个答案:

答案 0 :(得分:0)

txtdate =(EditText)findViewById(R.id.txtdate);

SimpleDateFormat df = new SimpleDateFormat(&#34; dd-MM-yyyy&#34;);

您可以尝试从EditText接收String并将其转换为日期。但我不建议:用户可以输入任何内容,您赢得的内容无法解析为有效日期。但无论如何,这是代码。

String string = txtdate.getText().toString();
Date date = Date.parse(string);
String prettyDate = df.format(date);

注意,不推荐使用Date.parse()。我改用JodaTime库。这很简单。现在给认真的员工。 如果要从用户获取正确的日期,请使用DatePicker。这是Android中的标准,它将返回您的有效日期。