Set default/global date format in Spring MVC to ISO 8601

爷,独闯天下 提交于 2019-12-06 01:49:31

问题


I have a simple Spring Controller:

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

And MyDTO:

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

I actually can call the controller method with my local date format: 03.10.2013 01:00, e.g. GET http://localhost:8080/test?date=03.10.2013 01:00

But I want application wide ISO 8601 date format, e.g.: 2007-03-01T13:00:00Z

If I use ISO format I get the following error:

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"

There must be some way to change it for java.util.Date and also all those Joda Date and Time containers.

I just found the addFormatters(FormatterRegistry registry) method within WebMvcConfigurationSupport, but I don't really know how to use it.


回答1:


I got it working for Joda Time:

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

I hope there's an easier way to get this done for ALL possible Date implementations.

Originally posted as an edit to the question by the OP, Benjamin M



来源:https://stackoverflow.com/questions/19148649/set-default-global-date-format-in-spring-mvc-to-iso-8601

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!