@DateTimeFormat无效

一般都是使用@DateTimeFormat把传给后台的时间字符串转成Date,使用@JsonFormat把后台传出的Date转成时间字符串,但是@DateTimeFormat只会在类似@RequestParam的请求参数(url拼接的参数才生效,如果是放到RequestBody中的form-data也是无效的)上生效,如果@DateTimeFormat放到@RequestBody下是无效的。

  在@RequestBody中则可以使用@JsonFormat把传给后台的时间字符串转成Date,也就是说@JsonFormat其实既可以把传给后台的时间字符串转成Date也可以把后台传出的Date转成时间字符串

 

/**
 * Controller
 **/
@SpringBootApplication
@RestController
public class Application {

    @RequestMapping("/server")
    public Result home(@RequestBody Param param, HttpServletRequest request) {
        return new Result().setRtime(param.getTime());
    }

    @RequestMapping("/server1")
    public Result home1(Param1 param, HttpServletRequest request) {
        return new Result().setRtime(param.getTime());
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}

 

 

/**
 * 在@RequestBody中使用@JsonFormat将入参时间字符串转Date
 **/
public class Param {

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date time;

    public Date getTime() {
        return time;
    }

    public void setTime(Date time) {
        this.time = time;
    }
}

 

 

/**
 * 在类似@RequestParam中将入参时间字符串转Date
 **/
public class Param1 {

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

    public Date getTime() {
        return time;
    }

    public void setTime(Date time) {
        this.time = time;
    }
}

 

 

/**
 * 使用@JsonFormat将Date转成时间字符串传给前端
 **/
public class Result {

    @JsonFormat(pattern = "yyyy/MM/dd HH:mm:ss", timezone = "GMT+8")
    private Date rtime;

    public Date getRtime() {
        return rtime;
    }

    public Result setRtime(Date time) {
        this.rtime = time;
        return this;
    }
}

 

你可能感兴趣的:(@DateTimeFormat无效)