package com.app.framework.core.support.filter;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.util.StringUtils;

/**
 * Spring MVC 时间转换
 */
public class DateConvertEditor extends PropertyEditorSupport {
	private SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	public void setAsText(String text) throws IllegalArgumentException {
		if (StringUtils.hasText(text)) {
			try {
				if (text.indexOf(":") > 0) {
					if(text.length() == 16){
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
						setValue(sdf.parse(text));
					}else if(text.length() == 19){
						setValue(this.datetimeFormat.parse(text));
					}else if(text.length() == 21){
						setValue(this.datetimeFormat.parse(text));
					}else{
						SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
						setValue(sdf.parse(text));
					}
				}  else if (text.indexOf("-") > 0) {
					if(text.length() == 7){
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
						setValue(sdf.parse(text));
					}else if(text.length() == 10){
						setValue(this.dateFormat.parse(text));
					}else{
						setValue(null);
					}
				} else {
					Long time = Long.parseLong(text);
					setValue(datetimeFormat.parse(datetimeFormat.format(new Date(time))));
				}
			} catch (ParseException ex) {
				IllegalArgumentException iae = new IllegalArgumentException("Could not parse date: " + ex.getMessage());
				iae.initCause(ex);
				throw iae;
			}
		} else {
			setValue(null);
		}
	}
}

