1

I'm trying to make a request to a api that i created. I must provide a name (String) and a date interval (two Dates). I'm getting the following error:

Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is java.lang.IllegalArgumentException: Could not parse date: Unparseable date: "20151211"

I've tried a lot of date formats, but none works. The request url is something like this:

http://localhost:8080/api/avaiableRoomTypes?hotel=Marriot&start=20151211&end=20151213

The controller method:

@RequestMapping(value = "api/avaiableRoomTypes", method = RequestMethod.GET)
public List<Room> CheckRoomTypeAvailability(@RequestParam(value="hotel") String name,@RequestParam(value="start") Date start,@RequestParam(value="end") Date end) {
    Hotel hotel = hotels.findByName(name);
    Iterable<RoomType> roomtypesList = roomtypes.findByhotel(hotel);
    Iterator<RoomType> roomtypesIt = roomtypesList.iterator();
    List<Room> roomsList = new ArrayList<Room>();
    while(roomtypesIt.hasNext()){
        RoomType rt = roomtypesIt.next();
          roomsList.addAll(rooms.findWithDates(start, end, rt.getId()));
    }

    return roomsList;

}
Miguel Morujão
  • 1,131
  • 1
  • 14
  • 39

2 Answers2

2

You need to declare a String in your method header, then parse the Date in your method.

You should also note that Date's string constructor is deprecated https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#Date-java.lang.String-. Docs suggests using DateFormat. Well, that's assuming your on java 8.

mugua
  • 224
  • 1
  • 3
  • 11
1

You can just add @DateTimeFormat annotation to your parameter with the pattern that you're using

 @RequestMapping(value ="/test")
 public @ResponseBody Date test(@RequestParam("start")@DateTimeFormat(pattern="yyyyMMdd") Date start){
     System.out.println(start);
     return start;
  } 
reos
  • 8,766
  • 6
  • 28
  • 34