有哪些好方法可以为不同的本地化自定义日期/时间显示格式



>每当我想将日期/时间格式打印为人类可读的形式时,IDE 都会建议我使用以下方式之一

getDateInstance()
getDateTimeInstance()
getTimeInstance()

但是,大多数时候,应用不同的int style不符合我的要求。最后,我需要定义我自己的。

private static final ThreadLocal<SimpleDateFormat> dateFormatThreadLocal = new ThreadLocal <SimpleDateFormat>() {
@Override protected SimpleDateFormat initialValue() {
// January 2
return new SimpleDateFormat("MMMM d");
}
};

这给我带来了麻烦,如果我也想支持非英语。例如,对于中国市场,我需要使用单独的格式。

private static final ThreadLocal<SimpleDateFormat> dateFormatForChineseThreadLocal = new ThreadLocal <SimpleDateFormat>() {
@Override protected SimpleDateFormat initialValue() {
// 1月2日
return new SimpleDateFormat("MMMMd日");
}
};

我的代码将以以下内容结束

public String dateString() {
if (chinese user) {
return dateFormatForChineseThreadLocal.get().format(calendar.getTime());
}
return dateFormatThreadLocal.get().format(calendar.getTime());
}

这使得维护工作变得困难。我想知道,有没有更好的方法来为不同的本地化自定义日期/时间显示格式?

当您本地化您的应用程序时,您通常会为您的应用程序/src/main/res/应支持的每种语言创建strings.xml文件,其中values/主要包含英语文件以及values-devalues-cn德语或中文,例如。当您在此处使用格式定义字符串资源时,只需将其读出并将该格式传递给日期格式化程序即可。

有了这个,您可以简单地添加新语言,而无需更改代码中的任何行。

最新更新