java - Spring REST 中将日期作为请求参数

标签 java spring rest date spring-boot

我的 Controller 如下所示:

@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。完整的异常(exception)是:

{
  "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!!!");
}

它可以正常工作,没有任何异常。相同的日期格式,相同的日期。

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

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

最佳答案

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

关于java - Spring REST 中将日期作为请求参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44187535/

相关文章:

java - 如何使用 RestTemplate 向相对 URL 发送 POST 请求?

javascript - WP-json 未使用 angularJS 显示

java - Spring Boot 页面反序列化 - PageImpl 无构造函数

Java 差异方法

java - JAXB 问题,Marshal,无法编码类型 "java.lang.String"

java - Spring AOP 中 @DeclareParents 注解中的泛型类型

java - 是否可以根据在 java 中调用方法的位置在方法中执行不同的代码?

java - Spring 存储库自动转换具有不同类类型的实体

java - 这里需要多线程: More students submitting their response to store in database

java - 如何从 REST 服务生成实体?