Get Localized Short Date Pattern As String?
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
Solution 1:
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.
Solution 2:
remember DateFormat
is the base class for SimpleDateFormat
so you can always cast it and grab the pattern.
finalDateFormatshortDateFormat= android.text.format.DateFormat.getDateFormat(context.getApplicationContext());
// getDateFormat() returns a SimpleDateFormat from which we can extract the patternif (shortDateFormat instanceof SimpleDateFormat) {
finalStringpattern= ((SimpleDateFormat) shortDateFormat).toPattern();
Solution 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 ?
Post a Comment for "Get Localized Short Date Pattern As String?"