微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

和MyDTO:

public class MyDTO {
    private DateTime date;
    public DateTime getDate() { return date; }
    public void setDate(DateTime date) { this.date = date; }
}

我实际上可以使用我的本地日期格式调用控制器方法: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"

必须有一些方法来改变java.util.Date以及所有那些Joda Date和Time容器.

我刚刚在WebMvcConfigurationSupport中找到了addFormatters(FormatterRegistry注册表)方法,但我真的不知道如何使用它.

最佳答案
我让它适用于Joda Time:

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

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

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

原文地址:https://www.jb51.cc/spring/432106.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐