package cn.freemud.utils;

import com.freemud.application.sdk.api.log.ErrorLog;
import org.apache.commons.lang.StringUtils;

import java.util.Calendar;
import java.util.Date;

public class DateUtils {

    /**
     * 对传入的时间翻译星期
     * @param date
     * @return
     */
    public static String getDayWeek(Date date){
        if (date == null ){
            return null;
        }
        String[] week={"(周日)","(周一)","(周二)","(周三)","(周四)","(周五)","(周六)"};
        Calendar calendar =Calendar.getInstance();
        calendar.setTime(date);
        int w = calendar.get(Calendar.DAY_OF_WEEK) -1 ;
        if (w < 0 ){
            w =0;
        }
        return week[w];
    }

    public static String convert2Date(String date){
        try {
            if(StringUtils.isBlank(date)){
                return null;
            }
            date = date.replace("年", "-");
            date = date.replace("月","-");
            date = date.replace("日"," ");
            date = date.replace("时",":");
            date = date + "00:00";
            return date;
        }catch (Exception e){
            ErrorLog.printErrorLog("时间转换报错，原始时间:{}", date, null,null);
            return null;
        }
    }

    public static int diffDay(Date before, Date after) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(before);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(after);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if(year1 != year2)   //同一年
        {
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++)
            {
                if(i%4==0 && i%100!=0 || i%400==0)    //闰年
                {
                    timeDistance += 366;
                }
                else    //不是闰年
                {
                    timeDistance += 365;
                }
            }

            return timeDistance + (day2-day1) ;
        }
        else    //不同年
        {
            return day2-day1;
        }
    }

}
