来自 EditText 的日期 [英] Date from EditText

查看:38
本文介绍了来自 EditText 的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从 Android 中的 edittext 获取日期,但代码返回错误的文本.

I try to get date from edittext in Android, but code return wrong text.

Java 代码:

SimpleDateFormat df = new SimpleDateFormat("dd-MM-YYYY"); 
java.util.Date myDate;
myDate = df.parse(editText1.getText().toString());
String myText = myDate.getDay() + "-" + myDate.getMonth() + "-" + myDate.getYear() + "abcd";

XML 代码:

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

当我在 EditText 中写入文本23-08-2013"​​时,代码返回5-7-113-abcd".怎么了?如何从 EditText 获取正确的日期?

When I write text "23-08-2013" in EditText, code return "5-7-113-abcd". What is wrong? How can I get correct date from EditText?

推荐答案

getDay() 返回星期几,所以这是错误的.使用 getDate().

getDay() returns the day of week, so this is wrong. Use getDate().

getMonth() 从零开始,所以你需要给它加 1.

getMonth() starts at zero so you need to add 1 to it.

getYear() 返回一个值,该值是从年份中减去 1900 的结果,因此您需要将 1900 添加到它.

getYear() returns a value that is the result of subtracting 1900 from the year so you need to add 1900 to it.

abcd - 好吧,您明确地将其添加到字符串的末尾,因此没有任何意外:)

abcd - well, you are explicitly adding that to the end of the string so no surprises there :)

SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); 
Date myDate;
try {
    myDate = df.parse(date);
    String myText = myDate.getDate() + "-" + (myDate.getMonth() + 1) + "-" + (1900 + myDate.getYear());
    Log.i(TAG, myText);
} catch (ParseException e) {
    e.printStackTrace();
}

虽然所有这些都已弃用,但您确实应该改用 Calendar.

All of these are deprecated though and you should really use a Calendar instead.

Calendar

Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
cal.get(Calendar.DAY_OF_MONTH); // and so on

这篇关于来自 EditText 的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆