我在Spring中编写了以下代码
@GetMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public StationView getSingleStation(@PathVariable Long id,
@RequestHeader("Authorization") String tokenHeader,
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @RequestParam LocalDateTime startDate,
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @RequestParam LocalDateTime endDate)
但是当我尝试以yyyy-MM-dd'T'HH:mm:ss.SSSZ格式发送数据时(例如2018-11-27T10:57:43.019 + 0100)它确实抛出异常
Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: 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.format.annotation.DateTimeFormat @org.springframework.web.bind.annotation.RequestParam java.time.LocalDateTime] for value '2018-11-27T10:57:43.019 0100'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2018-11-27T10:57:43.019 0100]]
我注意到该框架删除了'+'
我收到消息:“值[2018-11-27T10:57:43.019 0100]的解析尝试失败]]
当我经过2018-11-27T10:57:43.019 + 0100
Java中通过使用ZonedDateTime
类而不是LocalDateTime
支持时区。参见docs。
要么修改方法签名(可能也使用@DateTimeFormat),或者决定不使用日期中的时区。
解析尝试失败,值[2018-11-27T10:57:43.019 0100]
您的字符串似乎已被URL解码:其中的+
(加号)已被空格替换。请避免在发送它之前对它进行URL编码,或者可能更好,以便URL解码将恢复原始字符串。
航海家可能也有一点。我将添加一些精度:由于您的字符串包含偏移量+01:00
,因此要使用的正确类型是OffsetDateTime
。另一个答案中提到的ZonedDateTime
类是针对您所在的时区,例如America / Nome。时区ID的格式为区域/城市。