如何建立自己的公司网站,有什么做服装的网站,关联词有哪些五年级,现在做一个网站系统多少钱记一次DateTimeFormat注解的坑
背景#xff1a;在用Echarts做图表时#xff0c;前端传两个日期参数#xff0c;获取日期区间的图表数据。想遵循RESTful风格#xff0c;所以使用get请求获取date参数。前端读取当前日期#xff0c;将七天前日期和当前日期作为参数传给后端在用Echarts做图表时前端传两个日期参数获取日期区间的图表数据。想遵循RESTful风格所以使用get请求获取date参数。前端读取当前日期将七天前日期和当前日期作为参数传给后端后端通过Date参数接收。然后后端报错无法识别前端的date参数。经查阅可以通过DateTimeFormat标注在QueryString参数上可解决报错。然后发现DateTimeFormat接收前端的date参数时会比实际时间少8小时。
1. DateTimeFormat
DateTimeFormat注解是springboot内置的时间格式化注解将DateTimeFormat标注在RequestParam参数上。可以格式化DateTime参数。
假如不使用DateTimeFormat且前端传date对象后端用Date接收会导致错误 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.IllegalArgumentExceptionat org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:133)
......加上DateTimeFormat问题解决如下所示 GetMapping(statData)public Result statData(DateTimeFormat(patternyyyy-MM-dd) Date start,DateTimeFormat(patternyyyy-MM-dd) Date end){ListInteger integers blogIncreaseService.statData(start, end);return ResultUtils.success().data(integers);}2. 提前8小时问题
前端如果传的date后端用Date接收用DateTimeFormat(patternyyyy-MM-dd标识,会导致后端接收的数据比实际系统数据早8小时不知道是前端获取时间时区问题还是怎么的。这不符合我们的实际需求。
解决方案有三种 在以上基础上后端接收的Date数据基础上加上8小时。 放弃使用Get请求用Post用RequestBody接收前端请求数据在日期参数上使用JsonFormat(pattern “yyyy-MM-dd HH:mm:ss”)格式花日期。JsonFormat可以格式化时区DateTimeFormat没有timezone参数 继续使用DateTimeFormat但前端不传date对象改用字符串。
个人感觉还是第三种方案最好如果前端开发小姐姐配合的话。
具体解决步骤不列举了比较简单重点是最近我很懒懒得写笔记。
总结
总而言之使用DateTimeFormat时注意留意是否提前8小时主要是开发测试时还可能发现不了我就是上生产时才发现的问题还好影响不大。