springboot前后端分离项目,一般都是使用json将数据传回前端。
spring默认使用jackjson转换json对象和实体类属性。
所以会发现传回前端的时间早了8个小时
两种解决方法。
方法一,在实体类的时间字段上加上注解
public class HrDept implements Serializable {
@DateTimeFormat(pattern="yyyy-MM-dd")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="Asia/Shanghai")
private Date startDate; //起始时间
@DateTimeFormat(pattern="yyyy-MM-dd")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="Asia/Shanghai")
private Date startDate; //结束时间
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="Asia/Shanghai")
private Date updateTime;
}
@DateTimeFormat(入参格式化):前端传入的startDate格式必须符合 "yyyy-MM-dd HH:mm:ss",才能自动从字符串转换成date类型。所以DateTimeFormat是设置成"yyyy-MM-dd"还是"yyyy-MM-dd HH:mm:ss"要根据自己的需要。
@DateTimeFormat(出参格式化):将数据库查询出的日期数据,格式成json字符串格式,在前端展示。必须设置timezone,否则时间会差几个小时
方法二,在springboot的配置文件中对jackson做配置
如果使用properties格式的配置文件,application.properties写法如下:
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=Asia/Shanghai
如果使用yml格式的配置文件,application.yml写法如下:
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: Asia/Shanghai
如果没有实体类,而是使用Map格式往前台传输数据,那就只能使用第二种方法了。