Java – Failed to convert value of type java.lang.String to required type java.util.Date

hibernatejavaspringspring-mvc

<form th:action="@{home}" method="get">
    <div class="form-group">
        <label>from date:</label> <input type="date" pattern="yyyy-MM-dd" name="d1" th:value="${d1}" />
        <label>to date:</label> <input type="date" pattern="yyyy-MM-dd"  name="d2" th:value="${d2}" />
        <button type="submit">Trouver</button>
    </div>
</form>

this is the controller code part:

@RequestParam(name = "d1", defaultValue = "1900-01-01") @DateTimeFormat(pattern = "yyyy-MM-dd") Date d1,
        @RequestParam(name = "d2", defaultValue = "2200-01-01") @DateTimeFormat(pattern = "yyyy-MM-dd") Date d2){

Im getting this message:

There was an unexpected error (type=Bad Request, status=400). 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 'Wed Jun 08 00:00:00 WET 2016'; nested exception is
java.lang.IllegalArgumentException: Parse attempt failed for value
[Wed Jun 08 00:00:00 WET 2016]

Best Answer

The pattern you give to your html input elements doesn't work as you expect. You are not setting a format for your date with this, and as you can see from your error message, the date that spring is trying to parse is

Wed Jun 08 00:00:00 WET 2016

not any date in the format you have set in both your html and in your controller (the html pattern doesn't modify the format that gets sent, it's there for validation purposes).

I've never worked with that, but you should either

  • just remove the complete pattern and format and see if that works (I guess it could)
  • set the correct date format in your controller pattern, according to the date format I posted above (and your error message).

Here:

@DateTimeFormat(pattern = "yyyy-MM-dd")
Related Topic