【问题标题】:milliseconds since unix epoch as @RequestParameter for joda DateTime自 unix 纪元以来的毫秒数作为 joda DateTime 的 @RequestParameter
【发布时间】:2014-09-02 01:37:16
【问题描述】:

软件栈:Java8、Spring MVC 4.0.5、JodaTime 2.3、Jackson2

我正在实现的 API 要求将所有日期时间表示为自 UNIX 纪元以来的毫秒数。对于json,很简单:

configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);

在 JodaObjectMapper 中。 问题在于@RequestParams。每当将 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 格式。但我想知道最初的问题是否有解决方案,以防万一。

【问题讨论】:

  • 使用@InitBinder 或conversionService

标签: spring-mvc jodatime


【解决方案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>

【讨论】:

    猜你喜欢
    • 2015-03-06
    • 2013-09-11
    • 2019-12-04
    • 1970-01-01
    • 2019-02-24
    • 2021-06-11
    • 2013-08-19
    • 2013-05-02
    • 2013-05-14
    相关资源
    最近更新 更多