java - 使用 @DateTimeFormat 的日期时间解析问题

标签 java spring-boot spring-mvc urlencode java-time

我在 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/

相关文章:

java - 如何替换字符串模板(Gradle)

java.lang.IllegalStateException : Failed to load property source from location 'classpath:/application.yml' 错误

java - 如何在 gradle 启动测试中关闭关闭 Hook 的输出?

java - 如何使用 Spring MVC JSR-303 Validator 将不同的模型类验证为一种形式

java - 将项目资源中的图像写入字节数组

java - Android 应用程序中的 slider

java - 如何将 spring application.yml 文件中的字符串列表读入 Immutables 对象?

java - 信息 : No Spring WebApplicationInitializer types detected on classpath (jre 1. 8)

java - 需要在客户端/用户计算机而不是 Spring Boots 或 MVC 中的服务器计算机上下载 pdf 文件

java - 从网站访问视频内容