package com.gingersoft.gsa.cloud.common.utils.time;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.util.Log;

import com.gingersoft.gsa.cloud.common.utils.log.LogUtil;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

import timber.log.Timber;

/**
 * @ClassName: TimeUtils
 * @Description: TODO(时间工具类)
 */
public class TimeUtils {
    /**
     * SimpleDateFormat.format把date转成String
     * SimpleDateFormat.parse把String转成date。
     * <p>
     * SimpleDateFormat.parse的时候，经常会有ParseException原因是输入的字符串格式跟SimpleDateFormat定义的格式不一致。
     * 这时候，可以先通过SimpleDateFormat.format把参数转成符合格式的字符串，然后再调用SimpleDateFormat.parse
     * <p>
     * G 年代标志符
     * y 年
     * M 月
     * d 日
     * h 时 在上午或下午 (1~12)
     * H 时 在一天中 (0~23)
     * m 分
     * s 秒
     * S 毫秒
     * E 星期
     * D 一年中的第几天
     * F 一月中第几个星期几
     * w 一年中第几个星期
     * W 一月中第几个星期
     * a 上午 / 下午 标记符
     * k 时 在一天中 (1~24)
     * K 时 在上午或下午 (0~11)
     * z 时区
     * <p>
     * yyyy : 代表年(不去区分大小写) 假设年份为 2017
     * <p>
     * "y" , "yyy" , "yyyy" 匹配的都是4位完整的年 如 : "2017"
     * "yy" 匹配的是年分的后两位 如 : "15"
     * 超过4位,会在年份前面加"0"补位 如 "YYYYY"对应"02017"
     * <p>
     * MM : 代表月(只能使用大写) 假设月份为 9
     * "M" 对应 "9"
     * "MM" 对应 "09"
     * "MMM" 对应 "Sep"
     * "MMMM" 对应 "Sep"
     * 超出3位,仍然对应 "September"
     * <p>
     * dd : 代表日(只能使用小写) 假设为13号
     * "d" , "dd" 都对应 "13"
     * 超出2位,会在数字前面加"0"补位. 例如 "dddd" 对应 "0013"
     * <p>
     * hh : 代表时(区分大小写,大写为24进制计时,小写为12进制计时) 假设为15时
     * "H" , "HH" 都对应 "15" , 超出2位,会在数字前面加"0"补位. 例如 "HHHH" 对应 "0015"
     * "h" 对应 "3"
     * "hh" 对应 "03" , 超出2位,会在数字前面加"0"补位. 例如 "hhhh" 对应 "0003"
     * <p>
     * mm : 代表分(只能使用小写) 假设为32分
     * "m" , "mm" 都对应 "32" ,  超出2位,会在数字前面加"0"补位. 例如 "mmmm" 对应 "0032"
     * <p>
     * ss : 代表秒(只能使用小写) 假设为15秒
     * "s" , "ss" 都对应 "15" , 超出2位,会在数字前面加"0"补位. 例如 "ssss" 对应 "0015"
     * <p>
     * E : 代表星期(只能使用大写) 假设为 Sunday
     * "E" , "EE" , "EEE" 都对应 "Sun"
     * "EEEE" 对应 "Sunday" , 超出4位 , 仍然对应 "Sunday"
     * <p>
     * a : 代表上午还是下午,如果是上午就对应 "AM" , 如果是下午就对应 "PM"
     */
    public static final SimpleDateFormat ENGLISH_DATE_FORMAT = new SimpleDateFormat("MMM d, yyyy K:m:s a", Locale.ENGLISH);
    public static final SimpleDateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//, Locale.CHINESE
    public static final SimpleDateFormat DEFAULT_DATE_FORMAT_YMDHM = new SimpleDateFormat("yyyy-MM-dd HH:mm");//, Locale.CHINESE

    public static final SimpleDateFormat DATE_FORMAT_DATE = new SimpleDateFormat("yyyy-MM-dd");
    public static final SimpleDateFormat DATE_FORMAT_DATE_HM = new SimpleDateFormat("HH:mm");
    public static final SimpleDateFormat DATE_FORMAT_DATE_H = new SimpleDateFormat("HH");

    public static final SimpleDateFormat DATE_FORMAT_HMS = new SimpleDateFormat("HH:mm:ss");

    public static final SimpleDateFormat DEFAULT_DATE_MDHM = new SimpleDateFormat("MM-dd HH:mm");//, Locale.CHINESE
    public static final SimpleDateFormat DEFAULT_DATE_MD = new SimpleDateFormat("MM-dd");
    public static final SimpleDateFormat DEFAULT_DATE_Y = new SimpleDateFormat("yyyy-");
    public static final SimpleDateFormat DATE_FORMAT_YMDE = new SimpleDateFormat("yyyy/MM/dd E");

    /**
     * one day millisecond count
     */
    public static final long ONE_DAY_MILLISECONDS = 1000 * 3600 * 24;

    public static final long ONE_HOUR_MILLISECONDS = 1000 * 3600;

    public static final long ONE_MIN_MILLISECONDS = 1000 * 60;

    /**
     * 时间戳转特定格式时间
     *
     * @param format
     * @param timeStamp
     * @return
     */
    public static String StampToData(SimpleDateFormat format, long timeStamp) {
        return format.format(new Date(timeStamp));
    }

    /***
     * 将字符串转为时间戳
     * @param time
     * @param format
     * @return
     */
    public static String getTimeToStamp(String time, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
        Date date = new Date();
        try {
            date = sdf.parse(time);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String tmptime = String.valueOf(date.getTime()).substring(0, 10);
        return tmptime;
    }

    /***
     * 将字符串转为时间戳
     * @param time
     * @param format
     * @return Integer
     */
    public static long getTimeToStamp2(String time, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
        Date date = new Date();
        try {
            date = sdf.parse(time);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String tmptime = String.valueOf(date.getTime()).substring(0, 10);
        return Long.parseLong(tmptime);
    }

    public static long getTimeToStamp3(String time, String format) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = simpleDateFormat.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long ts = date.getTime();
        return Long.parseLong(String.valueOf(ts));
    }

    /**
     * 将毫秒转换成秒
     *
     * @param time
     * @return
     */
    public static int convertToSecond(Long time) {
        Date date = new Date();
        date.setTime(time);
        return date.getSeconds();
    }


    /**
     * 描述：String类型的日期时间转化为Date类型.
     *
     * @param strDate String形式的日期时间
     * @param format  格式化字符串，如："yyyy-MM-dd HH:mm:ss"
     * @return Date Date类型日期时间
     */
    public static Date getDateByFormat(String strDate, SimpleDateFormat format) {
        Date date = null;
        try {
            date = format.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 描述：获取偏移之后的Date.
     *
     * @param date          日期时间
     * @param calendarField Calendar属性，对应offset的值， 如(Calendar.DATE,表示+offset天,Calendar.HOUR_OF_DAY,表示＋offset小时)
     * @param offset        偏移(值大于0,表示+,值小于0,表示－)
     * @return Date 偏移之后的日期时间
     */
    public Date getDateByOffset(Date date, int calendarField, int offset) {
        Calendar c = new GregorianCalendar();
        try {
            c.setTime(date);
            c.add(calendarField, offset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return c.getTime();
    }

    /**
     * 描述：获取指定日期时间的字符串(可偏移).
     *
     * @param strDate       String形式的日期时间
     * @param format        格式化字符串，如："yyyy-MM-dd HH:mm:ss"
     * @param calendarField Calendar属性，对应offset的值， 如(Calendar.DATE,表示+offset天,Calendar.HOUR_OF_DAY,表示＋offset小时)
     * @param offset        偏移(值大于0,表示+,值小于0,表示－)
     * @return String String类型的日期时间
     */
    public static String getStringByOffset(String strDate, String format, int calendarField, int offset) {
        String mDateTime = null;
        try {
            Calendar c = new GregorianCalendar();
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            c.setTime(mSimpleDateFormat.parse(strDate));
            c.add(calendarField, offset);
            mDateTime = mSimpleDateFormat.format(c.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return mDateTime;
    }

    /**
     * 描述：Date类型转化为String类型(可偏移).
     *
     * @param date          the date
     * @param format        the format
     * @param calendarField the calendar field
     * @param offset        the offset
     * @return String String类型日期时间
     */
    public static String getStringByOffset(Date date, String format, int calendarField, int offset) {
        String strDate = null;
        try {
            Calendar c = new GregorianCalendar();
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            c.setTime(date);
            c.add(calendarField, offset);
            strDate = mSimpleDateFormat.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strDate;
    }

    /**
     * 描述：Date类型转化为String类型.
     *
     * @param date   the date
     * @param format the format
     * @return String String类型日期时间
     */
    public static String getStringByFormat(Date date, SimpleDateFormat format) {
        String strDate = null;
        try {
            strDate = format.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strDate;
    }

    /**
     * 描述：获取指定日期时间的字符串,用于导出想要的格式.
     *
     * @param strDate String形式的日期时间，必须为yyyy-MM-dd HH:mm:ss格式
     * @param format  输出格式化字符串，如："yyyy-MM-dd HH:mm:ss"
     * @return String 转换后的String类型的日期时间
     */
    public static String getStringByFormat(String strDate, String format) {
        String mDateTime = null;
        try {
            Calendar c = new GregorianCalendar();
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            c.setTime(mSimpleDateFormat.parse(strDate));
            SimpleDateFormat mSimpleDateFormat2 = new SimpleDateFormat(format);
            mDateTime = mSimpleDateFormat2.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mDateTime;
    }

    /**
     * 描述：获取表示当前日期时间的字符串.
     *
     * @param format 格式化字符串，如："yyyy-MM-dd HH:mm:ss"
     * @return String String类型的当前日期时间
     */
    public static String getCurrentDate(SimpleDateFormat format) {
        String curDateTime = null;
        try {
            Calendar c = new GregorianCalendar();
            curDateTime = format.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curDateTime;
    }

    //获取当前系统当天日期
    public static String getCurrentDay() {
        String curDateTime = null;
        try {
            Calendar c = new GregorianCalendar();
            c.add(Calendar.DAY_OF_MONTH, 0);
            curDateTime = DEFAULT_DATE_FORMAT_YMDHM.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curDateTime;
    }

    //获取当前系统当天日期
    public static String getCurrentDay2() {
        String curDateTime = null;
        try {
            Calendar c = new GregorianCalendar();
            c.add(Calendar.DAY_OF_MONTH, 0);
            curDateTime = DEFAULT_DATE_FORMAT.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curDateTime;
    }

    //获取当前系统前后第几天
    public static String getNextDay(int i) {
        String curDateTime = null;
        try {
            Calendar c = new GregorianCalendar();
            c.add(Calendar.DAY_OF_MONTH, i);
            curDateTime = DEFAULT_DATE_FORMAT_YMDHM.format(c.getTime());
            c.getTimeInMillis();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curDateTime;
    }

    //获取当前系统前后第几天
    public static long getNextDayLong(int i) {
        long curDateTime = 0;
        try {
            Calendar c = new GregorianCalendar();
            c.add(Calendar.DAY_OF_MONTH, i);
            return c.getTimeInMillis();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curDateTime;
    }

    //获取当前系统前后第几小时
    public static String getNextHour(int i) {
        String curDateTime = null;
        try {
            Calendar c = new GregorianCalendar();
            c.add(Calendar.HOUR_OF_DAY, i);
            curDateTime = DEFAULT_DATE_FORMAT_YMDHM.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curDateTime;
    }

    /**
     * 描述：获取表示当前日期时间的字符串(可偏移).
     *
     * @param format        格式化字符串，如："yyyy-MM-dd HH:mm:ss"
     * @param calendarField Calendar属性，对应offset的值， 如(Calendar.DATE,表示+offset天,Calendar.HOUR_OF_DAY,表示＋offset小时)
     * @param offset        偏移(值大于0,表示+,值小于0,表示－)
     * @return String String类型的日期时间
     */
    public static String getCurrentDateByOffset(String format, int calendarField, int offset) {
        String mDateTime = null;
        try {
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            Calendar c = new GregorianCalendar();
            c.add(calendarField, offset);
            mDateTime = mSimpleDateFormat.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mDateTime;

    }

    /**
     * 描述：计算两个日期所差的天数.
     *
     * @param date1 第一个时间的毫秒表示
     * @param date2 第二个时间的毫秒表示
     * @return int 所差的天数
     */
    public static int getOffectDay(long date1, long date2) {
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTimeInMillis(date1);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTimeInMillis(date2);
        //先判断是否同年
        int y1 = calendar1.get(Calendar.YEAR);
        int y2 = calendar2.get(Calendar.YEAR);
        int d1 = calendar1.get(Calendar.DAY_OF_YEAR);
        int d2 = calendar2.get(Calendar.DAY_OF_YEAR);
        int maxDays = 0;
        int day = 0;
        if (y1 - y2 > 0) {
            maxDays = calendar2.getActualMaximum(Calendar.DAY_OF_YEAR);
            day = d1 - d2 + maxDays;
        } else if (y1 - y2 < 0) {
            maxDays = calendar1.getActualMaximum(Calendar.DAY_OF_YEAR);
            day = d1 - d2 - maxDays;
        } else {
            day = d1 - d2;
        }
        return day;
    }

    /**
     * 描述：计算两个日期所差的小时数.
     *
     * @param date1 第一个时间的毫秒表示
     * @param date2 第二个时间的毫秒表示
     * @return int 所差的小时数
     */
    public static int getOffectHour(long date1, long date2) {
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTimeInMillis(date1);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTimeInMillis(date2);
        int h1 = calendar1.get(Calendar.HOUR_OF_DAY);
        int h2 = calendar2.get(Calendar.HOUR_OF_DAY);
        int h = 0;
        int day = getOffectDay(date1, date2);
        h = h1 - h2 + day * 24;
        return h;
    }

    /**
     * 描述：计算两个日期所差的分钟数.
     *
     * @param date1 第一个时间的毫秒表示
     * @param date2 第二个时间的毫秒表示
     * @return int 所差的分钟数
     */
    public static int getOffectMinutes(long date1, long date2) {
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTimeInMillis(date1);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTimeInMillis(date2);
        int m1 = calendar1.get(Calendar.MINUTE);
        int m2 = calendar2.get(Calendar.MINUTE);
        int h = getOffectHour(date1, date2);
        int m = 0;
        m = m1 - m2 + h * 60;
        return m;
    }

    /**
     * 两个时间相差距离多少天多少小时多少分多少秒
     *
     * @param str1 时间参数 1 格式：1990-01-01 12:00:00
     * @param str2 时间参数 2 格式：2009-01-01 12:00:00
     * @return long[] 返回值为：{天, 时, 分, 秒}
     */
    public static long[] getDistanceTimes(String str1, String str2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date one;
        Date two;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff;
            if (time1 < time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long[] times = {day, hour, min, sec};
        return times;
    }

    public static long[] getDistanceTimes2(String str1, String str2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date one;
        Date two;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff;
            if (time1 < time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        } catch (ParseException e) {
            e.printStackTrace();
        }
//        if (day != 0) {
//            hour += day * 24;
//        }
//        if (hour != 0) {
//            min += hour * 60;
//        }
        long[] times = {day, hour, min};
        return times;
    }

    /**
     * 描述：获取本周一.
     *
     * @param format the format
     * @return String String类型日期时间
     */
    public static String getFirstDayOfWeek(String format) {
        return getDayOfWeek(format, Calendar.MONDAY);
    }

    /**
     * 描述：获取本周日.
     *
     * @param format the format
     * @return String String类型日期时间
     */
    public static String getLastDayOfWeek(String format) {
        return getDayOfWeek(format, Calendar.SUNDAY);
    }

    /**
     * 描述：获取本周的某一天.
     *
     * @param format        the format
     * @param calendarField the calendar field
     * @return String String类型日期时间
     */
    private static String getDayOfWeek(String format, int calendarField) {
        String strDate = null;
        try {
            Calendar c = new GregorianCalendar();
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            int week = c.get(Calendar.DAY_OF_WEEK);
            if (week == calendarField) {
                strDate = mSimpleDateFormat.format(c.getTime());
            } else {
                int offectDay = calendarField - week;
                if (calendarField == Calendar.SUNDAY) {
                    offectDay = 7 - Math.abs(offectDay);
                }
                c.add(Calendar.DATE, offectDay);
                strDate = mSimpleDateFormat.format(c.getTime());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strDate;
    }

    /**
     * 描述：获取本月第一天.
     *
     * @param format the format
     * @return String String类型日期时间
     */
    public static String getFirstDayOfMonth(SimpleDateFormat format) {
        String strDate = null;
        try {
            Calendar c = new GregorianCalendar();
            //当前月的第一天
            c.set(GregorianCalendar.DAY_OF_MONTH, 1);
            strDate = format.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strDate;
    }

    /**
     * 描述：获取本月最后一天.
     *
     * @param format the format
     * @return String String类型日期时间
     */
    public static String getLastDayOfMonth(String format) {
        String strDate = null;
        try {
            Calendar c = new GregorianCalendar();
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            // 当前月的最后一天
            c.set(Calendar.DATE, 1);
            c.roll(Calendar.DATE, -1);
            strDate = mSimpleDateFormat.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strDate;
    }


    /**
     * 描述：获取表示当前日期的0点时间毫秒数.
     *
     * @return the first time of day
     */
    public static long getFirstTimeOfDay() {
        Date date = null;
        try {
            String currentDate = getCurrentDate(DATE_FORMAT_DATE);
            date = getDateByFormat(currentDate + " 00:00:00", DEFAULT_DATE_FORMAT);
            return date.getTime();
        } catch (Exception e) {
        }
        return -1;
    }

    /**
     * 描述：获取表示当前日期24点时间毫秒数.
     *
     * @return the last time of day
     */
    public static long getLastTimeOfDay() {
        Date date = null;
        try {
            String currentDate = getCurrentDate(DATE_FORMAT_DATE);
            date = getDateByFormat(currentDate + " 24:00:00", DEFAULT_DATE_FORMAT);
            return date.getTime();
        } catch (Exception e) {
        }
        return -1;
    }

    /**
     * 描述：判断是否是闰年()
     * <p>(year能被4整除 并且 不能被100整除) 或者 year能被400整除,则该年为闰年.
     *
     * @param year 年代（如2012）
     * @return boolean 是否为闰年
     */
    public static boolean isLeapYear(int year) {
        if ((year % 4 == 0 && year % 400 != 0) || year % 400 == 0) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 取指定日期为星期几
     *
     * @param strDate  指定日期
     * @param inFormat 指定日期格式
     * @return String   星期几
     */
    public static String getWeekNumber(String strDate, String inFormat) {
        String week = "星期日";
        Calendar calendar = new GregorianCalendar();
        DateFormat df = new SimpleDateFormat(inFormat);
        try {
            calendar.setTime(df.parse(strDate));
        } catch (Exception e) {
            return "錯誤";
        }
        int intTemp = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        switch (intTemp) {
            case 0:
                week = "星期日日";
                break;
            case 1:
                week = "星期一";
                break;
            case 2:
                week = "星期二";
                break;
            case 3:
                week = "星期三";
                break;
            case 4:
                week = "星期四";
                break;
            case 5:
                week = "星期五";
                break;
            case 6:
                week = "星期六";
                break;
        }
        return week;
    }

    /**
     * 将字符串转位日期类型
     *
     * @param sdate
     * @return
     */
    private static Date toDate(String sdate) {
        try {
            return DEFAULT_DATE_FORMAT.parse(sdate);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 以友好的方式显示时间
     */
    public static String getfriendlyTime(String sdate) {
        if (sdate == null)
            return "";
        Date time = toDate(sdate);
        //        Date time = new Date(ms);

        if (time == null) {
            return "Unknown";
        }
        String ftime = "";
        Calendar cal = Calendar.getInstance();

        // 判断是否是同一天
        String curDate = DATE_FORMAT_DATE.format(cal.getTime());
        String paramDate = DATE_FORMAT_DATE.format(time);

        LogUtil.d("getfriendlyTime: " + paramDate);

        if (curDate.equals(paramDate)) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0) {
                if (((cal.getTimeInMillis() - time.getTime()) / 60000) < 1) {
                    ftime = "剛剛";
                } else {
                    ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分鐘前";
                }
            } else {
                ftime = hour + "小時前";
            }
            return ftime;
        }

        long lt = time.getTime() / 86400000;
        long ct = cal.getTimeInMillis() / 86400000;
        int days = (int) (ct - lt);
        if (days == 0) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max(
                        (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
                        + "分鐘前";
            else
                ftime = hour + "小時前";
        } else if (days == 1) {
            ftime = "昨天";
        } else if (days == 2) {
            ftime = "前天";
        } else if (days > 2 && days <= 10) {
            ftime = days + "天前";
        } else if (days > 10) {
            ftime = DATE_FORMAT_DATE.format(time);
        }
        return ftime;
    }

    /**
     * 距离当前多少个小时
     *
     * @param dateStr
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    public static int getExpiredHour(String dateStr) {
        int ret = -1;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date;
        try {
            date = sdf.parse(dateStr);
            Date dateNow = new Date();

            long times = date.getTime() - dateNow.getTime();
            if (times > 0) {
                ret = ((int) (times / ONE_HOUR_MILLISECONDS));
            } else {
                ret = -1;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return ret;
    }

    /**
     * 过了多少个小时
     *
     * @param dateStr
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    public static int getExpiredHour2(String dateStr) {
        int ret = -1;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date sendDate;
        try {
            sendDate = sdf.parse(dateStr);
            Date dateNow = new Date(System.currentTimeMillis());
            Log.e("JPush", "date=" + sendDate);
            long times = dateNow.getTime() - sendDate.getTime();
            Log.e("JPush", "date.getTime()=" + sendDate.getTime());
            if (times > 0) {
                ret = ((int) (times / ONE_HOUR_MILLISECONDS));
                int sdqf = (int) Math.floor(times / ONE_HOUR_MILLISECONDS);
            } else {
                ret = -1;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Log.e("JPush", "ret=" + ret);
        return ret;
    }


    /**
     * 判断给定字符串时间是否为今日
     *
     * @param sdate
     * @return boolean
     */
    public static boolean isToday(String sdate) {
        boolean b = false;
        Date time = toDate(sdate);
        Date today = new Date();
        if (time != null) {
            String nowDate = DATE_FORMAT_DATE.format(today);
            String timeDate = DATE_FORMAT_DATE.format(time);
            if (nowDate.equals(timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 判断给定字符串时间是否为今日
     *
     * @param sdate
     * @return boolean
     */
    public static boolean isToday(long sdate) {
        boolean b = false;
        Date time = new Date(sdate);
        Date today = new Date();
        if (time != null) {
            String nowDate = DATE_FORMAT_DATE.format(today);
            String timeDate = DATE_FORMAT_DATE.format(time);
            if (nowDate.equals(timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 根据用户生日计算年龄
     */
    public static int getAgeByBirthday(Date birthday) {

        Calendar cal = Calendar.getInstance();

        if (cal.before(birthday)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }

        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

        cal.setTime(birthday);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH) + 1;
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        LogUtil.d("age: " + age);

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                // monthNow==monthBirth
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                }
            } else {
                // monthNow>monthBirth
                age--;
            }
        }
        return age;
    }

    /**
     * 友好显示时间差
     *
     * @param diff 毫秒
     * @return
     */
    public static String getFriendTimeOffer(long diff) {
        int day = (int) (diff / (24 * 60 * 60 * 1000));
        if (day > 0)
            return day + "天";
        int time = (int) (diff / (60 * 60 * 1000));
        if (time > 0)
            return time + "小時";
        int min = (int) (diff / (60 * 1000));
        if (min > 0)
            return min + "分鐘";
        int sec = (int) diff / 1000;
        if (sec > 0)
            return sec + "秒";
        return "1秒";
    }

    /**
     * 友好的时间间隔
     *
     * @param duration 秒
     * @return
     */
    public static String getFriendlyDuration(long duration) {
        String str = "";
        long tmpDuration = duration;
        str += (tmpDuration / 60 > 10 ? tmpDuration / 60 : "0" + tmpDuration / 60) + ":";
        tmpDuration %= 60;
        str += (tmpDuration / 1 >= 10 ? tmpDuration / 1 : "0" + tmpDuration / 1);
        tmpDuration %= 1;
        return str;
    }

    /**
     * 友好的时间间隔2
     *
     * @param duration 秒
     * @return
     */
    public static String getFriendlyDuration2(long duration) {
        String str = "";
        long tmpDuration = duration;
        str += (tmpDuration / 60 > 0 ? tmpDuration / 60 + "'" : "");
        tmpDuration %= 60;
        str += (tmpDuration / 1 >= 10 ? tmpDuration / 1 + "''" : "0" + tmpDuration / 1 + "''");
        tmpDuration %= 1;
        return str;
    }

    public static String getFriendlyMusicDuration(long duration) {
        String str = "-";
        int tmpDuration = (int) (duration / 1000);//秒
        str += (tmpDuration / 3600 > 10 ? tmpDuration / 3600 : "0" + tmpDuration / 3600) + ":";
        tmpDuration %= 3600;
        str += (tmpDuration / 60 > 10 ? tmpDuration / 60 : "0" + tmpDuration / 60) + ":";
        tmpDuration %= 60;
        str += (tmpDuration / 1 >= 10 ? tmpDuration / 1 : "0" + tmpDuration / 1);
        tmpDuration %= 1;
        return str;
    }

    /**
     * 通过日期来确定星座
     *
     * @param mouth
     * @param day
     * @return
     */
    public static String getStarSeat(int mouth, int day) {
        String starSeat = null;
        if ((mouth == 3 && day >= 21) || (mouth == 4 && day <= 19)) {
            starSeat = "白羊座";
        } else if ((mouth == 4 && day >= 20) || (mouth == 5 && day <= 20)) {
            starSeat = "金牛座";
        } else if ((mouth == 5 && day >= 21) || (mouth == 6 && day <= 21)) {
            starSeat = "雙子座";
        } else if ((mouth == 6 && day >= 22) || (mouth == 7 && day <= 22)) {
            starSeat = "巨蟹座";
        } else if ((mouth == 7 && day >= 23) || (mouth == 8 && day <= 22)) {
            starSeat = "獅子座";
        } else if ((mouth == 8 && day >= 23) || (mouth == 9 && day <= 22)) {
            starSeat = "處女座";
        } else if ((mouth == 9 && day >= 23) || (mouth == 10 && day <= 23)) {
            starSeat = "天秤座";
        } else if ((mouth == 10 && day >= 24) || (mouth == 11 && day <= 22)) {
            starSeat = "天蝎座";
        } else if ((mouth == 11 && day >= 23) || (mouth == 12 && day <= 21)) {
            starSeat = "射手座";
        } else if ((mouth == 12 && day >= 22) || (mouth == 1 && day <= 19)) {
            starSeat = "摩羯座";
        } else if ((mouth == 1 && day >= 20) || (mouth == 2 && day <= 18)) {
            starSeat = "水平座";
        } else {
            starSeat = "雙魚座";
        }
        return starSeat;
    }

    /**
     * 返回聊天时间
     *
     * @return
     */
    public static String getChatTimeForShow(long time) {
        if (isToday(time)) {
            return getStringByFormat(time, DATE_FORMAT_DATE);
        } else {
            return getStringByFormat(time, DATE_FORMAT_DATE);
        }
    }

    /**
     * 获取指定时间的毫秒值
     */
    public static long getDatelongMills(String fomat, String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat(fomat);
        Date date = null;
        try {
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long longDate = date.getTime();
        return longDate;
    }

    /**
     * 两个日期比较
     *
     * @param DATE1
     * @param DATE2
     * @return
     */
    public static int compare_date(String DATE1, String DATE2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() - dt2.getTime() > 0) {//date1>date2
                return 1;
            } else {
                return -1;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }

    /**
     * 格式化时间
     *
     * @param hour   小时
     * @param minute 分钟
     * @return 格式化后的时间:[xx:xx]
     */
    public static String formatTime(int hour, int minute) {
        return addZero(hour) + ":" + addZero(minute);
    }

    /**
     * 时间补零
     *
     * @param time 需要补零的时间
     * @return 补零后的时间
     */
    public static String addZero(int time) {
        if (String.valueOf(time).length() == 1) {
            return "0" + time;
        }

        return String.valueOf(time);
    }

    private TimeUtils() {
        throw new AssertionError();
    }

    public static String getFormatTime(String time, SimpleDateFormat simpleDateFormat) {
        return simpleDateFormat.format(new Date(time));
    }

    public static String getYesterdayTime(SimpleDateFormat simpleDateFormat) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, -1);//往上推一天
        return simpleDateFormat.format(calendar.getTime());
    }

    public static String getTime(Date date) {//可根据需要自行截取数据显示
        return DATE_FORMAT_DATE.format(date);
    }

    /**
     * long time to string
     *
     * @param timeInMillis
     * @param dateFormat
     * @return
     */
    public static String getTime(long timeInMillis, SimpleDateFormat dateFormat) {
        return dateFormat.format(new Date(timeInMillis));
    }

    /**
     * long time to string, format is {@link #DEFAULT_DATE_FORMAT}
     *
     * @param timeInMillis
     * @return
     */
    public static String getCurrentTime(long timeInMillis) {
        return getTime(timeInMillis, DEFAULT_DATE_FORMAT);
    }

    /**
     * get current time in milliseconds
     *
     * @return
     */
    public static long getCurrentTimeInLong() {
        return System.currentTimeMillis();
    }

    /**
     * get current time in milliseconds
     *
     * @return
     */
    public static String getCurrentTimeInString(SimpleDateFormat dateFormat) {
        return getTime(getCurrentTimeInLong(), dateFormat);
    }


    /**
     * @param distance 差距： 昨天天傳負一，今天傳零，明天傳一
     * @param type     類型： 1、天 Calendar.DATE  2、年Calendar.YEAR 3、月Calendar.MONTH
     * @param sf       {@link #DEFAULT_DATE_MD}
     * @return
     */
    public static String getDistanceDate(int distance, int type, SimpleDateFormat sf) {
        Date beginDate = new Date();
        Calendar date = Calendar.getInstance();
        date.setTime(beginDate);
        date.set(type, date.get(type) + distance);
        Date endDate = null;
        try {
            endDate = sf.parse(sf.format(date.getTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return sf.format(endDate);
    }

    /**
     * @param beginTime 開始時間
     * @param distance  差距： 昨天天傳負一，今天傳零，明天傳一
     * @param type      類型： 1、天 Calendar.DATE  2、年Calendar.YEAR 3、月Calendar.MONTH
     * @param sf        {@link #DEFAULT_DATE_MD}
     * @return 獲得從開始時間+distance(偏移時間的年月日)
     */
    public static String getBeginDistanceDate(Calendar beginTime, int distance, int type, SimpleDateFormat sf) {
        beginTime.set(type, beginTime.get(type) + distance);
        Date endDate = null;
        try {
            endDate = sf.parse(sf.format(beginTime.getTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return sf.format(endDate);
    }


    /**
     * 获取前n天日期、后n天日期
     *
     * @param distanceDay 前几天 如获取前7天日期则传-7即可；如果后7天则传7
     * @return
     */
    public static String getOldDate(int distanceDay) {
        return getDistanceDate(distanceDay, Calendar.DATE, DATE_FORMAT_DATE);
    }

    /**
     * 获取前n年日期、后n年日期
     *
     * @param distanceYear 前几年 如获取前7年日期则传-7即可；如果后7年则传7
     * @return
     */
    public static String getYear(int distanceYear) {
        return getDistanceDate(distanceYear, Calendar.YEAR, DATE_FORMAT_DATE);
    }

    /**
     * 获取前n月日期、后n月日期
     *
     * @param distanceMonth 前几月 如获取前7月日期则传-7即可；如果后7月则传7
     * @return
     */
    public static String getDistanceMonth(int distanceMonth) {
        return getDistanceDate(distanceMonth, Calendar.YEAR, DATE_FORMAT_DATE);
    }

    /**
     * 把日期型字符串转换为数字型字符串
     *
     * @param time
     * @return
     */
    public static String tranTime(String time) {
        if (time != null) {
            String year;
            String month;
            String day;
            String hour;
            String minute;
            String second;
            year = time.substring(0, 4);
            month = time.substring(5, 7);
            day = time.substring(8, 10);
            hour = time.substring(11, 13);
            minute = time.substring(14, 16);
            second = time.substring(17, 19);
            String newTime = String.format("%s%s%s%s%s%s", year, month, day,
                    hour, minute, second);
            return newTime;
        } else
            return time;
    }

    /**
     * 字符串转换成日期
     *
     * @param str
     * @return date
     */
    public static Date StrToDate(String str) {
        Date date = null;
        try {
            date = DEFAULT_DATE_FORMAT.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 把日期转为字符串
     *
     * @param date
     * @return
     * @Title: ConverToString
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    public static String ConverToString(Date date) {
        return DATE_FORMAT_DATE_HM.format(date);
    }

    /**
     * 日期转换成秒数
     */
    public static long getSecondsFromDate(String expireDate) {
        if (expireDate == null || expireDate.trim().equals(""))
            return 0;
        Date date = null;
        try {
            date = DEFAULT_DATE_FORMAT.parse(expireDate);
            return (long) (date.getTime() / 1000);
        } catch (ParseException e) {
            e.printStackTrace();
            return 0L;
        }
    }
//
//    /**
//     * 时间戳格式转换
//     */
//    static String dayNames[] = {app.getString(R.string.sunday), app.getString(R.string.monday),
//            app.getString(R.string.tuesday), app.getString(R.string.wednesday), app.getString(R.string.thursday),
//            app.getString(R.string.friday), app.getString(R.string.saturday)};
//
//    public static String getNewChatTime(long timesamp) {
//        String result = "";
//        Calendar todayCalendar = Calendar.getInstance();
//        Calendar otherCalendar = Calendar.getInstance();
//        otherCalendar.setTimeInMillis(timesamp);
//        String timeFormat = "M" + app.getString(R.string.month) + "d" + app.getString(R.string.day) + " " + "HH:mm";
//        String yearTimeFormat = "yyyy" + app.getString(R.string.year) + "M" + app.getString(R.string.month) + "d" + app.getString(R.string.day) + " " + "HH:mm";
//        String am_pm = "";
//        int hour = otherCalendar.get(Calendar.HOUR_OF_DAY);
//        if (hour >= 0 && hour < 6) {
//            am_pm = app.getString(R.string.early_morning);
//        } else if (hour >= 6 && hour < 12) {
//            am_pm = app.getString(R.string.morning);
//        } else if (hour == 12) {
//            am_pm = app.getString(R.string.noon);
//        } else if (hour > 12 && hour < 18) {
//            am_pm = app.getString(R.string.afternoon);
//        } else if (hour >= 18) {
//            am_pm = app.getString(R.string.at_night);
//        }
//        timeFormat = "M" + app.getString(R.string.month) + "d" + app.getString(R.string.day) + " " + am_pm + "HH:mm";
//        yearTimeFormat = "yyyy" + app.getString(R.string.year) + "M" + app.getString(R.string.month) + "d" + app.getString(R.string.day) + " " + am_pm + "HH:mm";
//
//        boolean yearTemp = todayCalendar.get(Calendar.YEAR) == otherCalendar.get(Calendar.YEAR);
//        if (yearTemp) {
//            int todayMonth = todayCalendar.get(Calendar.MONTH);
//            int otherMonth = otherCalendar.get(Calendar.MONTH);
//            if (todayMonth == otherMonth) {//表示是同一个月
//                int temp = todayCalendar.get(Calendar.DATE) - otherCalendar.get(Calendar.DATE);
//                switch (temp) {
//                    case 0:
//                        result = am_pm + " " + getHourAndMin(timesamp);
//                        break;
//                    case 1:
//                        result = app.getString(R.string.yesterday) + " " + am_pm + " " + getHourAndMin(timesamp);
//                        break;
//                    case 2:
//                    case 3:
//                    case 4:
//                    case 5:
//                    case 6:
//                        int dayOfMonth = otherCalendar.get(Calendar.WEEK_OF_MONTH);
//                        int todayOfMonth = todayCalendar.get(Calendar.WEEK_OF_MONTH);
//                        if (dayOfMonth == todayOfMonth) {//表示是同一周
////							int dayOfWeek=otherCalendar.get(Calendar.DAY_OF_WEEK);
////							if(dayOfWeek!=1){//判断当前是不是星期日     如想显示为：周日 12:09 可去掉此判断
//                            result = dayNames[otherCalendar.get(Calendar.DAY_OF_WEEK) - 1] + " " + am_pm + " " + getHourAndMin(timesamp);
////							}else{
////								result = getTime(timesamp,timeFormat);
////							}
//                        } else {
//                            result = getTime(timesamp, timeFormat);
//                        }
//                        break;
//                    default:
//                        result = getTime(timesamp, timeFormat);
//                        break;
//                }
//            } else {
//                result = getTime(timesamp, timeFormat);
//            }
//        } else {
//            result = getYearTime(timesamp, yearTimeFormat);
//        }
//        return result;
//    }

    /**
     * 当天的显示时间格式
     *
     * @param time
     * @return
     */
    public static String getHourAndMin(long time) {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        return format.format(new Date(time));
    }

    /**
     * 不同一周的显示时间格式
     *
     * @param time
     * @param timeFormat
     * @return
     */
    public static String getTime(long time, String timeFormat) {
        SimpleDateFormat format = new SimpleDateFormat(timeFormat);
        return format.format(new Date(time));
    }

    /**
     * 不同年的显示时间格式
     *
     * @param time
     * @param yearTimeFormat
     * @return
     */
    public static String getYearTime(long time, String yearTimeFormat) {
        SimpleDateFormat format = new SimpleDateFormat(yearTimeFormat);
        return format.format(new Date(time));
    }

    /**
     * 描述：获取milliseconds表示的日期时间的字符串.
     *
     * @param format 格式化字符串，如："yyyy-MM-dd HH:mm:ss"
     * @return String 日期时间字符串
     */
    public static String getStringByFormat(long milliseconds, SimpleDateFormat format) {
        String thisDateTime = null;
        try {
            thisDateTime = format.format(milliseconds);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return thisDateTime;
    }


    /**
     * 区分白天还是夜晚
     *
     * @param time
     * @return
     */
    public static boolean getDuringOrNight(String time) {
        String before = formatDate(time, DEFAULT_DATE_FORMAT, DATE_FORMAT_DATE_H);
        int k = Integer.parseInt(before);

        if ((k >= 0 && k < 6) || (k >= 18 && k < 24)) {
            return true;
        } else {
            return false;
        }
    }

    /***
     * from yyyy-MM-dd HH:mm:ss to MM-dd HH:mm
     * @param before 之前的时间
     * @param beforeformat 之前的时间格式
     * @param afterformat  之后的时间格式
     * @return
     */
    public static String formatDate(String before, SimpleDateFormat beforeformat, SimpleDateFormat afterformat) {
        String after;
        try {
            Date date = beforeformat.parse(before);
            after = afterformat.format(date);
        } catch (ParseException e) {
            return before;
        }
        return after;
    }

    public static Date parseServerTime(String serverTime, String format) {
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        Date date = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINESE);
            sdf.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
            date = sdf.parse(serverTime);
        } catch (Exception e) {
            Timber.e(e, "");
        }
        return date;
    }

    /**
     * @param time
     * @param dateFormat
     * @return
     */
    public static String parseTimeRepeat(String time, SimpleDateFormat dateFormat) {
        Date date = null;
        if (TextUtils.isEmpty(time)) {
            return "";
        }
        try {
            date = new Date(time);
        } catch (IllegalArgumentException e) {
//            e.printStackTrace();
            try {
                date = dateFormat.parse(time);
            } catch (ParseException ex) {
//                ex.printStackTrace();
            }
        }
        if (date != null) {
            return dateFormat.format(date);
        }
        return time;
    }

    public static String parseDateToString(Date date, SimpleDateFormat dateFormat) {
        return dateFormat.format(date);
    }

    public static Date parseTimeToDate(String time, SimpleDateFormat format) {
        Date date = new Date();
        try {
            date = new Date(time);
        } catch (IllegalArgumentException e) {
            try {
                date = format.parse(time);
            } catch (ParseException ex) {
            }
        }
        return date;
    }

    /**
     * 计算两个日期的相隔天数
     */
    public static int daysBetween(Date date1, Date date2) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date1);
        long time1 = cal.getTimeInMillis();
        cal.setTime(date2);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 计算两个日期的相隔天数
     */
    public static int daysBetween(Calendar startCal, Calendar endCal) {
        long time1 = startCal.getTimeInMillis();
        long time2 = endCal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 獲取傳入時間的前x天或后x的時間
     *
     * @param date
     * @param day
     * @return
     */
    public static String getDatebyDate(String date, int day) {
        try {
            Date date1 = TimeUtils.DATE_FORMAT_DATE.parse(date);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date1);

            long time = cal.getTimeInMillis() + (day * 24 * 60 * 60 * 1000);
            return TimeUtils.DATE_FORMAT_DATE.format(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }
}
