How to store date value from DatePicker to formatted String value?

During the registration process, I am trying to implement code that stores a date value as a string value in the following format: "dd-mm-yyyy".

So, in the onCreate () method part, I declared the DatePicker variable like this:

DatePicker dob = (DatePicker) findViewById(R.id.dob);

      

And in the onClick () method part, I wrote the code to convert this DatePicker value to a string.

String entered_dob = dob.toString();

      

But later when I opened the database, I found out that this only returns a value which looks silly. How should I implement to get what I wanted?

+3


source to share


2 answers


If you want to store your date as a string (which is not good practice)

DatePicker datePicker ;
SimpleDateFormat dateFormatter ;
Date d ;
String entered_dob ;

datePicker = (DatePicker) findViewById(R.id.dob);

int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth() + 1;
int year = datePicker.getYear()

d = new Date(year, month, day);
dateFormatter = new SimpleDateFormat("MM-dd-yyyy");
entered_dob = dateFormatter.format(d);

      



If you want to get a timestamp, you can do it like this:

Calendar calendar = new GregorianCalendar(year, month, day);
long enterded_dob_ts = calendar.getTimeInMillis();

      

0


source


I would recommend storing the timestamp.

Use Calendar to create this value. This one you can easily keep as long as possible (or a string if you really want it)



Checkout this example

0


source







All Articles