Ojonugwa Jude Ochalifu
Ojonugwa Jude Ochalifu

Reputation: 27237

Converting String to Date object

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

Answers (6)

mavalan
mavalan

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

Mohsin AR
Mohsin AR

Reputation: 3108

click here to see an example by mkyong

Upvotes: 1

Semih Eker
Semih Eker

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

elbuild
elbuild

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

wawek
wawek

Reputation: 1597

this.dateOfBirth = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(dateOfBirthTextField);

Upvotes: 1

gipinani
gipinani

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

Related Questions