SpringBoot请求日期参数异常(Failed-to-convert-value-of-type-'java-lang-String'-

问题

Failed to convert value of type ‘java.lang.String’ to required type ‘java.util.Date’; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value ‘2020-12-12 12:12’; nested exception is java.lang.IllegalArgumentException

分析

SpringMvc没有设置日期转换配置,直接把当成String类型强转Date类型!

解决方案

第一种方法:

@DateTimeFormat 日期参数格式化注解

  @RequestMapping(value = "test")
    @ResponseBody
    public Map<String,Object> test(@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date date, @NumberFormat(pattern = "#,###.##")Double number){
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("data",date);
        resultMap.put("number",number);
        return resultMap;
    }

第二种方法:

application.yml设置日期参数格式化配置:

spring:
  mvc:
    date-format: yyyy-MM-dd HH:mm:ss

返回格式化日期

第一种方法:

在实体类中Date属性上标记:@JsonFormat
pattern:是你需要转换的时间日期的格式
timezone:是时间设置为东八区,避免时间在转换中有误差

@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd")
private Date updateDate;

第二种方法:

spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8

@NumberFormat 注解 支持数字类型参数格式化格式

image.png

个人微信公众,经常更新一些实用的干货:
image.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值