3

I'd like to get the pattern of a "short date" as a String that is customized to the user's locale (e.g. "E dd MMM"). I can easily get a localized DateFormat-object using
DateFormat mDateFormat = android.text.format.DateFormat.getDateFormat(mContext);
but DateFormat doesn't have a .toPattern()-method.

If I use

SimpleDateFormat sdf = new SimpleDateFormat();
String mDateFormatString = sdf.toPattern();

I don't know how to only get the short date pattern String instead of the full M/d/yy h:mm a

Nick
  • 3,504
  • 2
  • 39
  • 78

3 Answers3

3

I ended up using

String deviceDateFormat = DateFormat.getBestDateTimePattern(Locale.getDefault(), "E dd MMM");

will will give me the "best regional representation" of the supplied input-format, in this case the weekday, day, and month.

Nick
  • 3,504
  • 2
  • 39
  • 78
2

remember DateFormat is the base class for SimpleDateFormat so you can always cast it and grab the pattern.

final DateFormat shortDateFormat = android.text.format.DateFormat.getDateFormat(context.getApplicationContext());

// getDateFormat() returns a SimpleDateFormat from which we can extract the pattern
if (shortDateFormat instanceof SimpleDateFormat) {
    final String pattern = ((SimpleDateFormat) shortDateFormat).toPattern();
earthling
  • 5,084
  • 9
  • 46
  • 90
0

You could try with something like this :

public String toLocalHourOrShortDate(String dateString, Context context) {
    java.text.DateFormat dateFormat = DateFormat.getDateFormat(context);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    Date date = null;
    try {
        date = sdf.parse(dateString);
        Calendar thisMoment = Calendar.getInstance();
        Calendar eventTime = new GregorianCalendar(Locale.getDefault());
        eventTime.setTime(date);
        if (thisMoment.get(Calendar.YEAR) == eventTime.get(Calendar.YEAR) &&
                thisMoment.get(Calendar.MONTH) == eventTime.get(Calendar.MONTH) &&
                thisMoment.get(Calendar.DAY_OF_MONTH) == eventTime.get(Calendar.DAY_OF_MONTH)) {
            SimpleDateFormat hourDateFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
            return hourDateFormat.format(eventTime.getTime());
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return dateFormat.format(date);
}

Does that work for you ?

2Dee
  • 8,609
  • 7
  • 42
  • 53
  • 1
    Thanks, Toodee! I unfortunately need an actual pattern as a string, I can't use the `.format(Date)` method. Please see my answer below if you'd like to know how I ended up doing this! – Nick Sep 19 '13 at 12:09