SpringMVC-日期格式化

页面提交的数据格式如果不正确,会报400

1. 使用注解,在日期字段上面添加注解:单个日期转换

@DateTimeFormat(pattern="yyyy-MM-dd HH:mm")
public class Member implements Serializable {
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birthday ;
public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }

2. 定义一个抽象父类,子类可以继承此父类:批量日期转换

public abstract class AbstractAction {
    private static final DateTimeFormatter LOCAL_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd") ;
    @InitBinder
    public void initBinder(WebDataBinder binder) {  // 通过此绑定设置处理转换
        binder.registerCustomEditor(java.util.Date.class,new PropertyEditorSupport(){
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                LocalDate localDate = LocalDate.parse(text,LOCAL_DATE_FORMAT) ; // 设置本地日期实例
                ZoneId zoneId = ZoneId.systemDefault() ;
                Instant instant = localDate.atStartOfDay().atZone(zoneId).toInstant() ;
                super.setValue(java.util.Date.from(instant)); // 字符串与日期转换
            }
        });
    }
}

 

posted @ 2019-06-24 01:25  SweetBaby。  阅读(743)  评论(0编辑  收藏  举报