9

Following is a request fullcalendar js send to the server.

http://localhost:8080/NVB/rest/calendar/events?start=1425168000&end=1428796800 400

How to specify Date pattern (@DateTimeFormat) in Spring Request Param to convert this time to a Date object. I tried different patterns but getting 405 Bad Request.

@RequestMapping(value = "/events", method = RequestMethod.GET)
public @ResponseBody List<EventDto> addOrder(@RequestParam(value = "start") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date start,
                                             @RequestParam(value = "end") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)   Date end) {
    LOGGER.info("Requesting event from [{}] to [{}]", start, end);
    return new LinkedList<EventDto>();
}
Susitha Ravinda Senarath
  • 1,648
  • 2
  • 27
  • 49
  • You can pass start as String and implement the converter in EventDao.setStart, take a look https://stackoverflow.com/questions/45989158/spring-boot-requestparam-unix-timestamp-to-localdatetime/45990098#45990098 hope it helps – whoopdedoo Aug 31 '17 at 21:38

2 Answers2

3

Since timestamps aren't a formatted date (going by Java's SimpleDateFormat options), but more a numeric value: I would recommend making a custom data-binder for Date objects if you're doing this more often than this single instance. See http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#portlet-ann-webdatabinder

As a one-off solution you can bind them to Long parameters and create your own Date object with new Date(start).

Kafkaesque
  • 1,233
  • 9
  • 13
3

Using @InitBinder and WebDataBinder:

@RestController
public class SimpleController {

    //... your handlers here...

    @InitBinder
    public void initBinder(final WebDataBinder webdataBinder) {
        webdataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(new Date(Long.valueOf(text)));
            }
        });
    }
}
tchudyk
  • 564
  • 4
  • 14
  • Took me hours to find this answer, thanks man! I suspected Jackson being the problem and the frustration from pointless after pointless config attempt really unnerved me. Seems Jackson does't handle request params at all, does anyone know the reason, why request params are handled differently than json types? – godsim Nov 02 '20 at 10:51