How to initialize @DateTimeFormat Parameter on Get?

590 views Asked by At

The problem is that the DateTime passed as a parameter on my Spring Rest Controller Request is not initialized correctly.

Controller:

@RequestMapping(value = "/events/{dateTimeStart}/{dateTimeEnd}", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Event>> getEventsWithinTime(@DateTimeFormat(iso=DateTimeFormat.ISO.DATE_TIME) DateTime dateTimeStart, @DateTimeFormat(iso=DateTimeFormat.ISO.DATE_TIME) DateTime dateTimeEnd)
{ 
  log.debug("Rest Request: Getting Timestamp Events from " + dateTimeStart + " and " + dateTimeEnd);
} 

Test:

    @Test
@Transactional
public void checkEventWithingDateTime() throws Exception {
    eventRepository.saveAndFlush(event);

    LocalDate nowDateTime = new LocalDate();

    DateTime midnightDateTime = new DateTime(nowDateTime.getYear(), nowDateTime.getMonthOfYear(),
        nowDateTime.getDayOfMonth(), 0,0);

    DateTime lastSecondDateTime = new DateTime(nowDateTime.getYear(), nowDateTime.getMonthOfYear(),
        nowDateTime.getDayOfMonth(), 23,59,59);


    System.out.println("Event Start Date: " + event.getStartDate());
    System.out.println("Looking between : " + midnightDateTime.toDateTimeISO() + " and " + lastSecondDateTime.toDateTimeISO());

    restEventMockMvc.perform(get("/api/events/{timestampStart}/{timestampEnd}", midnightDateTime.toDateTimeISO(), lastSecondDateTime.toDateTimeISO()))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath("$").isArray())
        .andExpect(jsonPath("$", hasSize(1)))
        ;


}

The Issue:

Event Start Date: 2015-06-09T15:19:01.935+02:00
Looking between : 2015-06-09T00:00:00.000+02:00 and 2015-06-09T23:59:59.000+02:00
[DEBUG] com.ent.event.web.rest.EventResource - Rest Request: Getting Timestamp Events from 2015-06-09T15:19:02.681+02:00 and 2015-06-09T15:19:02.681+02:00

The datetime passed is not initialized correctly, the date is ok, but the time is set to current and not the one given.

Thanks.

1

There are 1 answers

0
ema On

As I remember I faced with some problem of adding DateTimeFormat. Eventually I resolved situation through binder:

@InitBinder
public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");;
    dateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}