spring boot接收前端传递过来的时间,总是比实际时间晚几个小时或者早几个小时,这是由于使用在@RequestBody 实体类,进行接收json类型字符串的时候,会把接受的string时间字段转换成lang类型,然后对应实体类的时候,会按照GMT+0时区的时间进行处理。
解决办法:
1,使用@JsonFormat注解,并且指定时区
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date timingDate;
2,使用@DateTimeFormat注解,但此方法在pattern="yyyy-MM-dd HH:mm:ss"时不适用Jackson,只支持时间类型为pattern="yyyy-MM-dd"的。
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date timingDate;
3,Controller接收时,按照json字符串接收,然后代码对应到bean里时,特殊处理时间字段。
需要使用到net.sf.json。
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;
@RequestMapping("/insideByJson.tml")
public @ResponseBody Map<String, Object> insideByJson(@RequestBody String jsonParam) {
//json字符串转换成bean
JSONObject json=JSONObject.fromObject(jsonParam);
String[] dateFormats = new String[]{"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd"};
JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFormats));
Inside inside=(Inside) JSONObject.toBean(json, Inside.class);
}