1、使用注解@DateTimeFormat
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime localDateTime;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate localDate;
@DateTimeFormat(pattern = "HH:mm:ss")
private LocalTime localTime;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date date;
注解形式不能支持application/json传参请求
2、使用InitBinder
@RestControllerAdvice
public class BaseController {
@InitBinder
public void binder(WebDataBinder dataBinder) {
dataBinder.registerCustomEditor(LocalDateTime.class, new LocalDateTimeConvertEditor());
dataBinder.registerCustomEditor(LocalDate.class, new LocalDateConvertEditor());
dataBinder.registerCustomEditor(Date.class, new DateConvertEditor());
}
}
需要自己实现转换器,继承PropertyEditorSupport ,复写其setAsText方法
public class LocalDateTimeConvertEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
LocalDateTime dateTime = LocalDateTime.parse(text, Constant.DATE_TIME_FORMATTER);
setValue(dateTime);
}
}
使用数据绑定的形式,同样也不支持application/json的传参请求
3、使用自定义全局转换器
@Configuration
public class DateWebConfig {
@Bean
public Converter<String, LocalDate> localDateConverter() {
return new Converter<String, LocalDate>() {
@Override
public LocalDate convert(String s) {
return LocalDate.parse(s, Constant.DATE_FORMATTER);
}
};
}
@Bean
public Converter<String, LocalDateTime> localDateTimeConverter() {
return new Converter<String, LocalDateTime>() {
@Override
public LocalDateTime convert(String s) {
return LocalDateTime.parse(s, Constant.DATE_TIME_FORMATTER);
}
};
}
@Bean
public Converter<String, Date> dateConverter() {
return new Converter<String, Date>() {
@Override
public Date convert(String s) {
SimpleDateFormat sdf = new SimpleDateFormat(Constant.DATE_TIME_PATTERN);
Date date;
try {
date = sdf.parse(s);
} catch (ParseException e) {
throw new IllegalArgumentException("日期格式错误", e);
}
return date;
}
};
}
}
注意:实现Converter接口不要使用Lambda表达式,否则启动会报错。
同样不支持application/json传参请求
4、自定义日期序列化反序列化json
public final static DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern(Constant.DATE_TIME_PATTERN);
@Bean
public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomizer() {
return m -> {
m.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(Constant.DATE_TIME_FORMATTER));
m.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(Constant.DATE_TIME_FORMATTER));
m.simpleDateFormat("yyyy-MM-dd HH:mm:ss");
};
}
默认jackson对java8日期的转换格式是yyyy-MM-ddTHH:mm:ss,需要自己定义日期转换格式