关于@JsonFormat和@DateTimeFormat注解的理解和看法
这篇博客的缘由: 在获取数据库的timestamp字段时想到有两个关于时间格式化的注解,于是便来琢磨这两者的区别
前后端交换数据时很多种传输的方式
- 请求体
- 路径参数
- 查询参数
- 表单
- etc
正文
-
场景一:前端通过请求体@RequestBody将时间数据传输到后端,如果请求体的时间字段和后端实体类的时间字段的默认格式不同,就需要使用@JsonFormat来转化数据
前端json数据
{ "lastLoginTime": "2025-11-29 11:56:55" }LocalDateTime的默认格式
System.out.println(LocalDateTime.now()); -->2025-11-30T00:55:21.693146800可以看到
前端json数据和LocalDateTime的默认格式不同(多了一个T),这个时候就需要手动指定格式告诉后端public class Admin implements Serializable { @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private LocalDateTime lastLoginTime; }这样设置之后无论是前端传数据到后端还是后端传数据到前端都能正常显示(没T的格式), 有人就要问了,如果就是默认的带T的格式呢?如果是默认的就可以不用写@JsonFormat了,当然,这只是针对 LocalDdateTime来说的。
-
场景二:前端通过路径参数@PathVariable传递数据
http://localhost:8080/admin/time?createTime=2025-11-30 00:02:49@GetMapping("/time") public Result getAdminByCreateTime( @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime createTime){ log.info("查询管理员创建时间:{}",createTime); Admin admin = adminService.getAdminByCreateTime(createTime); return Result.success(admin); } -
场景三:前端通过查询参数@RequestParams传递数据
http://localhost:8080/admin/time/createTime=2025-11-30 00:02:49@GetMapping("/time/{createTime}") public Result getAdminByCreateTime( @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime createTime){ log.info("查询管理员创建时间:{}",createTime); Admin admin = adminService.getAdminByCreateTime(createTime); return Result.success(admin); }
总结
- 使用请求体传参到后端用@JsonFormat
- 使用路径参数和查询参数传参用@DateTimeFormat
- 当查询参数过多,后端使用对象接收查询参数时依旧使用@DateTimeFormat