我正在使用 Joda Time并且需要以用户首选格式 ( note that before Android M, the format could be changed ) 显示日期。
Joda DateTime 可以使用 DateTimeFormatter 格式化,它是从具有所需日期格式的字符串创建的:
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 采用用户首选的格式?
最佳答案
DateFormat 是一个抽象类,因此没有对格式模式的访问方法(因为每个具体实现将处理自己的模式)。 但是,android.text.format.DateFormat.getDateFormat() 返回的实际上是一个提供模式的SimpleDateFormat。因此你可以这样做:
SimpleDateFormat format=(SimpleDateFormat)DateFormat.getDateFormat(context.getApplicationContext());
String pattern=format.toPattern();
或
String pattern=format.toLocalizedPattern();
这暂时有效,但请注意,这不是 100% 的 future 证明,因为 getDateFormat() 返回的实际类将来可能会发生变化。
关于java - 使用首选 DateFormat 格式化 JodaTime DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39300420/