【问题标题】:Cannot convert string to date type [duplicate]无法将字符串转换为日期类型 [重复]
【发布时间】:2020-01-23 13:19:50
【问题描述】:

我的控制器方法

@GetMapping("/fetch/{one_date}/{two_date}")
    public List<CourierInfo> getData_between(@PathVariable(value = "one_date") @DateTimeFormat(pattern = "dd-MM-yyyy HH:mm:ss") Date fromDate, @PathVariable(value = "two_date") @DateTimeFormat(pattern = "dd-MM-yyyy") Date toDate) throws Exception{
        System.out.println(fromDate);
        System.out.println(toDate);
        String date1 = "20-01-2020";
        String date2 = "24-01-2020";
        Date d1 = new SimpleDateFormat("dd-MM-yyyy").parse(date1);
        Date d2 = new SimpleDateFormat("dd-MM-yyyy").parse(date2);
        return bookRepository.getData_between(d1, d2);
    }

我正在传递日期的网址

http://localhost:8080/book_api/fetch/20-01-2020/24-01-2020

我收到了这个错误

无法将“java.lang.String”类型的值转换为所需的“java.util.Date”类型;嵌套异常是 org.springframework.core.convert.ConversionFailedException: 无法从类型 [java.lang.String] 转换为类型 [@org.springframework.web.bind.annotation.PathVariable @org.springframework.format.annotation.DateTimeFormat java.util.Date] 的值'20-01-2020';嵌套异常是 java.lang.IllegalArgumentException:值 [20-01-2020] 的解析尝试失败

我该如何解决这个错误。我尝试了不同的方法。

【问题讨论】:

  • @DateTimeFormat(pattern = "dd-MM-yyyy HH:mm:ss") 然后你传递了一个没有时间的日期
  • 您传递了格式为dd-MM-yyyy 的日期,但您试图将其解析为dd-MM-yyy HH:mm:ss

标签: java rest spring-boot


【解决方案1】:

尝试更改 DateTimeFormat 为

@PathVariable(value = "one_date") @DateTimeFormat(pattern = "dd-MM-yyyy HH:mm:ss")

@PathVariable(value = "one_date") @DateTimeFormat(pattern = "dd-MM-yyyy")

您只是输入了一个日期,但您还指示格式化程序格式化时间。

【讨论】:

    猜你喜欢
    • 2013-03-11
    • 2019-10-21
    • 2012-03-19
    • 2017-11-04
    • 2013-12-02
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多