在接收前端参数时,为了能够最大程度的偷懒,使用过LocalDate来接收了日期,但是发现一个问题。先看代码:
java
@GetMapping("test")
public Result test(@RequestParam("startDate") LocalDate startDate){}
使用postman测试接口时使用了?startDate=2025/10/10
,发现可正常工作。但是偶然发现在我的chrome访问相同链接就会报错:Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type
查找原因
使用charles抓包发现请求完全一致不存在转义编码,而且用safari也行。
于是java断点,发现了问题LocalDate转换时:
java
public static LocalDate parse(CharSequence text, DateTimeFormatter formatter) {
Objects.requireNonNull(formatter, "formatter");
return formatter.parse(text, LocalDate::from);
}
发现了其中的区别:
问题发现
chrome配置的默认语音是英文。中文的默认短日期格式支持 yyyy/M/d,而英文的默认短日期格式为 M/d/yy,其中月在前,年份在后(且通常简化为两位,如 "20" 表示 2020)。例如,对于 2020 年 10 月 10 日,期望的输入是 "10/10/20",只可表示2000-2099年的范围。
解决
所以非常不建议这么书写,还挑访问环境必须不能惯着。正确书写方式,指定:
java
@GetMapping("test")
public Result test(@RequestParam("startDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate startDate){}
ISO默认:
java
/**
* Common ISO date time format patterns.
*/
enum ISO {
/**
* The most common ISO Date Format {@code yyyy-MM-dd} — for example,
* "2000-10-31".
*/
DATE,
/**
* The most common ISO Time Format {@code HH:mm:ss.SSSXXX} — for example,
* "01:30:00.000-05:00".
*/
TIME,
/**
* The most common ISO Date Time Format {@code yyyy-MM-dd'T'HH:mm:ss.SSSXXX}
* — for example, "2000-10-31T01:30:00.000-05:00".
*/
DATE_TIME,
/**
* Indicates that no ISO-based format pattern should be applied.
*/
NONE
}