Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date from EditText

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?

like image 997
Adam N Avatar asked Jul 16 '13 10:07

Adam N


2 Answers

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
like image 164
Ken Wolf Avatar answered Oct 25 '22 11:10

Ken Wolf


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);
like image 45
Semyon Danilov Avatar answered Oct 25 '22 09:10

Semyon Danilov