我有一个拥有java.time.ZonedDateTime
财产的实体。我想将dd/MM/yyyy HH:mm
格式从表单提交的字符串解析为java.time.ZonedDateTime
.
我试过了@DateTimeFormat(pattern = "dd/MM/yyyy HH:mm")
。但它只适用LocalDate
于@DateTimeFormat(pattern = "dd/MM/yyyy")
格式。
我还创建了一个Converter
如下
public class ZonedDateTimeConverter implements Converter<String, ZonedDateTime> {
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
private final ZoneId zoneId;
public ZonedDateTimeConverter(ZoneId zoneId) {
this.zoneId = zoneId;
}
@Override
public ZonedDateTime convert(String source) {
LOG.info("Parsing string {} to ZonedDateTime: {}", source, ZonedDateTime.parse(source, DATE_TIME_FORMATTER));
return ZonedDateTime.parse(source, DATE_TIME_FORMATTER);
}
}
并覆盖 webMvcConfiguration 如下
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new ZonedDateTimeConverter(ZoneId.systemDefault()));
}
}
我不确定使它起作用的正确方法是什么。使用 Spring Boot 1.5.6。百里香叶 3.0.7