springboot后端时间到前端,相差8小时,时间格式不对

时间:2023-03-09 19:50:35
springboot后端时间到前端,相差8小时,时间格式不对

spring boot后台时间正确,返回给前台的时间不正确,和后台差8个小时

{
"code": 1,
"msg": "SUCCESS",
"result": {
"extractRecords": null,
"chargeRecords": [
{
"id": 4,
"account": "1604516",
"deposit_paid": 500,
"deposit_paid_time": "2019-05-30T03:01:03.000+0000"
}
]
}
}

原因是:

spring-boot中对于@RestController或者@Controller+@ResponseBody注解的接口方法的返回值默认是Json格式,

所以当对于date类型的数据,在返回浏览器端是会被spring-boot默认的Jackson框架转换,而Jackson框架默认的时区GMT(相对于中国是少了8小时)。

处理方式:

在application.yml添加配置

spring:
jackson:
#日期格式化
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8

再次访问的数据:

{
"code": 1,
"msg": "SUCCESS",
"result": {
"extractRecords": null,
"chargeRecords": [
{
"id": 4,
"account": "1604516",
"deposit_paid": 500,
"deposit_paid_time": "2019-05-30 11:01:03"
}
]
}
}

jackson的全部配置:

spring:
jackson:
#日期格式化
date-format: yyyy-MM-dd HH:mm:ss
serialization:
#格式化输出
indent_output: true
#忽略无法转换的对象
fail_on_empty_beans: false
#设置空如何序列化
defaultPropertyInclusion: NON_EMPTY
deserialization:
#允许对象忽略json中不存在的属性
fail_on_unknown_properties: false
parser:
#允许出现特殊字符和转义符
allow_unquoted_control_chars: true
#允许出现单引号
allow_single_quotes: true