java – ZonedDateTime作为Spring REST RequestMapping中的PathV
我的
Spring应用程序中有一个REST端点,如下所示
@RequestMapping(value="/customer/device/startDate/{startDate}/endDate/{endDate}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) public Page<DeviceInfo> getDeviceListForCustomerBetweenDates(@PathVariable ZonedDateTime startDate,@PathVariable ZonedDateTime endDate,Pageable pageable) { ... code here ... } 我试过传递路径变量作为毫秒和秒.但是,我从两个方面得到以下异常: "Failed to convert value of type 'java.lang.String' to required type 'java.time.ZonedDateTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @org.springframework.web.bind.annotation.PathVariable java.time.ZonedDateTime for value '1446361200'; nested exception is java.time.format.DateTimeParseException: Text '1446361200' could not be parsed at index 10" 有人可以解释我如何传入(如秒或毫秒)字符串,如1446361200,并让它转换为ZonedDateTime? 或者是作为String传递然后自己进行转换的唯一方法?如果是这样,有一种通用的方法来处理具有类似设计的多种方法吗? 解决方法
ZonedDateTime参数有一个默认转换器.它使用Java 8的DateTimeFormatter创建的
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT); 就你而言,这可能是任何FormatStyle或任何DateTimeFormatter,你的例子不会有效. DateTimeFormatter解析并格式化为日期字符串,而不是时间戳,这是您提供的. 您可以为参数提供适当的自定义 public Page<DeviceInfo> getDeviceListForCustomerBetweenDates( @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) ZonedDateTime startDate,@PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) ZonedDateTime endDate,Pageable pageable) { ... 或者使用适当的
您将无法使用unix时间戳执行上述任何操作. The canonical way给ZonedDateTime转换的时间戳是通过 long startTime = 1446361200L; ZonedDateTime start = Instant.ofEpochSecond(startTime).atZone(ZoneId.systemDefault()); System.out.println(start); 要使其与@PathVariable一起使用,请注册一个自定义Converter.就像是 class ZonedDateTimeConverter implements Converter<String,ZonedDateTime> { private final ZoneId zoneId; public ZonedDateTimeConverter(ZoneId zoneId) { this.zoneId = zoneId; } @Override public ZonedDateTime convert(String source) { long startTime = Long.parseLong(source); return Instant.ofEpochSecond(startTime).atZone(zoneId); } } 并在 @Override protected void addFormatters(FormatterRegistry registry) { registry.addConverter(new ZonedDateTimeConverter(ZoneId.systemDefault())); } 现在,Spring MVC将使用此转换器将String路径段反序列化为ZonedDateTime对象. 在Spring Boot中,我认为你可以为相应的Converter声明一个@Bean,它会自动注册它,但是不要接受我的话. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |