jackson在处理date类型时,如果不指定时区,则会默认去UTC。当系统时间不是UTC时(东八区为GMT+8),容易造成和正确时间不符合的情况。问题常见于springmvc接受json时间参数等场景。
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
TimeZone timeZone = objectMapper.getSerializationConfig().getTimeZone();
System.out.println(timeZone);//未设置时,默认时区为UTC
//sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
@PostMapping("timezone-vo")
public String timezone_vo(@RequestBody TimeVo vo) {
log.info(vo.toString());
return JSON.toJSONString(vo, SerializerFeature.WriteDateUseDateFormat);
}
@Test
public void timezone_vo() throws Exception {
Map param = new HashMap();
param.put("time", "2019-07-19");
ObjectMapper mapper = new ObjectMapper();
mockMvc.perform(MockMvcRequestBuilders.post("/json/timezone-vo")
.contentType(MediaType.APPLICATION_JSON).content(mapper.writeValueAsString(param)))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(print());
//Body = {"time":"2019-07-19 08:00:00"}
}