@JsonFormat时间格式化注解

@JsonFormat时间格式化注解

@JsonFormat注解是一个时间格式化注解,比如存储在mysql中的数据是dateTime类型,程序读取出来封装在实体类中的时候,就会变成英文时间格式,而不是yyyy-MM-dd HH:mm:ss格式的时间,因此@JsonFormat注解就可以用来格式化时间。

@JsonFormat注解是jackson包里面的一个注解,在使用的时需引入fasterxml 的jar包,如下所示。

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.2</version>
</dependency>

引入fasterxml 的jar包之后,就可以在实体类属性上面使用@JsonFormat注解,要注意的是,它只会在类似@ResponseBody返回json数据时,才会返回格式化的yyyy-MM-dd HH:mm:ss时间,直接使用System.out.println()输出的话,仍然是类似“Fri Dec 01 21:05:20 CST 2017”这样的时间样式。(将实体序列化成json字符串也可以将时间进行转换)

import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
public class Student {
    private int id;
    private String username;
        
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    private Date createDate;
    
    //getter setter省略。。。
}

当这样@ResponseBody输出json数据的时候,@JsonFormat注解标识的date属性就会自动返回yyyy-MM-dd HH:mm:ss样式的时间,例如。

@PostMapping("/api/getStudent")
@ResponseBody
public Map<String,Object> findStudentById(Long stuId){
    Map<String,Object> resultMap = new HashMap<>();
    Student stu = studentService.findStudentById(stuId);
    resultMap.put("result",stu);
    return resultMap;
}
posted @ 2021-11-16 23:40  黄河大道东  阅读(3912)  评论(0编辑  收藏  举报