【问题标题】:How to initialize @DateTimeFormat Parameter on Get?如何在 Get 上初始化 @DateTimeFormat 参数?
【发布时间】:2015-08-24 08:19:41
【问题描述】:

问题是我的 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

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

谢谢。

【问题讨论】:

    标签: java spring-mvc jodatime


    【解决方案1】:

    我记得我在添加 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));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-08
      • 2017-06-12
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      • 1970-01-01
      • 2022-10-06
      相关资源
      最近更新 更多