我有UT,顺利通过
@Test
public void test() {
String text1 = "2009-07-10T14:30:01.001Z";
String text2 = "2009-07-10T14:30:01.001+03:00";
DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ");
ZonedDateTime zonedDateTime1 = ZonedDateTime.parse(text1, f);
ZonedDateTime zonedDateTime2 = ZonedDateTime.parse(text2, f);
System.out.println(zonedDateTime1);
System.out.println(zonedDateTime2);
}
输出是
2009-07-10T14:30:01.001Z
2009-07-10T14:30:01.001+03:00
但是,当我尝试在 spring-controller 上使用这个模式时
@GetMapping
public ResponseEntity get( @RequestParam("start") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ")
ZonedDateTime start) {
Dto result = service.get(start);
return new ResponseEntity(result, getHeaders(), HttpStatus.OK);
}
它仅在我传递 Z 而不是时区时有效,例如
2009-07-10T14:30:01.001Z
但是当尝试传递时区偏移量时 - 出现错误消息
"Failed to convert value of type 'java.lang.String' to required type 'java.time.ZonedDateTime'; 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.ZonedDateTime] for value '2009-07-10T14:30:01.001 03:00'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2009-07-10T14:30:01.001 03:00]",
我尝试像这样通过 postman 传递请求
POST localhost:9080/MyApp/user?start=2009-07-10T14:30:01.001+03:00
header: Content-Type application/json
最佳答案
您必须对 url 进行编码当你有像 plus sign 这样的特殊字符时(+
)
POST localhost:9080/MyApp/user?start=2009-07-10T14:30:01.001%2B03:00
关于java - Spring rest Controller 从查询参数中的 zoneddatetime 中删除加号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61448838/