I try to get date from edittext in Android, but code return wrong text.
Java code:
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 code:
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="date">
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()
returns the day of week, so this is wrong. Use getDate()
.
getMonth()
starts at zero so you need to add 1 to it.
getYear()
returns a value that is the result of subtracting 1900 from the year so you need to add 1900 to it.
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();
}
All of these are deprecated though and you should really use a Calendar
instead.
Edit: quick example of Calendar
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
cal.get(Calendar.DAY_OF_MONTH); // and so on
Please, don`t be afraid to look at Java Documentation. These methods are deprecated. (And btw you are using wrong methods for getting values) Use Calendar:
Calendar c = Calendar.getInstance();
c.setTime(myDate)
String dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
String month = c.get(Calendar.MONTH);
String year = c.get(Calendar.YEAR);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With