日期前后端处理
日期前后端处理总结:
1.如果前后端传的数据都是json格式,那么后台接数据,传数据都可以用@JsonFormat ;
2.@DateTimeFormat适合后端接收前端传来的数据,不管是不是json格式都可以正确转换成Date型数据,只要前端传来的格式正确且后端@DateTimeFormat的pattern写正确。但是,这个注解无法将Date型数据用json传到前端去
解决spring boot接收前端传递过来的json数据时,接收到的时间与实际传递时间不一致的问题
spring boot接收前端传递过来的时间,总是比实际时间晚几个小时或者早几个小时,这是由于使用在@RequestBody 实体类,进行接收json类型字符串的时候,会把接受的string时间字段转换成lang类型,然后对应实体类的时候,会按照GMT+0时区的时间进行处理。
解决办法:
1,使用@JsonFormat注解,并且指定时区
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date timingDate;
- 1
- 2
2,使用@DateTimeFormat注解,但此方法在pattern="yyyy-MM-dd HH:mm:ss"时不适用Jackson,只支持时间类型为pattern="yyyy-MM-dd"的。
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date timingDate;
- 1
- 2
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);
}
浙公网安备 33010602011771号