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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM