johngun3 johngun3 - 1 month ago 8
Android Question

Display date only and no time in Android

I am attempting to display a date in android with year, month, and day chosen using a DatePicker. What I'm having trouble with is taking the year, month, and day chosen and displaying them on the screen in the correct format for the locale of the phone without also displaying the time.

The code as it stands now will display the date correctly but it also displays the time.

StringBuilder string = new StringBuilder()
// Month is 0 based so add 1
.append(mYear).append("-")
.append(mMonth + 1).append("-")
.append(mDay);

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

try {
Date date = format.parse(string.toString());
mDateDisplay.setText(date.toLocaleString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


mDateDisplay is a TextView.

I can't figure out how to get rid of the time that is also displayed. I've done a fair amount of searching and reading documentation and I couldn't figure it out. Any help would be appreciated.

Answer
java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getContext());
mDateDisplay.setText(dateFormat.format(date))

This will take into account the users locale settings and only display the date.

Here is the relevant documentation: getDateFormat(Context context)

Comments