Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display date only and no time in Android

Tags:

date

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.

like image 729
johngun3 Avatar asked May 08 '12 16:05

johngun3


2 Answers

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)

like image 135
Lukazoid Avatar answered Nov 01 '22 00:11

Lukazoid


android.text.format.DateFormat df = new android.text.format.DateFormat();
df.format("yyyy-MM-dd", new java.util.Date());

or

android.text.format.DateFormat.format("yyyy-MM-dd", new java.util.Date());

refer this LINK

Updated::

you can also use formatter to get only date as below::

mDateDisplay.setText(String.format("%1$tY %1$tb %1$td", date));
like image 30
Shankar Agarwal Avatar answered Oct 31 '22 23:10

Shankar Agarwal