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 public class DateConverterConfig implements Converter<String, Date> { private static final List<String> formarts = new ArrayList<>(); 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 if (source.length() == 13) {//long 时间戳转换 returnparseDate (Source, formarts.get (. 3 )); } the else { the throw new new an IllegalArgumentException ( "Invalid Boolean value '" Source + + "'" ); } } / ** * Date format * * @param dateStr Character String date * @param the format String format * @return a date date * / public a date parseDate (dateStr String, String the format) { a date dATE = null ; // Long timestamp to IF ! (dateStr = null && dateStr.length() == 13) { long time = Long.parseLong(dateStr); date = new Date(time); } try { DateFormat dateFormat = new SimpleDateFormat(format); date = dateFormat.parse(dateStr); } catch (Exception e) { } return date; } }