记一次DateTimeFormat注解的坑

记一次DateTimeFormat注解的坑

背景:在用Echarts做图表时,前端传两个日期参数,获取日期区间的图表数据。想遵循RESTful风格,所以使用get请求获取date参数。前端读取当前日期,将七天前日期和当前日期作为参数传给后端,后端通过Date参数接收。然后后端报错,无法识别前端的date参数。经查阅,可以通过@DateTimeFormat标注在QueryString参数上可解决报错。然后发现DateTimeFormat接收前端的date参数时会比实际时间少8小时。

1. @DateTimeFormat

@DateTimeFormat注解是springboot内置的时间格式化注解,将@DateTimeFormat标注在RequestParam参数上。可以格式化DateTime参数。

假如不使用@DateTimeFormat,且前端传date对象,后端用Date接收,会导致错误

shell 复制代码
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value [2024-01-11]; nested exception is java.lang.IllegalArgumentException
	at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:133)
......

加上@DateTimeFormat,问题解决,如下所示

java 复制代码
    @GetMapping("statData")
    public Result statData(@DateTimeFormat(pattern="yyyy-MM-dd") Date start,
                           @DateTimeFormat(pattern="yyyy-MM-dd") Date end){
        List<Integer> integers = blogIncreaseService.statData(start, end);
        return ResultUtils.success().data(integers);
    }

2. 提前8小时问题

前端如果传的date,后端用Date接收(用@DateTimeFormat(pattern="yyyy-MM-dd"标识),会导致后端接收的数据比实际系统数据早8小时(不知道是前端获取时间时区问题还是怎么的)。这不符合我们的实际需求。

解决方案有三种

    1. 在以上基础上,后端接收的Date数据基础上加上8小时。
    1. 放弃使用Get请求,用Post,用RequestBody接收前端请求数据,在日期参数上使用@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")格式花日期。@JsonFormat可以格式化时区,@DateTimeFormat没有timezone参数
    1. 继续使用@DateTimeFormat,但前端不传date对象,改用字符串。

个人感觉还是第三种方案最好,如果前端开发小姐姐配合的话。

具体解决步骤不列举了,比较简单,重点是最近我很懒,懒得写笔记。

总结

总而言之,使用@DateTimeFormat时注意留意是否提前8小时,主要是开发测试时还可能发现不了,我就是上生产时才发现的问题,还好影响不大。

相关推荐
毕设源码-赖学姐6 小时前
【开题答辩全过程】以 高校评教评学系统的设计与实现为例,包含答辩的问题和答案
java·eclipse
老华带你飞6 小时前
博物馆展览门户|基于Java博物馆展览门户系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端
路边草随风6 小时前
iceberg 基于 cosn 构建 catalog
java·大数据
It's now6 小时前
Spring Framework 7.0 原生弹性功能系统讲解
java·后端·spring
点PY6 小时前
C++ 中 std::async 和 std::future 的并发性
java·开发语言·c++
无限大66 小时前
Agent 入门科普:从"人工智障"到"数字打工人"的进化史
后端
一 乐7 小时前
人事管理系统|基于Springboot+vue的企业人力资源管理系统设计与实现(源码+数据库+文档)
java·前端·javascript·数据库·vue.js·spring boot·后端
带刺的坐椅7 小时前
Solon AI 开发学习19 - 结合 Solon Flow 实现 ReAct 效果
java·ai·chatgpt·llm·openai·solon·deepseek
SelectDB7 小时前
浙江头部城商行:每日 700 万查询、秒级响应,Apache Doris 查算分离架构破局资源冲突
数据库·后端·apache
CoderYanger7 小时前
Java SE——12.异常(≠错误)《干货笔记》
java·开发语言