问题说明.
从数据库获取时间传到前端进行展示的时候,我们有时候可能无法得到一个满意的时间格式的时间日期,在数据库中显示的是正确的时间格式,获取出来却变成了很丑的时间戳。(
数据库==>前端
)@JsonFormat
注解很好的解决了这个问题,我们通过使用@JsonFormat
可以很好地解决:后台到前台时间格式保持一致的问题。
我们在使用WEB服务的时,可能会从前端传入时间给后端,比如注册新用户需要填入出生日期等,这个时候前台传递给后台的时间格式同样是不一致的,而我们的与之对应的便有了另一个注解
@DataTimeFormat
便很好的解决了这个问题。
注解@JsonFormat主要是后端到前端的时间格式的转换
注解@DateTimeFormat主要是前端到后端的时间格式的转换
@JsonFormat
.
导入依赖.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.11.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.3</version>
</dependency>
使用.
需使用在
Date
字段上或其对应的Getter
方法上
public class User(){
private String name;
private Integer age;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
private Date birth;
}
@DateTimeFormat
.
导入依赖.
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
需要开启 注解驱动.
<mvc:annotation-driven/>
使用.
在实体类的
Date
字段上
public class User(){
private String name;
private Integer age;
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date birth;
}
controller
类的方法Date
参数上
@RequestMapping("add")
public String add(@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date birth){
...
}