Springboot uses the Datetimeformat (pattern = “yyyy MM DD HH: mm: SS”) annotation to automatically convert the string to date type error

1.dto

import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import java.io.Serializable;
import java.util.Date;

/**
 * @author: htdd
 * @date: 2022/1/7 11:15
 */
@Data
public class TestDTO implements Serializable {

    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date createTime;
}

2.controller

@PostMapping("test")
public JsonData test(HttpServletRequest request, @RequestBody TestDTO dto) {
    return JsonData.buildSuccess("success");
}

3. An error is reported after a postman request

Postman request

Background error reporting

Error reporting reason:

The general meaning is that the time format does not meet the requirements. After checking the document, the default conversion format for time is

"yyyy-MM-dd'T'HH:mm:ss.SSSZ"  
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"  
"EEE, dd MMM yyyy HH:mm:ss zzz"  
"yyyy-MM-dd"

Solution:

Unified configuration in configuration file

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

4. Postman requests again and the conversion is successful

Similar Posts: