将Spring MVC中的默认/全局日期格式设置为ISO 8601

Ben*_*n M 6 spring datetime date spring-mvc jodatime

我有一个简单的Spring控制器:

@RequestMapping(value="", method=RequestMethod.GET)
public void search(MyDTO dto) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

而且MyDTO:

public class MyDTO {
    private DateTime date;
    public DateTime getDate() { return date; }
    public void setDate(DateTime date) { this.date = date; }
}
Run Code Online (Sandbox Code Playgroud)

我实际上可以用我的本地日期格式调用控制器方法:03.10.2013 01:00例如GET http://localhost:8080/test?date=03.10.2013 01:00

但我想要应用程序范围的ISO 8601日期格式,例如: 2007-03-01T13:00:00Z

如果我使用ISO格式,我会收到以下错误:

Failed to convert property value of type 'java.lang.String' to required type
'org.joda.time.DateTime' for property 'date'; nested exception is
org.springframework.core.convert.ConversionFailedException: Failed to convert
from type java.lang.String to type org.joda.time.DateTime for value
'2013-09-25T23:05:18.000+02:00'; nested exception is
java.lang.IllegalArgumentException: Invalid format:
"2013-09-25T23:05:18.000+02:00" is malformed at "13-09-25T23:05:18.000+02:00"
Run Code Online (Sandbox Code Playgroud)

必须有一些方法来改变它java.util.Date以及所有那些Joda日期和时间容器.

我刚刚找到了这个addFormatters(FormatterRegistry registry)方法WebMvcConfigurationSupport,但我真的不知道如何使用它.

Mar*_*eel 0

我让它在乔达时间上工作:

public class WebConfig extends WebMvcConfigurationSupport {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        JodaTimeFormatterRegistrar j = new JodaTimeFormatterRegistrar();
        j.setUseIsoFormat(true);
        j.registerFormatters(registry);
    }       
}
Run Code Online (Sandbox Code Playgroud)

我希望有一种更简单的方法来完成所有可能的日期实现。

最初发布为 OP Benjamin M对问题的编辑