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.
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)
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With