I have an entity which has java.time.ZonedDateTime
property. I want to parse a string submitted from form in dd/MM/yyyy HH:mm
format to java.time.ZonedDateTime
.
I tried @DateTimeFormat(pattern = "dd/MM/yyyy HH:mm")
. But it works only LocalDate
with @DateTimeFormat(pattern = "dd/MM/yyyy")
format.
I also created a Converter
as below
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);
}
}
and overwriting webMvcConfiguration as below
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new ZonedDateTimeConverter(ZoneId.systemDefault()));
}
}
I'm not sure what is the right way to make it work. Using Spring Boot 1.5.6. Thymeleaf 3.0.7