日期转换
- 今日写代码的时候,发现前端的日期格式字符串不能被后台接收。于是找出了下面这么个配置来统一处理日期格式的转换。
非BOOT方式xml配置:
import java.text.SimpleDateFormat;import java.util.Date;import org.springframework.beans.propertyeditors.CustomDateEditor;import org.springframework.web.bind.WebDataBinder;import org.springframework.web.bind.annotation.InitBinder;import org.springframework.web.bind.support.WebBindingInitializer;public class CustomDateFormat implements WebBindingInitializer { /** * form表单提交 Date类型数据绑定 * @param binder * @see [类、类#方法、类#成员] */ @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); }}
并在spingMVC配置文件进行配置
自定义DateConverterConfig重写convert方法
实现spring提供的Converter,重写里面的convert方法::
import lombok.extern.slf4j.Slf4j;import org.springframework.core.convert.converter.Converter;import org.springframework.stereotype.Component;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.List;@Component@Slf4jpublic class DateConverterConfig implements Converter{ private static final List FORMARTS = new ArrayList<>(4); static { FORMARTS.add("yyyy-MM"); FORMARTS.add("yyyy-MM-dd"); FORMARTS.add("yyyy-MM-dd HH:mm"); FORMARTS.add("yyyy-MM-dd HH:mm:ss"); } @Override public Date convert(String source) { String value = source.trim(); if ("".equals(value)) { return null; } if (source.matches("^\\d{4}-\\d{1,2}$")) { return parseDate(source, FORMARTS.get(0)); } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) { return parseDate(source, FORMARTS.get(1)); } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")) { return parseDate(source, FORMARTS.get(2)); } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) { return parseDate(source, FORMARTS.get(3)); } else { throw new IllegalArgumentException("Invalid boolean value '" + source + "'"); } } /** * 格式化日期 * * @param dateStr String 字符型日期 * @param format String 格式 * @return Date 日期 */ private Date parseDate(String dateStr, String format) { Date date = null; try { DateFormat dateFormat = new SimpleDateFormat(format); date = dateFormat.parse(dateStr); } catch (Exception e) { log.error("日期转换错误", e); } return date; }}
我这里是springboot项目通过@Component注解将这个类交给spring容器托管的,如果springmvc项目还需要到xml配置文件注册这个类
优点很明显了:足够灵活,在静态代码块里自定义任意格式日期,在重写的方法里在配上对应的正则表达式就行,也可以做到全局统一处理。后记
- 感谢这位博主的文章,若有侵权,请联系博主删除。