Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

<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]

like image 369
Extony Avatar asked Sep 20 '16 17:09

Extony


2 Answers

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")
like image 117
baao Avatar answered Sep 23 '22 17:09

baao


You have correctly set pattern in the Controller Class with the annotation @DateTimeFormat(pattern = "yyyy-MM-dd"). And please also make sure that you have: imported two required patterns in your Model/Entity Class as:

import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Temporal(TemporalType.DATE)
private Date date;

Hope it does work.cause It worked on mine.

like image 36
N.Neupane Avatar answered Sep 23 '22 17:09

N.Neupane