package com.farriver.bwf.common.utilities; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /* Converter是SpringMvc框架中的一个功能点,通过转化器可以实现对UI端传递的数据进行类型转化, 实现类型转化可以实现接口Converter接口、ConverterFactory接口、GenericConverter接口。 ConverterRegistry接口就是对这三种类型提供了对应的注册方法。 */ @Component public class DateConverter implements Converter { private final Logger logger = LoggerFactory.getLogger(DateConverter.class); private static ThreadLocal formats = new ThreadLocal() { protected SimpleDateFormat[] initialValue() { return new SimpleDateFormat[]{ new SimpleDateFormat("yyyy-MM"), new SimpleDateFormat("yyyy-MM-dd"), new SimpleDateFormat("yyyy-MM-dd HH"), new SimpleDateFormat("yyyy-MM-dd HH:mm"), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") }; } }; @Override public Date convert(String source) { if (source == null || source.trim().equals("")) { return null; } Date result = null; String originalValue = source.trim(); if (source.matches("^\\d{4}-\\d{1,2}$")) { return parseDate(source, formats.get()[0]); } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) { return parseDate(source, formats.get()[1]); } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}$")) { return parseDate(source, formats.get()[2]); } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")) { return parseDate(source, formats.get()[3]); } 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, formats.get()[4]); } else if (originalValue.matches("^\\d{1,13}$")) { try { long timeStamp = Long.parseLong(originalValue); if (originalValue.length() > 10) { result = new Date(timeStamp); } else { result = new Date(1000L * timeStamp); } } catch (Exception e) { result = null; } } else { result = null; } return result; } public Date parseDate(String dateStr, DateFormat dateFormat) { Date date = null; try { date = dateFormat.parse(dateStr); } catch (Exception e) { } return date; } }