【问题标题】:DateTime parsing issue using @DateTimeFormat使用@DateTimeFormat 的日期时间解析问题
【发布时间】:2021-06-19 19:55:18
【问题描述】:

在我的SpringBootApplication 中使用@DateTimeFormat 时遇到问题。下面是我遇到问题的代码sn-p`

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)

代码为 Not Working,日期时间为 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)

例外 - “无法将 'java.lang.String' 类型的值转换为 所需类型“java.time.LocalDateTime”;嵌套异常是 org.springframework.core.convert.ConversionFailedException: 失败 从类型 [java.lang.String] 转换为类型 [@org.springframework.web.bind.annotation.RequestParam @org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime] 值'2021-03-02T10:57:43 05:30';嵌套的 异常是 java.lang.IllegalArgumentException:解析尝试失败 对于价值 [2021-03-02T10:57:43 05:30]"

知道如何解决这个问题吗?

【问题讨论】:

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


    【解决方案1】:

    问题在于您的请求 URL 中的 + 号。这是一个保留的标志。

    您必须对查询参数进行 URL 编码。然后看起来像这样:

    GET http://localhost:8080/test/datetime/1?since=2021-03-02T10:57:43%2B05:30
    

    【讨论】:

    • 感谢您指出问题。我的想法完全不同。
    【解决方案2】:

    URL 中的加号 ("+") 会自动转换为空格字符 (" ")。这可以通过URL encoding 将空格字符设置为"%2B" 来解决。

    http://localhost:8080/test/datetime/1?since=2021-03-02T10:57:43%2B05:30
    

    这个问题可以通过仔细阅读异常消息来确认,它显示解析的文本中有一个空格,而不是加号:

    Parse attempt failed for value [2021-03-02T10:57:43 05:30]"
    

    加号到空格的这种转换是 URL 中相当常见的转换,而且 Spring 似乎默认这样做。

    【讨论】:

    • 感谢您的澄清。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 2022-06-11
    • 2015-07-30
    相关资源
    最近更新 更多