自unix epoch以来的毫秒为joda DateTime的@RequestParameter

时间:2014-07-11 12:18:03

标签: spring-mvc jodatime

软件堆栈:Java8,Spring MVC 4.0.5,JodaTime 2.3,Jackson2

API我实现请求所有日期时间表示为自UNIX纪元以来的毫秒数。对于json来说,这很容易:

configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
在JodaObjectMapper中

。 问题出在@RequestParam上。每当Unix时间戳传递给控制器​​时 @RequestParam DateTime date我得到一个例外:

Failed to convert value of type 'java.lang.String' to required type 'org.joda.time.DateTime';
  nested exception is org.springframework.core.convert.ConversionFailedException:
    Failed to convert from type java.lang.String to type @org.springframework.web.bind.annotation.RequestParam org.joda.time.DateTime for value '1404820782110';
      nested exception is java.lang.IllegalArgumentException:
        Invalid format: "1404820782110" is malformed at "04820782110"

目前,我将DateTime更改为Long并执行new DateTime(date)以获取日期时间对象。我也正在考虑从纪元时间戳转移到支持得很好的ISO格式。但我想知道是否有最初问题的解决方案,以防万一。

1 个答案:

答案 0 :(得分:1)

创建自定义转换器:

public class StringToJodaDateTimeConverter implements Converter<String, DateTime> {

    @Override
    public DateTime convert(String source) {
        return new DateTime(Long.parseLong(source));
    }

}

并按照以下方式注册:

<mvc:annotation-driven conversion-service="conversionService" />
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="StringToJodaDateTimeConverter"/>
        </set>
    </property>
</bean>