package com.sunxung.factoring.component.config;

import com.sunxung.factoring.component.util.StringUtil;
import org.springframework.core.convert.converter.Converter;

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

/**
 * @author <a href="mailto:122058102@qq.com">王庆之</a>
 * @version V1.0
 * @Description: 日期处理转换
 * @date 2016年8月30日 下午7:50:18
 */
public class StringToDateConverter implements Converter<String, Date> {
    private static final String dateFormat = "yyyy/MM/dd HH:mm:ss";
    private static final String shortDateFormat = "yyyy/MM/dd";

    @Override
    public Date convert(String source) {

        if (StringUtil.isEmpty(source)) {
            return null;
        }
        if (source.contains("T") && source.contains("Z")) {
            //UTC日期转换
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            TimeZone utcZone =TimeZone.getTimeZone("UTC");
            sdf.setTimeZone(utcZone);
            try {
                return sdf.parse(source);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            source = source.trim();
            source = source.contains("-") ? source.replaceAll("-", "/") : source;
            if (source.contains("/")) {
                String formatter = source.contains(":") ? dateFormat : shortDateFormat;
                try {
                    return new SimpleDateFormat(formatter).parse(source);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                throw new RuntimeException(String.format("解析 %s 转换成日期失败", source));
            }
        }
        return null;
    }
}
