package cn.com.countrygarden.bi.main.util;

import org.apache.commons.lang.StringUtils;
import org.springframework.format.Formatter;

import java.text.*;
import java.util.Date;
import java.util.Locale;

/**
 * Created by chenweijiang on 2017/9/13.
 */
public class DateFormatter  implements Formatter<Date> {

    private final static long DAY = 1000 * 3600 * 24;

    public DateFormatter() {
        super();
    }

    public Date parse(final String text, final Locale locale) throws ParseException {
        if (StringUtils.isEmpty(text))
        {
            return null;
        }
        final SimpleDateFormat dateFormat;
        if (text.length() == 10)
        {
            dateFormat = createDateFormat("yyyy-MM-dd", locale);
        }
        else
        {
            dateFormat = createDateFormat("yyyy-MM-dd HH:mm", locale);
        }
        return dateFormat.parse(text);
    }

    public String print(final Date object, final Locale locale) {
        final SimpleDateFormat dateFormat;
        if (object.getTime() % DAY == 0)
        {
            dateFormat = createDateFormat("yyyy-MM-dd", locale);
        }
        else
        {
            dateFormat = createDateFormat("yyyy-MM-dd HH:mm", locale);
        }
        return dateFormat.format(object);
    }

    private SimpleDateFormat createDateFormat(String format, final Locale locale) {
        final SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        dateFormat.setLenient(false);
        return dateFormat;
    }

    public static void main (String[] args){

    }

}