从数据库或前端获取时间格式化两种注解方式 @JsonFormat与@DateTimeFormat

解决什么问题?
1 、数据库获取时间传到前端进行展示的时候,在数据库中显示的是正确的时间格式,获取出来成了的时间戳,@JsonFormat注解很好的解决了这个问题

2、 另一个问题是,我们在使用WEB服务的时,可能会需要用到,传入时间给后台,比如注册新用户需要填入出生日期等,这个时候前台传递给后台的时间格式同样是不一致的,而我们的与之对应的便有了另一个注解,@DataTimeFormat便很好的解决了这个问题

用法
1、注解@JsonFormat

pom文件的依赖

<!--JsonFormat-->

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.8</version>
</dependency>

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

<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
实体类中使用

/*读数时间*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Column(name = "read_time")
private Date readTime;
timezone:是时间设置为东八区,避免时间在转换中有误差

//设置时区为上海时区,时间格式自己据需求定。
@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
private Date testTime;
2.注解@DateTimeFormat

pom

<!-- joda-time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.3</version>
</dependency>
在对应的接收前台数据的对象的属性上加@DateTimeFormat

@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date symstarttime;

posted @ 2022-06-17 13:43  liftsail  阅读(680)  评论(0编辑  收藏  举报