[英]How to change default date formats in Struts2?
I am developing a multilingual Struts2 application, and I have quite a few actions which are dealing with Calendar
properties. 我正在开发一个多语言Struts2应用程序,我有很多处理
Calendar
属性的操作。 The default type conversion works most of the time, however in some locales I would like to change the default format used. 默认类型转换大部分时间都有效,但在某些语言环境中我想更改使用的默认格式。
Specifically I would like to have the dates in English locale to follow the yyyy-MM-dd
format. 具体来说,我希望英语语言环境中的日期遵循
yyyy-MM-dd
格式。 However, this does not work (strangely yyyy-MM-dd HH:mm
works fine, but in this case I do not want to have a time part), as Struts2 expect dates in English locale to look different. 但是,这不起作用(奇怪的是
yyyy-MM-dd HH:mm
工作正常,但在这种情况下我不想有时间部分),因为Struts2期望英语语言环境中的日期看起来不同。
So, I would like to change the expected format of the conversion. 所以,我想改变转换的预期格式。 I am looking for a sane solution for this.
我正在寻找一个理智的解决方案。 The options I have already tried:
我已经尝试过的选项:
StrutsTypeConverter
. StrutsTypeConverter
。 This should work, but I could not inject the format specified in the package.properties
file into it. package.properties
文件中指定的格式注入其中。 String
instead - works, but this is not a sane solution . String
- 有效,但这不是一个理智的解决方案 。 How to fix the solution A ? 如何解决方案A ? Or is there an alternative approach?
或者有替代方法吗? Of course, if this can be done entirely in configuration, that would be the best.
当然,如果这可以完全在配置中完成,那将是最好的。
Okay, I found a solution for my problem at hand, still, I think this could done in a saner way. 好的,我找到了解决我手头问题的方法,我认为这可以用更好的方式完成。 Anyway, I am posting my own type converter:
无论如何,我发布了自己的类型转换器:
public class DateConverter extends StrutsTypeConverter {
private DateFormat dateFormat;
{
ActionContext ctx = ActionContext.getContext();
ActionSupport action = (ActionSupport) ctx.getActionInvocation().getAction();
String formatString = action.getText("dateformat.ui");
dateFormat = new SimpleDateFormat(formatString);
}
public Object convertFromString(Map context, String[] values, Class toClass) {
String input = values[0];
try {
Date date = dateFormat.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
} catch (ParseException e) {
return null;
}
}
public String convertToString(Map context, Object object) {
Calendar cal = (Calendar) object;
return dateFormat.format(cal.getTime());
}
}
I removed the non-essential parts of the code, but this is a working solution. 我删除了代码的非必要部分,但这是一个有效的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.