@JsonFormat与@DateTimeFormat注解的使用
一、区别
注解@JsonFormat主要是后台到前台的时间格式的转换
注解@DataFormAT主要是前台到后台的时间格式的转换
二、@JsonFormat 的使用
@JsonFormat(pattern=“yyyy-MM-dd”,timezone = “GMT+8”) pattern:是你需要转换的时间日期的格式 timezone:是时间设置为东八区,避免时间在转换中有误差
public static final String DATEFORMAT = "yyyy-MM-dd HH:mm:ss";
示例:
三、@DateTimeFormat 的使用
-
@DateTimeFormat 直接接收指定的时间格式,既灵活又方便。
在Controller中 @RequestParam和 @DateTimeFormat搭配使用
示例:
@GetMapping("/getSceneMapByTimeToTime") public List<SceneMap> getSceneMapByTimeToTime(@RequestParam("startTime") @DateTimeFormat(pattern=Constants.DATEFORMAT)Date startTime, @RequestParam("endTime") @DateTimeFormat(pattern=Constants.DATEFORMAT)Date endTime){ return sceneMapService.getSceneMapByTimeToTime(startTime,endTime); }
四、同时使用
在controller层我们使用spring mvc 表单自动封装映射对象时,我们在对应的接收前台数据的对象的属性上加 @JsonFormat与@DateTimeFormat注解 若既需要取数据到前台,也需要前台数据传到后台,都需要进行时间格式的转换,可以同时使用
@DateTimeFormat(pattern = "yyyy-MM-dd") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") private Date symstarttime; @DateTimeFormat(pattern = "yyyy-MM-dd") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") private Date symendtime;
上一篇:
通过多线程提高代码的执行效率例子