Using Spring @RestController to handle HTTP GET with ZonedDateTime parameters

Andrés Soto picture Andrés Soto · Sep 11, 2015 · Viewed 9.1k times · Source

I'm creating an endpoint that will receive dates to do some filtering in the server side. The code looks like this:

@RequestMapping(
        value = "/test",
        method = RequestMethod.GET,
        produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}
)
@ResponseStatus(HttpStatus.OK)
public TestSummaryModel getTestSummaryByDate(
        @RequestParam ZonedDateTime start,
        @RequestParam ZonedDateTime end) {

    return testService.getTestBetween(start, end);

}

When I try to invoke my endpoint I get an HTTP 400 error "The request sent by the client was syntactically incorrect."

I have try different date formats but none of them worked. Am I missing something? I read about the @DateTimeFormat but even though I added it, was not working.

@RequestParam @DateTimeFormat(pattern = "dd-MM-yyyy") ZonedDateTime start

This is an example of the request I'm doing:

http://host/test-api/v1/test-summary/test?start=09-09-2015&end=09-09-2015

Thanks!

Answer

Sotirios Delimanolis picture Sotirios Delimanolis · Sep 11, 2015

@DateTimeFormat is what you need. Spring MVC 4 has the appropriate converters for ZonedDateTime.

However, you need to provide an appropriate pattern and send an appropriate value.

The information provided in a date formatted as dd-MM-yyyy is not enough to produce a ZonedDateTime.

Try

@RequestParam("start") @DateTimeFormat(iso = ISO.DATE_TIME) ZonedDateTime start

and send

...?start=2014-04-23T04:30:45.123Z

Alternatively, use a date type that doesn't need zone or time information and provide an appropriate date format to @DateTimeFormat.