好吧,我终于得到了这个“东西”的工作。该解决方案可能对其他人有用。我仍然不是100%确定我没有滥用框架...我写我自己的DateFormatter,它使用地图Locale/SimpleDateFormat而不是独特的模式(如基础框架类),我写了我自己的DateFormatter。
由于在Play Java中似乎是(多一个)bug,我的覆盖解析(String date,Locale locale)忽略了locale参数,并使用请求获取首选语言。
下面是完整的代码:
public class DateFormatter extends Formatters.SimpleFormatter<Date> {
private Map<Locale, SimpleDateFormat> formats;
private SimpleDateFormat defaultFormat;
public DateFormatter(String defaultPattern) {
formats = new HashMap<Locale, SimpleDateFormat>();
defaultFormat = new SimpleDateFormat(defaultPattern);
}
@Override
public Date parse(String date, Locale locale) throws ParseException {
Logger.debug("Parsing date " + date + " for locale " + locale);
Context ctx = Context.current();
if (ctx != null) {
Lang preferred = Lang.preferred(ctx.request().acceptLanguages());
Locale loc = preferred.toLocale();
return getFormat(loc).parse(date);
} else {
return getFormat(locale).parse(date);
}
}
@Override
public String print(Date date, Locale locale) {
return getFormat(locale).format(date);
}
public void addPattern(Locale locale, String pattern) {
formats.put(locale, new SimpleDateFormat(pattern, locale));
}
private SimpleDateFormat getFormat(Locale locale) {
SimpleDateFormat format = formats.get(locale);
if (format == null)
return defaultFormat;
else
return format;
}
}
(2)本DateFormatter被构造并通过在应用程序加载应用程序全局对象注册。
@Override
public void onStart(Application app) {
registerDateFormatter(app);
}
/**
* Registers a custom date formatter using configured
* available languages and custom date formats.
*
* Browses the locales defined in langs parameter and
* for each one loads the date format defined in the
* parameters custom.date.format.xx
*
* Gets also the default (fallback) format defined in
* date.format. If no one is defined uses an hard-coded
* format yyyy-MM-dd
*/
private void registerDateFormatter(Application app) {
Configuration config = app.configuration();
// Get default format
String defaultPattern = config.getString("date.format");
if (defaultPattern == null)
defaultPattern = "yyyy-MM-dd";
DateFormatter formatter = new DateFormatter(defaultPattern);
// Get date format from configuration
for (Lang lang: Lang.availables()) {
Locale locale = lang.toLocale();
String pattern = app.configuration().getString("custom.date.format." + lang.code());
if (pattern != null)
formatter.addPattern(locale, pattern);
}
// Register the formatter for java.util.Date
Formatters.register(Date.class, formatter);
}
(在application.conf)的配置是:
# The application languages
# ~~~~~
application.langs="pt-br, en"
#
date.format="MM/dd/yyyy"
custom.date.format.en = "MM/dd/yyyy"
custom.date.format.pt-br = "dd/MM/yyyy"
(需要在参数名自定义,使用直接date.format.xx引发错误)