问题描述
调项目时发现前端时间始终比后端返回时间慢8小时
前端和数据库时区都已设置为Asia/Shanghai
问题原因
SpringBoot中对加了@RestController或者@Controller+@ResponseBody注解的方法的返回值默认是Json格式,所以,对date类型的数据,在返回浏览器端时,会被SpringBoot默认的Jackson框架转换,而Jackson框架默认的时区GMT(相对于中国是少了8小时)。所以最终返回到前端结果是相差8小时。
解决方案
解决方案:
- 将spring的json构造器的时区改正即可,在application.yml文件中添加:
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
- 可以使用注解,在entity实体类的date数据上添加注解,那么数据库传回的data数据要转换为json格式的时候就是北京时间了,再次传回到前端的时候,也不会出现时区问题。
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date updateDate;
修改后的问题
前端new date以后是Sat Nov 26 2022 21:37:29 GMT+0800格式,与后端配置的格式不一致,导致后端无法接受前端的时间参数,所以前端需要格式化一下时间,格式化代码如下:
/** 时间格式转换
* @param e 要转换的日期(如:Sat Nov 26 2022 21:37:29 GMT+0800 (中国标准时间))
* @returns {string} 转换结果(如:2022-11-26 21:37:29)
*/
timeFormatConvert(e) {
const Y = e.getFullYear(); // 年
const M = this.prefixZero(e.getMonth() + 1); // 月
const D = this.prefixZero(e.getDate()); // 日
const H = this.prefixZero(e.getHours()); // 时
const Mi = this.prefixZero(e.getMinutes()); // 分
const S = this.prefixZero(e.getSeconds()); // 秒
return Y + "-" + M + "-" + D + " " + H + ":" + Mi + ":" + S;
},
prefixZero(num = 0, n = 2) {
// 数字位数不够,数字前面补零
return (Array(n).join("0") + num).slice(-n);
},