Reputation: 539
I'm having a few issues with getting a date from a controller because I don't understand what's the right format for it to work.
Controller:
@RequestMapping(value = "/findFlights", method = RequestMethod.POST)
public String findFlights(@RequestParam("from") String from, @RequestParam("to") String to,
@RequestParam("departureDate") @DateTimeFormat(pattern = "YYYY-MM-DD") LocalDate departureDate, Model model) {}
Form:
<form th:action="@{/findFlights}" method="POST">
From:<input type="text" name="from" required/>
To:<input type="text" name="to" required/>
Departure Date:<input type="date" name="departureDate" required />
<input type="submit" value="Search"/>
</form>
When I submit the form it always gives me an error no matter what the format of the date is :( Here is the error:
Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate'; 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.time.LocalDate] for value '2018-11-05'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2018-11-05]
If I specify the @DateTimeFormat
annotation I thought that the conversion would be done automatically.
Upvotes: 1
Views: 7991
Reputation: 44980
In YYYY-MM-DD
pattern Y
is a week year and D
is day in a year as per SimpleDateFormat javadoc. For standard dates the pattern should be yyyy-MM-dd
:
@DateTimeFormat(pattern = "yyyy-MM-dd")
or if you want to use DateTimeFormat.ISO
enum:
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
Upvotes: 2