首页 > 解决方案 > 使用@DateTimeFormat 的日期时间解析问题

问题描述

我在@DateTimeFormat使用SpringBootApplication. 下面是我遇到问题的代码片段`

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] 的解析尝试失败”

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

标签: javaspring-bootspring-mvcurlencodejava-time

解决方案


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

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

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

推荐阅读