前后端传输Date类型数据时格式化日期 |
您所在的位置:网站首页 › 表格日期型数据 › 前后端传输Date类型数据时格式化日期 |
问题一: 后台在返回json格式的Date类型数据时,直接通过@ResponseBody返回出去的是一个长整型时间戳: 它的作用是,出参时,自动把Date型对象数据转化成格式化后的字符串输出: yyyy-MM-dd HH:mm:ss 案例: Postman请求结果:
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;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 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); } |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |