1. 程式人生 > 其它 >Failed to convert property value of type ‘java.lang.String‘ to required type ‘java.util.Date‘

Failed to convert property value of type ‘java.lang.String‘ to required type ‘java.util.Date‘

技術標籤:springbootjavaspring boot日期格式化

spring boot的日期轉換問題

前言

小編的springboot專案已經配置了全域性的日期轉換,並且在專案中日期自動上添加了 @JsonFormat(pattern = “yyyy-MM-dd HH-mm-ss”) 的日期轉換註解,但是今天遇到一個奇怪的問題,部分日期的轉換還是報錯了。

解決方法

在日期的註解上在新增一個日期裝的註解。DateTimeFormat

    @JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @ApiModelProperty(value = "活動開結束時間")
    private Date activityTimeEnd;

原因

@DatetimeFormat是將String轉換成Date,一般前臺給後臺傳值時用

  /**
     * 前臺傳後臺時, 字串自動封裝成日期
     */
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date birth;

@JsonFormat(pattern=”yyyy-MM-dd”) 將Date轉換成String 一般後臺傳值給前臺

/**
     * 後臺返給前臺時, 日期自動格式化
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date birth;