SpringMvc字符串转LocalDate用正则表达式实现
SpringMvc实现前端字符串到后台LocalDate需要添加一个转换器
代码:
@Bean
public Converter<String,LocalDate> LocalDateConverter() {
return new Converter<String,LocalDate>() {
@Override
public LocalDate convert(String source) {
LocalDate date = null;
try{
source = source.replaceAll("^(\\d{4})(.)(\\d{1})(\\2)(\\d{1,2})$","$10$3$5").replaceAll("^(\\d{4})(.)(\\d{2})(\\2)(\\d{1,2})$","$1$3$5").replaceAll("^(\\d{6})(\\d{1})$","$10$2");
date = LocalDate.parse(source,DateTimeFormatter.BASIC_ISO_DATE);//yyyyMMdd
}catch(Exception e){
e.pringStackTrace();
}
return date;
}
};
}
假定任意分隔符为-
以上正则可以将yyyy-MM-dd、yyyy-M-dd、yyyy-MM-d、yyyy-M-d格式的字符串转换为yyyyMMdd格式,再进行LocalDate的转换。