场景

在Controller层的接口中,若存在Date等时间类型参数,而前端传递时间为String类型,所以需要一个参数类型转换器。SpringMVC默认的时间转换类型不能支持所有的需求,所以需要自定义。 这里提供三种实现方法:

@DateTimeFormat注解

@RequestParam(value = "beginTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date beginTime,
@RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime,

@InitBinder注解

自定义属性编辑器(PropertyEditor) 原理:PropertyEditor 是 Java 中用于在不同数据类型之间进行转换的机制。在 Spring 中,可以通过自定义 PropertyEditor 来实现日期字符串到 Date 类型的转换。

public class CustomDateEditor extends PropertyEditorSupport {
    private SimpleDateFormat dateFormat;
    public CustomDateEditor(String format) {
        dateFormat = new SimpleDateFormat(format);
    }
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        try {
            Date date = dateFormat.parse(text);
            setValue(date);
        } catch (Exception e) {
            throw new IllegalArgumentException("日期格式错误");
        }
    }
}
@RestController
public class YourController {
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor("yyyy - MM - dd HH:mm:ss"));
    }
    // 其他控制器方法
}

Converter<S,T>接口

实现 Converter 接口 原理:Spring 提供了Converter<S, T>接口,用于将一种类型S转换为另一种类型T。可以通过实现这个接口来创建自定义的日期字符串到 Date 类型的转换器。

public class StringToDateConverter implements Converter<String, Date> {
    private SimpleDateFormat dateFormat;
    public StringToDateConverter(String format) {
        dateFormat = new SimpleDateFormat(format);
    }
    @Override
    public Date convert(String source) {
        try {
            return dateFormat.parse(source);
        } catch (Exception e) {
            throw new IllegalArgumentException("日期格式错误");
        }
    }
}

注册转换器

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToDateConverter("yyyy-MM-dd HH:mm:ss"));
    }
}