karthi karthi - 3 months ago 11
Java Question

Change the Date Format before setText of TextView

I using DatePicker for to choose the date.Everything going good. But the problem is to Format the date.

// display current date
public void setCurrentDateOnView() {

tvDisplayDate = (TextView) findViewById(R.id.tvDate);

final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);

// set current date into textview
tvDisplayDate.setText(new StringBuilder().append(year).append("-").append(month + 1).append("-").append(day).append(" "));
// Month is 0 based, just add 1

}


As per Code i am getting the OUTPUT: 2016-8-22
but
My expected output is 2016-08-22(I want month like this 08)

Thank you,
regards,
Karthi.

Answer

Use SimpleDateFormat:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
tvDisplayDate.setText(sdf.format(c.getTime()));

For more Information about SimpleDateFormat see the official documentation

Comments