@DateTimeFormat 和 @JsonFormat 都是用来指定日期时间格式的注解。

@DateTimeFormat 是 Spring 框架提供的注解,用于指定 Java 对象中日期时间类型属性的格式化方式,可以将日期时间字符串转换为 Java 对象中对应的日期时间类型。例如:

public class User {
    private String name;
    
    @DateTimeFormat(pattern = 'yyyy-MM-dd HH:mm:ss')
    private Date birthday;
    
    // getter and setter
}

@JsonFormat 是 Jackson 库提供的注解,用于指定 JSON 字符串中日期时间类型属性的格式化方式,可以将 JSON 字符串转换为 Java 对象中对应的日期时间类型。例如:

public class User {
    private String name;
    
    @JsonFormat(pattern = 'yyyy-MM-dd HH:mm:ss', timezone = 'GMT+8')
    private Date birthday;
    
    // getter and setter
}

需要注意的是,@DateTimeFormat 和 @JsonFormat 都可以指定日期时间格式,但它们的作用范围不同。@DateTimeFormat 只适用于 Java 对象中日期时间类型属性的格式化,而 @JsonFormat 只适用于 JSON 字符串中日期时间类型属性的格式化。因此,如果要同时对 Java 对象和 JSON 字符串中的日期时间类型属性进行格式化,需要同时使用这两个注解。

@DateTimeFormat 和 @JsonFormat 注解:日期时间格式化指南

原文地址: https://www.cveoy.top/t/topic/ngBX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录