@JsonFormat与@DateTimeFormat的区别

@JsonFormat用于后端传给前端的时间格式转换,@DateTimeFormat用于前端传给后端的时间格式转换

1、@JsonFormat

1、使用maven引入@JsonFormat所需要的jar包

 1         <dependency>
 2             <groupId>com.fasterxml.jackson.core</groupId>
 3             <artifactId>jackson-annotations</artifactId>
 4             <version>2.8.8</version>
 5         </dependency>
 6   
 7         <dependency>
 8             <groupId>com.fasterxml.jackson.core</groupId>
 9             <artifactId>jackson-databind</artifactId>
10             <version>2.8.8</version>
11         </dependency>
12   
13         <dependency>
14             <groupId>org.codehaus.jackson</groupId>
15             <artifactId>jackson-mapper-asl</artifactId>
16             <version>1.9.13</version>
17          </dependency>    

2、在需要查询时间的数据库字段对应的实体类的属性上添加@JsonFormat

1     @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
2     private LocalDateTime updateDate;

注: timezone:是时间设置为东八区,避免时间在转换中有误差,pattern:是时间转换格式

3、 这样我们用对应的实体类来接收数据库查询出来的结果时就完成了时间格式的转换,再返回给前端时就是一个符合我们设置的时间格式了

2、@DateTimeFormat

1、添加依赖

1         <dependency>
2             <groupId>joda-time</groupId>
3             <artifactId>joda-time</artifactId>
4             <version>2.3</version>
5         </dependency>

2、我们在对应的接收前台数据的对象的属性上加@DateTimeFormat

1     @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
2     private LocalDateTime acquireDate;

3.这样我们就可以将前端获取的时间转换为一个符合自定义格式的时间格式存储到数据库了

猜你喜欢

转载自www.cnblogs.com/04241202-nan/p/11422057.html