【问题标题】:Date as a request parameter in Spring REST日期作为 Spring REST 中的请求参数
【发布时间】:2017-10-26 12:27:16
【问题描述】:

我的控制器如下所示:

@RequestMapping(value = "/process_date", method = RequestMethod.GET)
    public ResponseEntity processDate
       (@RequestParam(value = "time", required = false) 
        @DateTimeFormat(pattern="yyyy-MM-dd'T'HH:mm:ssXXX") Date date){
// process the date
}

POSTMAN 查询:

http://localhost:8080/process_date?date=2014-05-09T00:48:16-04:00

它给了我IllegalArgumentException。完整的例外是:

{
  "timestamp": 1495736131978,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
  "message": "Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; 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.util.Date] for value '2013-05-10T07:48:16-04:00'; nested exception is java.lang.IllegalArgumentException: Illegal pattern component: XXX",
  "path": "/airspaces"
}

现在,奇怪的是,当我跑步时:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
try {
    System.out.println(df.parse("2013-05-10T07:48:16-04:00"));
} catch (ParseException e) {
    System.out.println("PARSE EXCEPTION!!!");
}

它毫无例外地工作。相同的日期格式,相同的日期。

一种解决方法是将日期作为字符串接收,然后通过解析器方法进行转换。

但我更关心幕后发生的事情。

【问题讨论】:

标签: java spring rest date spring-boot


【解决方案1】:

yyyy-MM-dd'T'HH:mm:ssXXX

使用:

yyyy-MM-dd'T'HH:mm:ss.SSSXXX >>> 2017-05-04T12:08:56.235-07:00

S 毫秒 X 时区
ISO 8601 时区 -07; -0700; -07:00

【讨论】:

    【解决方案2】:

    尝试在您的模式中使用Z 而不是XXX。它应该可以工作。

    【讨论】:

    • 它会工作,但它不允许我发送时区。
    • 如果您在时区中删除分号,它将允许在您的请求中使用-0400 而不是-04:00。请查看此帖子stackoverflow.com/questions/23251895/…
    【解决方案3】:

    确保更改为 @RequestParam(value = "date", required = false),因为参数 value 与您在 Postman 中使用的 URL 参数名称不同。

    同时查看您的日志,您正在使用java.util.Date。您是否考虑过使用新的 Java 8 API java.time.LocalDate 来代替?

    【讨论】:

      猜你喜欢
      • 2018-03-23
      • 2019-10-07
      • 2018-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      • 1970-01-01
      相关资源
      最近更新 更多