![](/img/trans.png)
[英]Can't use LocalDateTime RequestParam in Spring, I keep getting bad request
[英]Use LocalDateTime RequestParam in Spring boot
当我尝试使用带有 LocalDateTime 的 RequestParam 时遇到问题:
public ResponseData getTotalRevenue(@RequestParam(value = "startDate")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
@RequestParam(value = "endDate")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate){
//....
}
我用这个参数测试:
/total-revenue?startDate=2022-07-28&endDate=2022-08-20
我收到以下错误:
Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime'; nested exception is org.springframework.core.convert.ConversionFailedException:
Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam @org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime]
for value '2022-07-28'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2022-07-28]]
任何人都可以帮助我吗? 太感谢了。
DateTimeFormat.ISO.DATE_TIME 是一种需要日期和时间的格式,但您的请求只包括日期。 请改用 DateTimeFormat.ISO.DATE。
该错误是不言自明的:
值的解析尝试失败 [2022-07-28]]
我认为您希望startDate
和endDate
的类型为LocalDate
而不是LocalDateTime
因为您想表示日期。
无论如何,您传递的查询参数是错误的DateTimeFormat
。 而不是DateTimeFormat.ISO.DATE_TIME
,您应该使用DateTimeFormat.ISO.DATE
。
public ResponseData getTotalRevenue(@RequestParam(value = "startDate")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDateTime startDate,
@RequestParam(value = "endDate")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDateTime endDate) {
//....
}
这是一个示例供您参考。
查看所有 ISO 格式的文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.