Date from EditText

53,293

Solution 1

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

Solution 2

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);
Share:
53,293
Adam N
Author by

Adam N

Updated on July 30, 2022

Comments

  • Adam N
    Adam N almost 2 years

    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?

  • Adam N
    Adam N almost 11 years
    Thank you :) How can I use Calenda to do it? I was trying to get date from Calendar instance, but resualts was wrong.
  • Ken Wolf
    Ken Wolf almost 11 years
    Well, I'm not really sure what you're trying to do since in your example you seem to be converting to date only to convert back exactly to the same string. Use a calendar for calculations involving dates. Anyway, hope that helps.
  • Rohit Gupta
    Rohit Gupta almost 9 years
    Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
  • John Lindal
    John Lindal almost 8 years
    You cannot construct a Calendar directly. Use Calendar.getInstance() instead.