You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中使用@RequestParam绑定LocalDateTime报错求助

问题分析与解决方案

错误原因

你使用的@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)要求参数必须符合ISO日期时间格式(例如2022-07-28T00:00:00),但你传入的是纯日期字符串2022-07-28,缺少时间部分,导致Spring无法完成字符串到LocalDateTime的转换,抛出类型转换异常。

三种可行解决方案

1. 适配纯日期格式

修改@DateTimeFormat的pattern属性,指定纯日期的解析格式,Spring会自动将纯日期字符串转换为当天0点的LocalDateTime:

public ResponseData getTotalRevenue(@RequestParam(value = "startDate")
                                    @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDateTime startDate,
                                    @RequestParam(value = "endDate")
                                    @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDateTime endDate) {
    // 业务逻辑
}

2. 传入符合ISO标准的日期时间参数

保持现有注解不变,请求时传入带时间部分的参数,符合ISO.DATE_TIME格式要求:

/total-revenue?startDate=2022-07-28T00:00:00&endDate=2022-08-20T23:59:59

3. 改用LocalDate接收(推荐)

如果业务场景只需要日期信息,直接用LocalDate类型接收参数更合理,Spring默认支持yyyy-MM-dd格式的解析,无需额外注解:

public ResponseData getTotalRevenue(@RequestParam(value = "startDate") LocalDate startDate,
                                    @RequestParam(value = "endDate") LocalDate endDate) {
    // 如需转换为LocalDateTime,可手动处理:
    LocalDateTime startDateTime = startDate.atStartOfDay();
    LocalDateTime endDateTime = endDate.atTime(23, 59, 59);
    // 业务逻辑
}

内容的提问来源于stack exchange,提问作者namkellbi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 15:39:14