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

前端 未结 3 866
深忆病人
深忆病人 2021-02-08 01:48

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:28

    @britter: thanks.

    spring.mvc.date-format= # Date format to use. For instance, dd/MM/yyyy works fine with Spring Boot 2.1.0.x

    See # SPRING MVC (WebMvcProperties) properties.

    UPDATE: But it doen't work for Spring Data Rest params ...

    0 讨论(0)
  • 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<LocalDate>. This will also work with optional parameters modeled as 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);
          }
        };
      }
    

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

    0 讨论(0)
  • 2021-02-08 02:42

    You can use spring.mvc.format.date, spring.mvc.format.time and spring.mvc.format.date-time

    For example:
    spring.mvc.format.time=HH:mm:ss
    spring.mvc.format.date=iso
    spring.mvc.format.date-time=iso-offset

    as in the example above, you can use shortcuts iso аnd iso-offset from spring boot 2.4.1

    0 讨论(0)
提交回复
热议问题