Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Spring @RestController to handle HTTP GET with ZonedDateTime parameters

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!

like image 819
Andrés Soto Avatar asked Sep 10 '15 22:09

Andrés Soto


1 Answers

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

like image 178
Sotirios Delimanolis Avatar answered Sep 19 '22 20:09

Sotirios Delimanolis