How to globally configure `@DateTimeFormat` pattern in Spring Boot?

前端 未结 3 1973
渐次进展
渐次进展 2021-02-08 02:01

Im my Spring Boot application, I have some controllers that accept a date as query parameter:

@RestController
public class MyController {

  @GetMapping
  public         


        
3条回答
  •  鱼传尺愫
    2021-02-08 02:34

    This is currently not easily possible (e.g. by setting a simple configuration property), see #5523. The best solution I found so far is to register a Formatter. This will also work with optional parameters modeled as Optional:

      @Bean
      public Formatter localDateFormatter() {
        return new Formatter() {
          @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);
          }
        };
      }
    

    It may become possible to set this using a configuration property when my proposal in #9930 has been merged.

提交回复
热议问题