gpt4 book ai didi

java - ZonedDateTime 作为 Spring REST RequestMapping 中的 PathVariable

转载 作者:IT老高 更新时间:2023-10-28 13:45:56 25 4
gpt4 key购买 nike

我的 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?

或者是作为字符串传递然后自己进行转换的唯一方法?如果是这样,是否有一种通用方法可以为具有相似设计的多种方法处理此问题?

最佳答案

ZonedDateTime 参数有一个默认转换器。它使用 Java 8 的 DateTimeFormatter 创建像

DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);

就您而言,这可能是任何 FormatStyle 或真正的任何 DateTimeFormatter,您的示例将不起作用。 DateTimeFormatter 解析并格式化为日期字符串,而不是您提供的时间戳。

您可以提供适当的自定义 @org.springframework.format.annotation.DateTimeFormat到您的参数,例如

public Page<DeviceInfo> getDeviceListForCustomerBetweenDates(
@PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) ZonedDateTime startDate,
@PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) ZonedDateTime endDate,
Pageable pageable) { ...

或使用适当的 pattern和相应的日期字符串,如

2000-10-31T01:30:00.000-05:00

您将无法使用 unix 时间戳执行上述任何操作。 The canonical way做时间戳到ZonedDateTime的转换是通过Instant#ofEpochSecond(long) ,给定一个适当的 ZoneId

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

并将其注册到 WebMvcConfigurationSupport @Configuration 注释类,覆盖 addFormatters

@Override
protected void addFormatters(FormatterRegistry registry) {
registry.addConverter(new ZonedDateTimeConverter(ZoneId.systemDefault()));
}

现在,Spring MVC 将使用此转换器将 String 路径段反序列化为 ZonedDateTime 对象。


在 Spring Boot 中,我认为您可以为相应的 Converter 声明一个 @Bean 并且它会自动注册它,但不要相信我的话.

关于java - ZonedDateTime 作为 Spring REST RequestMapping 中的 PathVariable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34398387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com