问题:
- Field error in object 'saleOrderHeadCriteria' on field 'orderDatetime.greaterThanOrEqual': rejected value [2021-04-16]; codes [typeMismatch.saleOrderHeadCriteria.orderDatetime.greaterThanOrEqual,typeMismatch.orderDatetime.greaterThanOrEqual,typeMismatch.greaterThanOrEqual,typeMismatch.java.time.ZonedDateTime,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [saleOrderHeadCriteria.orderDatetime.greaterThanOrEqual,orderDatetime.greaterThanOrEqual]; arguments []; default message [orderDatetime.greaterThanOrEqual]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.time.ZonedDateTime' for property 'orderDatetime.greaterThanOrEqual'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.time.ZonedDateTime] for value '2021-04-16'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2021-04-16]]
解决:
- import org.apache.commons.lang.StringUtils;
- import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
- import org.springframework.core.convert.converter.Converter;
- import org.springframework.stereotype.Component;
- import java.time.LocalDate;
- import java.time.ZoneId;
- import java.time.ZonedDateTime;
- import java.time.format.DateTimeFormatter;
- /**
- * Description: 实现自己的转换器并通知Spring启动
- * Created by Hoscen on 2021/4/16 16:15 with IntelliJ IDEA.
- */
- @Component
- @ConfigurationPropertiesBinding
- public class ZonedDateTimeConverter implements Converter
{ - @Override
- public ZonedDateTime convert(String source) {
- try {
- if (StringUtils.isBlank(source)) {
- return null;
- }
- if (!source.contains(":")) {
- LocalDate ld = LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
- return ld.atStartOfDay(ZoneId.systemDefault());
- } else {
- try{
- LocalDateTime ld = LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
- return ld.atZone(ZoneId.systemDefault());
- }catch (Exception e){
- return ZonedDateTime.parse(source);
- }
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- return null;
- }
- }