StringToDateConverter.java 1.16 KB
Newer Older
liqin's avatar
liqin committed
1 2 3 4 5
package cn.wisenergy.chnmuseum.party.common.mvc;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

liqin's avatar
liqin committed
6 7 8
import java.text.SimpleDateFormat;
import java.util.Date;

liqin's avatar
liqin committed
9
public class StringToDateConverter implements Converter<String, Date> {
liqin's avatar
liqin committed
10

liqin's avatar
liqin committed
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
	private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
	private static final String shortDateFormat = "yyyy-MM-dd";

	/**
	 * @see Converter#convert(Object)
	 */
	@Override
	public Date convert(String source) {
		if (StringUtils.isBlank(source)) {
			return null;
		}
		source = source.trim();
		try {
			if (source.contains("-")) {
				SimpleDateFormat formatter;
				if (source.contains(":")) {
					formatter = new SimpleDateFormat(dateFormat);
				} else {
					formatter = new SimpleDateFormat(shortDateFormat);
				}
				Date dtDate = formatter.parse(source);
				return dtDate;
			} else if (source.matches("^\\d+$")) {
				Long lDate = new Long(source);
				return new Date(lDate);
			}
		} catch (Exception e) {
			throw new RuntimeException(String.format("parser %s to Date fail", source));
		}
		throw new RuntimeException(String.format("parser %s to Date fail", source));
	}

}