问题
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 usingDateFormat 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
回答1:
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();
回答2:
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.
回答3:
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 ?
来源:https://stackoverflow.com/questions/18860731/get-localized-short-date-pattern-as-string