我在 SpringBootApplication
中使用 @DateTimeFormat
时遇到问题。下面是我遇到问题的代码片段`
package com.example.demo;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
@RestController
public class DateTimeController {
@GetMapping("/test/datetime/{id}")
public String testDateParsing(@PathVariable String id,
@RequestParam("since") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssz") LocalDateTime since) {
System.out.println("id : " + id);
System.out.println("since : " + since);
return "success";
}
}
代码在 EST 时区的日期时间下运行良好 -
http://localhost:8080/test/datetime/1?since=2021-03-02T10:57:43-05:00
- I am getting SUCCESS response for 2021-03-02T10:57:43-05:00 (EST Time)
代码无法正常工作
,日期时间为 IST 时区 -
http://localhost:8080/test/datetime/1?since=2021-03-02T10:57:43+05:30
- I am getting ERROR response for 2021-03-02T10:57:43+05:30 (IST Time)
Exception - "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 '2021-03-02T10:57:43 05:30'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2021-03-02T10:57:43 05:30]"
知道如何解决此问题吗?
最佳答案
问题出在您的请求 URL 中的 + 号。这是一个保留标志。
您必须对查询参数进行 URL 编码。然后它看起来像这样:
GET http://localhost:8080/test/datetime/1?since=2021-03-02T10:57:43%2B05:30
关于java - 使用 @DateTimeFormat 的日期时间解析问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66758453/