如何在Get上初始化@DateTimeFormat参数?

时间:2015-06-09 13:24:14

标签: java spring-mvc jodatime

问题是我的Spring Rest Controller Request上作为参数传递的DateTime没有正确初始化。

控制器

@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
@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)))
        ;


}

问题:

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

传递的日期时间未正确初始化,日期正常,但时间设置为当前而不是给定的时间。

感谢。

1 个答案:

答案 0 :(得分:0)

我记得我遇到过添加DateTimeFormat的一些问题。最终我通过活页夹解决了问题:

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