// 方法一
import org.springframework.core.convert.converter.Converter;
import java.time.LocalDateTime;
// 日期转换器
// 将 2022-10-14T19:59:24 格式转换成 LocalDateTime
public class DateConvertor implements Converter<String,LocalDateTime>{
@Override
public LocalDateTime convert(String source) {
return LocalDateTime.parse(source);
}
}
// 方法二
import org.springframework.core.convert.converter.Converter;
import java.time.LocalDate;
public class DateConvertor implements Converter<String, LocalDate> { //String, LocalDate (两个参数,一个入参类型,一个是返回参数类型)
// yyyy-mm-dd 转换成 localDateTime
@Override
public LocalDate convert(String source) {
final String[] split = source.split("//D+");
try {
int year = Integer.parseInt(split[0]);
int month = Integer.parseInt(split[1]);
int day = Integer.parseInt(split[2]);
return LocalDate.of(year, month, day);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
定义完日期消息转换器后,要在启动类上实现WebMvcConfig,且要在启动器上进行注册