问题:
首先,在做项目时发现从数据库获取时间传到前端进行展示时,我们有时可能无法得到一个满意的时间格式的时间日期或者出现乱码现象,而在数据库中显示的是正确的时间格式,问题一:该怎样才能保证后台跟前台的时间格式保持一致呢?
其次,我们有时候在使用WEB服务的时,可能会需要将时间给后台,比如注册新用户需要填入出生日期等,这个时候会发现前台传递给后台的时间格式同样是不一致的,问题二:该怎样才能保证前台跟后台的时间格式保持一致呢?
解决方法:
1、使用注解@JsonFormat解决问题一
1.1、首先需要导入相关的依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.12.3</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
1.2、在实体类的属性上添加注解@JsonFormat
@Data
@AllArgsConstructor //有参构造函数
@NoArgsConstructor //无参构造函数
public class Customer {
// 注解@JsonFormat主要是后台到前台的时间格式的转换
// 注解@DataFormAT主要是前后到后台的时间格式的转换
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date cust_createtime;
}
注:@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
pattern:是你需要转换的时间日期的格式
timezone:是时间设置为东八区,避免时间在转换中有误差
提示:@JsonFormat注解可以在属性的上方,同样可以在属性对应的get方法上,两种方式没有区别
1.3、最后
完成以上之后,我们用对应的实体类来接收数据库查询出来的结果时就完成了时间格式的转换,再返回给前端时就是一个符合我们想要的设置的时间格式了。
2、使用注解@DateTimeFormat解决问题二
2.1、首先需要导入相关依赖(Spring、jodatime等依赖)
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.3</version>
</dependency>
2.2、在实体类的属性上添加注解@DateTimeFormat
@Data
@AllArgsConstructor //有参构造函数
@NoArgsConstructor //无参构造函数
public class Customer {
// 注解@JsonFormat主要是后台到前台的时间格式的转换
// 注解@DataFormAT主要是前后到后台的时间格式的转换
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date cust_createtime;
}
注:两个注解都同时使用
2.3、 最后
完成以上之后,我们就可以获取一个符合自定义格式的时间格式存储到数据库了。
结论: