Akeshwar Jha
Akeshwar Jha

Reputation: 4576

Date as a request parameter in Spring REST

My controller looks like this:

@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
}

The POSTMAN query:

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

It's giving me IllegalArgumentException. The full exception is:

{
  "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"
}

Now, strangely when I run:

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

It works without any exception. Same date-format, same date.

One workaround would be to receive the date as a string and then do the conversions through the parser method.

But I'm concerned more about what's going on behind the scene here.

Upvotes: 8

Views: 14650

Answers (3)

Luay Abdulraheem
Luay Abdulraheem

Reputation: 761

Make sure you change to @RequestParam(value = "date", required = false), as the parameter value is not the same as your URL parameter name which you are using in Postman.

Also looking at your logs, you're using java.util.Date. Have you considered using new Java 8 API, java.time.LocalDate instead ?

Upvotes: 0

Rizwan
Rizwan

Reputation: 2437

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

USE:

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

S Millisecond X Time zone
ISO 8601 time zone -07; -0700; -07:00

Upvotes: 1

eg04lt3r
eg04lt3r

Reputation: 2610

Try to use Z instead of XXX in your pattern. It should works.

Upvotes: 0

Related Questions