Reputation: 27237
Am trying to store a date object in Android.I want to get the date as a String from EditText
and then "convert" or should i say store it as a Date
object.This is what i have done.
I have a TextField
`EditText dateOfBirthTextField = (EditText) findViewById(R.id.DoBTextField);`
and then a String
`String dateOfBirth = dateOfBirthTextField.getText().toString();`
Now i have a Student
class that has a dateOfBirth
field of type Date
and a method
`setDateOfBirth(Date dob){
this.dateOfBirth=dob;
}
How do i set the value of dateOfBirth
with what ever is entered into dateOfBirthTextField
?
Upvotes: 0
Views: 114
Reputation: 21
I'm assuming you meant to declare a string dateOfBirthString
and a date dateOfBirth
.
You just convert the string to a date with a SimpleDateFormat
.
It should be something like this:
EditText dateOfBirthTextField = (EditText) findViewById(R.id.DoBTextField);
String dateOfBirthString = dateOfBirthTextField.getText().toString();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); //you have to enter the format of your string, here "dd/MM/yyyy" = "day/month/year"
Date dateOfBirth = sdt.parse(dateOfBirthString);
setDateOfBirth(dateOfBirth);
Upvotes: 1
Reputation: 2409
You can do sthg like that;
String str = "26/08/1994";
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse(str);
please notice the capital M.
Upvotes: 1
Reputation: 4899
String dateOfBirth = dateOfBirthTextField.getText().toString();
SimpleDateFormat s=new SimpleDateFormat("MM/dd/yyyy"); // use your pattern here
Date d = s.parse(dateOfBirth);
Upvotes: 1
Reputation: 1597
this.dateOfBirth = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(dateOfBirthTextField);
Upvotes: 1
Reputation: 14398
Date date = new SimpleDateFormat("yyyy/MM/dd").parse (yourStringDate);
then call
setDateOfBirth(date);
You can provide your custom format to constructor.
Take a look at SimpleDateFormat javadoc: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Upvotes: 3