LocalDate format in Get request JAVA

8.4k views Asked by At

I'm writing a REST interface for my Java MVC app. Here is one function:

    @GetMapping(value = "/restaurant_representation", produces = MediaType.APPLICATION_JSON_VALUE)
    public RestaurantRepresentation restaurantRepresent(
        @RequestParam(value = "date", required = false) LocalDate date,
        @RequestParam(value = "id") Integer id) {
            return date == null ?
                restaurantRepresentationCompiler.compileRestaurantRepresentation(id, LocalDate.now()) :
                restaurantRepresentationCompiler.compileRestaurantRepresentation(id, date);
    }

Now I'm testing this, and

/rest/admin/restaurant_representation?id=1004

this requst provides a correct result, but when I try to add date parameter

/rest/admin/restaurant_representation?date=2015-05-05&id=1004

it showes this:

The request sent by the client was syntactically incorrect.

What LocalDate format is correct?

2

There are 2 answers

1
Nicolazz92 On BEST ANSWER

We need to use @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)

like this:

    @GetMapping(value = "/restaurant_representation", produces = MediaType.APPLICATION_JSON_VALUE)
    public RestaurantRepresentation restaurantRepresent(
        @RequestParam(value = "date", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date,
        @RequestParam(value = "id") Integer id) {
            return date == null ?
                restaurantRepresentationCompiler.compileRestaurantRepresentation(id, LocalDate.now()) :
                restaurantRepresentationCompiler.compileRestaurantRepresentation(id, date);
}
0
Kishore Bandi On

You need to use @DateTimeFormat and specify the format of the date that you're accepting.

@RequestParam(required = false, value = "date") @DateTimeFormat(pattern="yyyy-MM-dd") LocalDate fromDate