方式1 Controller处理>
@InitBinder public void initBinder(WebDataBinder binder, WebRequest request) { //转换日期 DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd"); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器 }
方式2 全局处理>
package sy.ccpit.qiye.config; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.format.support.FormattingConversionService; import org.springframework.validation.Validator; import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * @Title: CustomDateConfig * @ProjectName qiye * @date 2019/12/1013:14 */ @Configuration public class CustomDateConfig{ @Bean public ConfigurableWebBindingInitializer configurableWebBindingInitializer(FormattingConversionService mvcConversionService, Validator mvcValidator) { ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer(); initializer.setConversionService(mvcConversionService); initializer.setValidator(mvcValidator); DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd"); //装配自定义属性编辑器 initializer.setPropertyEditorRegistrar(propertyEditorRegistry -> { propertyEditorRegistry.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); }); return initializer; } }