【问题标题】:Convert Unix timestamp to Java Date, Spring RequestParam将 Unix 时间戳转换为 Java 日期,Spring RequestParam
【发布时间】:2015-05-25 15:06:24
【问题描述】:

下面是一个请求fullcalendar js发送到服务器。

http://localhost:8080/NVB/rest/calendar/events?start=1425168000&end=1428796800 400

如何在 Spring 请求参数中指定日期模式 (@DateTimeFormat) 以将此时间转换为日期对象。我尝试了不同的模式,但收到 405 Bad Request。

@RequestMapping(value = "/events", method = RequestMethod.GET)
public @ResponseBody List<EventDto> addOrder(@RequestParam(value = "start") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date start,
                                             @RequestParam(value = "end") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)   Date end) {
    LOGGER.info("Requesting event from [{}] to [{}]", start, end);
    return new LinkedList<EventDto>();
}

【问题讨论】:

标签: spring-mvc datetime unix-timestamp


【解决方案1】:

由于时间戳不是格式化的日期(通过 Java 的 SimpleDateFormat 选项),而是更多的数值:如果你这样做的频率比这个单一的多,我建议为 Date 对象制作一个自定义数据绑定器实例。见http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#portlet-ann-webdatabinder

作为一次性解决方案,您可以将它们绑定到 Long 参数并使用 new Date(start) 创建您自己的 Date 对象。

【讨论】:

    【解决方案2】:

    使用@InitBinderWebDataBinder

    @RestController
    public class SimpleController {
    
        //... your handlers here...
    
        @InitBinder
        public void initBinder(final WebDataBinder webdataBinder) {
            webdataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
                @Override
                public void setAsText(String text) throws IllegalArgumentException {
                    setValue(new Date(Long.valueOf(text)));
                }
            });
        }
    }
    

    【讨论】:

    • 花了我几个小时才找到这个答案,谢谢!我怀疑杰克逊是问题所在,而在毫无意义的配置尝试之后毫无意义的挫败感真的让我感到不安。似乎杰克逊根本不处理请求参数,有谁知道原因,为什么请求参数的处理方式与 json 类型不同?
    猜你喜欢
    • 2020-10-19
    • 2020-12-23
    • 2016-04-24
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    相关资源
    最近更新 更多