此處定義的dateConvert用來轉換Date類型,如果是LocalDate、LocalDateTime類型,則將Date
類型換成相應的類型即可,注意java8的日期類型需要用Formatter格式化:
編寫一個這樣的類就可以了
/**
* 轉換解析器
* @author wangqingguo 2017/9/25
*/
@Configuration
public class MappingConverterAdapter {
/**
* 接收前端datetime參數
* @return
*/
@Bean
public Converter<String, LocalDateTime> LocalDateTimeConvert() {
return new Converter<String, LocalDateTime>() {
@Override
public LocalDateTime convert(String source) {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime date = null;
try {
date = LocalDateTime.parse((String) source,df);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
};
}
/**
* 返回LocalDateTime值(去掉LocalDateTime中的T)
*/
@org.springframework.beans.factory.annotation.Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
private String pattern;
@Bean
public LocalDateTimeSerializer localDateTimeDeserializer() {
return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
}
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
}
}