【发布时间】:2017-01-11 01:02:30
【问题描述】:
我正在使用Joda Time,需要以用户的首选格式 (note that before Android M, the format could be changed) 显示日期。
可以使用 DateTimeFormatter 格式化 Joda DateTime,它是从具有所需日期格式的字符串创建的:
public String getFormattedDate(String datePattern) {
if (mDate != null) {
// get your local timezone
DateTimeZone localTZ = DateTimeZone.getDefault();
DateTime dt = mDate.toDateTime(localTZ);
DateTimeFormatter fmt = DateTimeFormat.forPattern(datePattern);
String formattedDate = dt.toString(fmt);
return formattedDate;
}
return "";
}
但要获得用户的首选格式,您必须使用 Java DateFormat:
public static DateFormat getPreferredDateFormat(Context context) {
final String format = Settings.System.getString(context.getContentResolver(), Settings.System.DATE_FORMAT);
DateFormat dateFormat;
if (android.text.TextUtils.isEmpty(format)) {
dateFormat = android.text.format.DateFormat.getMediumDateFormat(context.getApplicationContext());
} else {
dateFormat = android.text.format.DateFormat.getDateFormat(context.getApplicationContext()); // Gets system date format
}
if (dateFormat == null)
dateFormat = new SimpleDateFormat(format);
return dateFormat;
}
Java DateFormat 没有一种方法可以给我一个带有日期格式的字符串。
那么有没有办法用 Java DateFormat 格式化 Joda DateTime?也许还指定我只想显示日期和月份(将是 dd/MM 或 MM/dd)?还是让 DateTimeFormatter 采用用户喜欢的格式?
【问题讨论】:
标签: java android datetime jodatime date-formatting