为什么使用DateTimeFormat我无法转换属性错误

时间:2019-03-20 23:54:24

标签: java spring spring-boot

我正在尝试以dd / MM / yyyy格式绑定日期,我尝试了很多类似的事情:

初始化活页夹

@InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");   
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, null,  new CustomDateEditor(dateFormat, true));
    }

DateTimeFormat批注

@DateTimeFormat(pattern = "dd/MM/yyyy")
@Temporal(TemporalType.DATE)
private Date fecha;

配置类

@Configuration
public class DateTimeConfig {

    @Bean
    public FormattingConversionService conversionService() {
        DefaultFormattingConversionService conversionService = 
          new DefaultFormattingConversionService(false);

        DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
        registrar.setDateFormatter(DateTimeFormatter.ofPattern("dd-MM-yyyy"));        
        registrar.registerFormatters(conversionService);

        // other desired formatters

        return conversionService;
    }
}

但以上方法均无效,我总是会收到此错误:

Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'fecha'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.format.annotation.DateTimeFormat @javax.persistence.Temporal java.util.Date] for value '2018-10-09'; nested exception is java.lang.IllegalArgumentException: Invalid format: "2018-10-09" is malformed at "18-10-09"]

实际上我的模型是:

@DateTimeFormat(pattern = "dd/MM/yyyy")
@Temporal(TemporalType.DATE)
private Date fecha;

<input name="fecha" type="date" th:value="*{fecha}" class="form-control" />

1 个答案:

答案 0 :(得分:1)

问题在于,Spring仅在@DateTimeFormat标记中接受yyyy-MM-dd格式的日期,而您应该使用新的Java时间类LocalDate。

实体

@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate fecha;

胸腺

<input name="fecha" type="date" th:value="*{fecha}" class="form-control" />

输入可以以任何格式显示,在我的情况下,我以dd / MM / yyyy格式显示日期,然后Spring会自动将其转换为yyyy-MM-dd