package com.house365.tags;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.tags.RequestContextAwareTag;

/**
 * @author duhui
 */
public class DateFormatTag extends RequestContextAwareTag {

    /**
	 * 
	 */
    private static final long serialVersionUID = -7894927768684836538L;

    private Object date;

    public void setDate(Object date) {
        this.date = date;
    }

    @Override
    protected int doStartTagInternal() throws IOException {
        pageContext.getOut().write(this.getFormatDate(date));
        return 0;
    }

    public String getFormatDate(Object date) {
        if (date == null) {
            return "";
        } else if (StringUtils.isBlank(date.toString())) {
            return "";
        } else {
            if (date instanceof Date) {
                Date newDate = (Date) date;
                newDate.parse(date.toString());
                SimpleDateFormat sdf = new SimpleDateFormat(
                        "yyyy-MM-dd HH:mm:ss");
                return sdf.format(newDate);
            } else if (date instanceof String) {
                SimpleDateFormat sdf = new SimpleDateFormat(
                        "yyyy-MM-dd HH:mm:ss");
                Date newDate = null;
                try {
                    newDate = sdf.parse(date.toString());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return sdf.format(newDate);
            }
            return "";
        }
    }
}
