接收前端时间类型(Date)的参数问题

定义DTO

    @ApiModelProperty("起始时间")
    private Date beginDate;

    @ApiModelProperty("结束时间")
    private Date endDate;

从前端传来的参数

这样接收的时候会报错:

{
    "status": 200,
    "rst": 0,
    "timestamp": "2019-12-03 14:19:10",
    "error": null,
    "exception": "org.springframework.validation.BindException",
    "msg": "Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'beginDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@io.swagger.annotations.ApiModelProperty java.util.Date] for value '2019-12-03 14:17:26'; nested exception is java.lang.IllegalArgumentException\n",
    "path": null,
    "data": null,
    "total": null
}

解决方法

    @ApiModelProperty("起始时间")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date beginDate;

    @ApiModelProperty("结束时间")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date endDate;

使用@DateTimeFormat去做转换就可以了

# 随记 
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×