shailbenq shailbenq - 1 year ago 115
Android Question

Date formatting based on user locale on android

I want to display date of birth based on the user locale. In my application one of my field is date of birth which is currently in the format dd/mm/yyyy. So if the user changes his locale the date format should also change accordingly. Any pointers or code samples would really help me to overcome the problem.

Answer Source

You can use the DateFormat class that formats a date according to the user locale.


String dateOfBirth = "26/02/1974";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = null;
try {
    date = sdf.parse(dateOfBirth);
} catch (ParseException e) {
    // handle exception here !
java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context);
String s = dateFormat.format(date);

You can use the different methods getLongDateFormat, getMediumDateFormat depending on the level of verbosity you would like to have.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download