Rom*_*naV 6 java datetime android jodatime date-formatting
我正在使用Joda Time并且需要以用户首选格式显示日期(请注意,在Android M之前,可以更改格式).
可以使用DateTimeFormatter格式化Joda DateTime,该DateTimeFormatter是从具有所需日期格式的String创建的:
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 "";
}
Run Code Online (Sandbox Code Playgroud)
但要获得用户的首选格式,您必须使用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;
}
Run Code Online (Sandbox Code Playgroud)
Java DateFormat没有一个方法可以给我一个带有日期格式的String.
那么有没有办法用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();
Run Code Online (Sandbox Code Playgroud)
或者
String pattern=format.toLocalizedPattern();
Run Code Online (Sandbox Code Playgroud)
这暂时有效,但请注意,它不是 100% 的未来证明,因为 getDateFormat() 返回的实际类将来可能会发生变化。
| 归档时间: |
|
| 查看次数: |
528 次 |
| 最近记录: |