@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;
}