加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 01:27:24 所属栏目:大数据 来源:网络整理
导读:我有一个简单的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(Dat

我有一个简单的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的问题编辑

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读