spring.jackson.time-zone=GMT+8
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
springboot之restTemplate學習
SpringBoot系列: RestTemplate 快速入門 - harrychinese - 博客園 (cnblogs.com)
由於springboot默認使用jackson做序列化,但是jackson序列化按照的是GMT時區的時間。中國是GTM+8小時,所以原本在中國是2020-11-28 19:00:00,序列化到前端就是2020-11-28 12:00:00
就是說北京時間晚上19點的時候,倫敦才中午12點。
解決返回前端的日期字段少了8小時,可以通過入下三種方式,
一:所有日期字段加上時區
@JsonFormat( pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8" ) private Date date;
二:springboot配置文件中統一配置
spring.jackson.time-zone=GMT+8
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
三:通過配置類的方式:
@Configuration public class TimeZoneConfiguration { @Bean public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization() { return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.timeZone(TimeZone.getTimeZone("GMT+8")); } }
前端的展示時間的問題解決了,但是后端的問題並沒有解決,一次偶然中發現,微服務consumer調用微服務provider的時候,傳過去的時間也少了8個小時。
排查后發現使用springboot的RestTemplate請求去調用服務的時候,也會進行jackson序列化,此時上面三種方式,二和三都失效了,序列化的時候都不會幫我們+8小時,
只有在每個字段上面加上時區標識才有效
timezone = "GMT+8"
調式看為什么RestTemplate的時候序列化少8小時

代碼調式到這里的時候,值變了
com.fasterxml.jackson.databind.ObjectWriter#writeValue(com.fasterxml.jackson.core.JsonGenerator, java.lang.Object)

最后跟到這里來了。java.text.SimpleDateFormat#format(java.util.Date, java.lang.StringBuffer, java.text.Format.FieldDelegate)

最關鍵的日期字段格式化在這里
g.writeString(f.format(value));

DateFormat里面的屬性如下:

calendar里面的時區,使用的是UTC(相當於GMT+0)


