Given an endpoint with a LocalDate parameter :
public void doSth(@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate) {
...
}
I must set @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
everywhere I want to bind a LocalDate
. This code is boilerplate so I defined a custom editor :
webDataBinder.registerCustomEditor(LocalDate.class, new LocalDateEditor());
But it would be great if spring boot was able to do this natively with a date format in the properties file, and ISO as default.
DateTimeFormatterRegistrar
has some options setters that we might be able to surface as properties.
What are the pros/cons of using WebDataBinder#registerCustomEditor
vs FormatterRegistry#addConverter
+1, its painful to spam @DateTimeFormat
everywhere
This should also work by default in POJOs for GET request. It does work for POST.
Vote up for this enhancement. Actually I feel somewhat surprised that there is no global configuration to change the default @DateTimeFormat
.
What are the pros/cons of using
WebDataBinder#registerCustomEditor
vs.FormatterRegistry#addConverter
I only tried the WebDataBinder
approach. This had the problem, that Optional<LocalDate>
did no longer work for parameters with @RequestParam(required = false)
. It works when using @DateTimeFormat
.
I found a way to make it work even with Optional<LocalDate>
:
@Bean
public Formatter<LocalDate> localDateFormatter() {
return new Formatter<LocalDate>() {
@Override
public LocalDate parse(String text, Locale locale) throws ParseException {
return LocalDate.parse(text, DateTimeFormatter.ISO_DATE);
}
@Override
public String print(LocalDate object, Locale locale) {
return DateTimeFormatter.ISO_DATE.format(object);
}
};
}
I tried to generalize this using the spring.mvc.date-pattern
property and auto configuration in #9930.
I've blogged about this: https://blog.codecentric.de/en/2017/08/parsing-of-localdate-query-parameters-in-spring-boot/
I just tried to use this new feature with Spring Boot 2.0.1 and ran into parsing problems that I described in this Stack Overflow answer. Is this intended behaviour, have I been doing something wrong? My expectation was that yyyy-MM-dd
would work just fine.
@jo-ka I think you've identified a bug. Can you please open a new issue? I believe the key difference is the use of ResolverStyle.STRICT
when a custom format is specified. If no custom format is specified, the DataTimeFormatter
is created using java.time.format.DateTimeFormatter.ofLocalizedDate(FormatStyle)
which uses ResolverStyle.SMART
. I suspect that inconsistency is accidental and, with confirmation from @bclozel, should be corrected.
@wilkinsona Okay, I'll open a new issue , but only after @bclozel confirmed this, right?
Please open a new one now. If we have to close it because @bclozel disagrees with my analysis then that's better than it getting forgotten because it's only being tracked by this already-closed issue.
Most helpful comment
+1, its painful to spam
@DateTimeFormat
everywhere