How to get datepicker value in date format?

Sibin Francis picture Sibin Francis · Feb 13, 2013 · Viewed 51.2k times · Source

I have a problem with my Datapicker

i use the code for getting date,month & year shown below

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

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

but when i print the date it shows the value 7 not 07 and for month it shows the value 2 not 02

I want these integer data in a date format ie; eg: 02-02-2013, 24-12-2013
Is there any possible way????

Answer

zdesam picture zdesam · Feb 13, 2013

You can format the date like this :

int   day  = datePicker.getDayOfMonth();
int   month= datePicker.getMonth();
int   year = datePicker.getYear();
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String formatedDate = sdf.format(calendar.getTime());

You can parse the String back to Date object by calling

Date date = sdf.parse(formatedDate);