Date from EditText

I am trying to get the date from edittext in Android, but the code returns the 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 the text "23-08-2013" in EditText, return the code "5-7-113-abcd". What's wrong? How can I get the correct date from EditText?

+6
source share
3 answers

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

getMonth() starts from scratch, 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 explicitly add this to the end of the line so that there are no surprises :)

 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(); } 

They are all out of date, although you really should use Calendar .

Edit: Calendar quick example

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

Please do not be afraid to look at the Java documentation. These methods are outdated. (And by the way, you are using the wrong methods to get the 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); 
+2
source

An Android document is always the best link. here is a link to the calendar document page:

http://developer.android.com/reference/java/util/Calendar.html

0
source

Source: https://habr.com/ru/post/949553/


All Articles