package xyz.wbsite.frame.excel.converter;

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

/**
 * DateConverter - Date转化器，重写了对象到String，String到对象的转化方式
 *
 * @author wangbing
 * @version 0.0.1
 * @since 2017-01-01
 */
public class DateConverter implements Converter<Date> {

    @Override
    public Date convert(String var) {
        if (var == null) {
            return null;
        }
        Date date = null;
        try {
            var = var.trim();
            if (var.matches("[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}")) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                return sdf.parse(var);
            } else if (var.matches("[0-9]{4}/[0-9]{1,2}/[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}")) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                return sdf.parse(var);
            } else if (var.matches("[0-9]{4}-[0-9]{1,2}-[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}")) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                date = sdf.parse(var);
            } else if (var.matches("[0-9]{4}年[0-9]{1,2}月[0-9]{1,2}日 [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}")) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                date = sdf.parse(var);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    @Override
    public String string(Date var) {
        if (var == null) {
            return "";
        }
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(var);
    }
}
