/**
 *
 */
package com.weiqi.mis;

import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @类名 DateUtil
 * @描述: TODO
 * @创建人 yyy
 * @创建时间 2024年3月23日
 * @版本 v1.0
 */
public class DateUtil {
    private static final Logger logger = LoggerFactory.getLogger(DateUtil.class);

    /**
     * 字符串转换成日期
     *
     * @param dateString
     *            日期串
     * @param model
     *            日期串的格式 ，如：yyyy-mm-dd
     * @return
     * @throws Exception
     */
    public static Date string2Date(String dateString, String model) {
        Date date = null;
        SimpleDateFormat sdf = new SimpleDateFormat(model);
        try {
            date = sdf.parse(dateString);

            if (!dateString.equals(sdf.format(date))) {
                date = null;
            }
        } catch (ParseException e) {
            logger.error("DateUtil.String2Date error!");
            e.printStackTrace();
        }
        return date;
    }

    /**
     * utc 时间格式转换正常格式 2018-08-07T03:41:59Z
     *
     * @param utcTime
     *            时间
     * @return
     */
    public static String formatStrUTCToDateStr(String utcTime) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TimeZone utcZone = TimeZone.getTimeZone("UTC");
        sf.setTimeZone(utcZone);
        Date date = null;
        String dateTime = "";
        try {
            date = sf.parse(utcTime);
            dateTime = sdf.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateTime;
    }

    /**
     * 当前日期加减n天的日期
     *
     * @param n
     *            正数加，负数减
     * @return
     */
    public static Date nDaysAfterNowDate(int n) {
        Calendar rightNow = Calendar.getInstance();
        rightNow.add(Calendar.DAY_OF_MONTH, +n);
        return rightNow.getTime();
    }

    /**
     * dateToDate
     *
     * @param date
     *            日期
     * @param model
     *            转换成的格式 如：yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static Date getFormatDate(Date date, String model) {
        SimpleDateFormat sdf = new SimpleDateFormat(model);
        Date formatdate = null;
        try {
            formatdate = sdf.parse(sdf.format(date));
        } catch (ParseException e) {
            logger.error("日期转换失败", e);
        }
        return formatdate;
    }

    /**
     * 日期转换成字符串
     *
     * @param date
     * @param model
     *            如yyyyMMdd
     * @return
     */
    public static String Date2String(Date date, String model) {
        SimpleDateFormat sdf = new SimpleDateFormat(model);
        String strdate = sdf.format(date);
        return strdate;
    }

    /**
     * 返回8位当前系统时间
     *
     * @return
     */
    public static String Date2String8() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String strdate = sdf.format(new Date());
        return strdate;
    }

    /**
     * 判定传入时间是否是当天
     *
     * @param date
     *            日期
     * @return
     */
    public static boolean isTodayDate(Date date) {
        boolean ret = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String compDay = null;
        try {
            compDay = sdf.format(date);
            String today = sdf.format(new Date());
            if (compDay.equals(today)) {
                ret = true;
            }
        } catch (Exception e) {
            logger.error("日期比较失败", e);
        }
        return ret;
    }

    /**
     * 大于当天 true 否则 false
     *
     * @param str
     *            日期
     * @param
     * @return
     */
    public static boolean compareToday(String str) {
        boolean ret = false;
        if (str == null || str.length() == 0) {
            return ret;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String strdate = sdf.format(new Date());
        try {
            if (strdate.compareTo(str) <= 0) {
                return true;
            } else {
                return false;
            }

        } catch (Exception e) {
            logger.error("日期比较失败", e);

        }
        return ret;
    }

    /**
     * 给定时间在某一时间范围内
     *
     * @param start
     *            日期格式为 yyyy-MM-dd
     * @param end
     *            日期格式为 yyyy-MM-dd
     * @param appoint
     *            日期格式为 yyyy-MM-dd
     * @return
     */
    public static boolean compareBetweenAnd(String start, String end, String appoint) {
        boolean ret = false;
        if ((start == null || start.length() == 0) || (end == null || end.length() == 0)) {
            return ret;
        }
        try {
            if ((appoint.compareTo(start) >= 0) && (appoint.compareTo(end) <= 0)) {
                return true;
            } else {
                return false;
            }

        } catch (Exception e) {
            logger.error("日期比较失败", e);

        }
        return ret;
    }

    /**
     * 给定时间在某一时间范围内不含等号
     *
     * @param start
     *            日期格式为 yyyy-MM-dd
     * @param end
     *            日期格式为 yyyy-MM-dd
     * @param appoint
     *            日期格式为 yyyy-MM-dd
     * @return
     */
    public static boolean compareBetweenAndNOT(String start, String end, String appoint) {
        boolean ret = false;
        if ((start == null || start.length() == 0) || (end == null || end.length() == 0)) {
            return ret;
        }
        try {
            if ((appoint.compareTo(start) < 0) || (appoint.compareTo(end) > 0)) {
                return true;
            } else {
                return false;
            }

        } catch (Exception e) {
            logger.error("日期比较失败", e);

        }
        return ret;
    }

    // 获取当天的开始时间
    public static Date getDayBegin() {
        Calendar cal = new GregorianCalendar();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    // 获取当天的结束时间
    public static Date getDayEnd() {
        Calendar cal = new GregorianCalendar();
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        return cal.getTime();
    }

    // 获取昨天的开始时间
    public static Date getBeginDayOfYesterday() {
        Calendar cal = new GregorianCalendar();
        cal.setTime(getDayBegin());
        cal.add(Calendar.DAY_OF_MONTH, -1);
        return cal.getTime();
    }

    // 获取昨天的结束时间
    public static Date getEndDayOfYesterDay() {
        Calendar cal = new GregorianCalendar();
        cal.setTime(getDayEnd());
        cal.add(Calendar.DAY_OF_MONTH, -1);
        return cal.getTime();
    }

    // 获取明天的开始时间
    public static Date getBeginDayOfTomorrow() {
        Calendar cal = new GregorianCalendar();
        cal.setTime(getDayBegin());
        cal.add(Calendar.DAY_OF_MONTH, 1);

        return cal.getTime();
    }

    // 获取明天的结束时间
    public static Date getEndDayOfTomorrow() {
        Calendar cal = new GregorianCalendar();
        cal.setTime(getDayEnd());
        cal.add(Calendar.DAY_OF_MONTH, 1);
        return cal.getTime();
    }

    // 获取本周的开始时间
    public static Date getBeginDayOfWeek() {
        Date date = new Date();
        if (date == null) {
            return null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
        if (dayofweek == 1) {
            dayofweek += 7;
        }
        cal.add(Calendar.DATE, 2 - dayofweek);
        return getDayStartTime(cal.getTime());
    }

    // 获取本周的结束时间
    public static Date getEndDayOfWeek() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getBeginDayOfWeek());
        cal.add(Calendar.DAY_OF_WEEK, 6);
        Date weekEndSta = cal.getTime();
        return getDayEndTime(weekEndSta);
    }

    // 获取本月的开始时间
    public static Date getBeginDayOfMonth() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(getNowYear(), getNowMonth() - 1, 1);
        return getDayStartTime(calendar.getTime());
    }

    // 指定月的开始时间
    public static Date getBeginDayOfMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 1);
        return getDayStartTime(calendar.getTime());
    }

    // 获取本月的开始时间
    public static String getBeginDayOfMonthStr() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(getNowYear(), getNowMonth() - 1, 1);

        return Date2String(getDayStartTime(calendar.getTime()), "yyyy-MM-dd") + " 00:00:00";
    }

    // 获取本月的结束时间
    public static String getEndDayOfMonth() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(getNowYear(), getNowMonth() - 1, 1);
        int day = calendar.getActualMaximum(5);
        calendar.set(getNowYear(), getNowMonth() - 1, day);

        return Date2String(getDayEndTime(calendar.getTime()), "yyyy-MM-dd") + " 00:00:00";
    }

    // 获取本月的结束时间
    public static Date getEndDayOfMonthStr() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(getNowYear(), getNowMonth() - 1, 1);
        int day = calendar.getActualMaximum(5);
        calendar.set(getNowYear(), getNowMonth() - 1, day);
        return getDayEndTime(calendar.getTime());
    }

    // 指定月的结束时间
    public static Date getEndDayOfMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 1);
        int day = calendar.getActualMaximum(5);
        calendar.set(year, month - 1, day);
        return getDayEndTime(calendar.getTime());
    }

    // 获取本年的开始时间
    public static Date getBeginDayOfYear() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, getNowYear());
        // cal.set
        cal.set(Calendar.MONTH, Calendar.JANUARY);
        cal.set(Calendar.DATE, 1);

        return getDayStartTime(cal.getTime());
    }

    // 获取本年的结束时间
    public static Date getEndDayOfYear() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, getNowYear());
        cal.set(Calendar.MONTH, Calendar.DECEMBER);
        cal.set(Calendar.DATE, 31);
        return getDayEndTime(cal.getTime());
    }

    // 获取某个日期的开始时间
    public static Timestamp getDayStartTime(Date d) {
        Calendar calendar = Calendar.getInstance();
        if (null != d) {
            calendar.setTime(d);
        }
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0,
            0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return new Timestamp(calendar.getTimeInMillis());
    }

    // 获取某个日期的结束时间
    public static Timestamp getDayEndTime(Date d) {
        Calendar calendar = Calendar.getInstance();
        if (null != d) {
            calendar.setTime(d);
        }
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 23,
            59, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return new Timestamp(calendar.getTimeInMillis());
    }

    // 获取今年是哪一年
    public static Integer getNowYear() {
        Date date = new Date();
        GregorianCalendar gc = (GregorianCalendar)Calendar.getInstance();
        gc.setTime(date);
        return Integer.valueOf(gc.get(1));
    }

    // 获取本月是哪一月
    public static int getNowMonth() {
        Date date = new Date();
        GregorianCalendar gc = (GregorianCalendar)Calendar.getInstance();
        gc.setTime(date);
        return gc.get(2) + 1;
    }

    // 两个日期相减得到的天数
    public static int getDiffDays(Date beginDate, Date endDate) {

        if (beginDate == null || endDate == null) {
            throw new IllegalArgumentException("getDiffDays param is null!");
        }

        long diff = (endDate.getTime() - beginDate.getTime()) / (1000 * 60 * 60 * 24);

        int days = new Long(diff).intValue();

        return days + 1;
    }

    // 两个日期相减得到的毫秒数
    public static long dateDiff(Date beginDate, Date endDate) {
        long date1ms = beginDate.getTime();
        long date2ms = endDate.getTime();
        return date2ms - date1ms;
    }

    // 获取两个日期中的最大日期
    public static Date max(Date beginDate, Date endDate) {
        if (beginDate == null) {
            return endDate;
        }
        if (endDate == null) {
            return beginDate;
        }
        if (beginDate.after(endDate)) {
            return beginDate;
        }
        return endDate;
    }

    // 获取两个日期中的最小日期
    public static Date min(Date beginDate, Date endDate) {
        if (beginDate == null) {
            return endDate;
        }
        if (endDate == null) {
            return beginDate;
        }
        if (beginDate.after(endDate)) {
            return endDate;
        }
        return beginDate;
    }

    // 返回某月该季度的第一个月
    public static Date getFirstSeasonDate(Date date) {
        final int[] SEASON = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int sean = SEASON[cal.get(Calendar.MONTH)];
        cal.set(Calendar.MONTH, sean * 3 - 3);
        return cal.getTime();
    }

    // 返回某个日期下几天的日期
    public static Date getNextDay(Date date, int i) {
        Calendar cal = new GregorianCalendar();
        cal.setTime(date);
        cal.set(Calendar.DATE, cal.get(Calendar.DATE) + i);
        return cal.getTime();
    }

    // 返回某个日期前几天的日期
    public static Date getFrontDay(Date date, int i) {
        Calendar cal = new GregorianCalendar();
        cal.setTime(date);
        cal.set(Calendar.DATE, cal.get(Calendar.DATE) - i);
        return cal.getTime();
    }

    // 获取某年某月到某年某月按天的切片日期集合（间隔天数的集合）
    public static List getTimeList(int beginYear, int beginMonth, int endYear, int endMonth, int k) {
        List list = new ArrayList();
        if (beginYear == endYear) {
            for (int j = beginMonth; j <= endMonth; j++) {
                list.add(getTimeList(beginYear, j, k));

            }
        } else {
            {
                for (int j = beginMonth; j < 12; j++) {
                    list.add(getTimeList(beginYear, j, k));
                }

                for (int i = beginYear + 1; i < endYear; i++) {
                    for (int j = 0; j < 12; j++) {
                        list.add(getTimeList(i, j, k));
                    }
                }
                for (int j = 0; j <= endMonth; j++) {
                    list.add(getTimeList(endYear, j, k));
                }
            }
        }
        return list;
    }

    // 获取某年某月按天切片日期集合（某个月间隔多少天的日期集合）
    public static List getTimeList(int beginYear, int beginMonth, int k) {
        List list = new ArrayList();
        Calendar begincal = new GregorianCalendar(beginYear, beginMonth, 1);
        int max = begincal.getActualMaximum(Calendar.DATE);
        for (int i = 1; i < max; i = i + k) {
            list.add(begincal.getTime());
            begincal.add(Calendar.DATE, k);
        }
        begincal = new GregorianCalendar(beginYear, beginMonth, max);
        list.add(begincal.getTime());
        return list;
    }

    public static String UTCToCST(String UTCStr, String format) {
        try {
            if (UTCStr.length() == 19) {
                return UTCStr;
            } else {
                return UTCStr.substring(0, 19);
            }
            // if(format==null){
            // if(UTCStr.length()==19){
            // format = "yyyy-MM-dd'T'HH:mm:ss";
            // }else{
            //
            // format = "yyyy-MM-dd'T'HH:mm:ss.SSS";
            // }
            // }
            //
            // Date date = null;
            // SimpleDateFormat sdf = new SimpleDateFormat(format);
            // date = sdf.parse(UTCStr);
            //// System.out.println("UTC时间: " + date);
            // Calendar calendar = Calendar.getInstance(); calendar.setTime(date);
            // calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) + 8); //calendar.getTime()
            // 返回的是Date类型，也可以使用calendar.getTimeInMillis()获取时间戳
            //// System.out.println("北京时间: " + calendar.getTime());
            //
            // SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // String strdate = sdf1.format(calendar.getTime());
            //
            // return strdate;
        } catch (Exception e) {
            return UTCStr;
        }
    }

    // 获取当前时间1-5秒统一归位1秒
    public static Date getCurrentTimeFormate() {

        Date d = new Date();
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        int second = now.get(Calendar.SECOND);
        int sechigh = second / 10;
        int sec = second % 10;
        // System.out.println(second);
        if (sec < 5) {
            sec = sechigh * 10;
        } else {
            sec = sechigh * 10 + 5;
        }
        now.set(Calendar.SECOND, sec);
        // logger.error("--------当前时间，计算时间-------{}---{}---------{}",second,sec,now.getTime());
        return now.getTime();
    }

    // 获取当前时间1-5秒统一归位1秒
    public static long getCurrentTimeLong() {

        Date d = new Date();
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        int second = now.get(Calendar.SECOND);
        int sechigh = second / 10;
        int sec = second % 10;
        // System.out.println(second);
        if (sec < 5) {
            sec = sechigh * 10;
        } else {
            sec = sechigh * 10 + 5;
        }
        now.set(Calendar.SECOND, sec);

        // System.out.println("+++++"+now.getTime());
        String time = now.getTime().getTime() + "";
        String rettime = time.substring(0, 10) + "000";
        // logger.error("--------当前时间，计算时间-------{}---{}---------{},{}",second,sec,now.getTime(),rettime);
        return Long.valueOf(rettime);
    }

    // 获取当前时间1-5秒统一归位1秒
    public static long getCurrentTimeLong(String date) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date d = sdf.parse(date);
            Calendar now = Calendar.getInstance();
            now.setTime(d);
            int second = now.get(Calendar.SECOND);
            int sechigh = second / 10;
            int sec = second % 10;
            if (sec < 5) {
                sec = sechigh * 10;
            } else {
                sec = sechigh * 10 + 5;
            }
            now.set(Calendar.SECOND, sec);
            String time = now.getTime().getTime() + "";
            String rettime = time.substring(0, 10) + "000";

            return Long.valueOf(rettime);
        } catch (Exception e) {
            logger.error("{}", e);
        }

        return 0;

    }

    public static void main(String[] args) throws ParseException {
//
//        System.currentTimeMillis();
//        System.out.println(getCurrentTimeFormate().getTime());
//        System.out.println(getCurrentTimeLong());

        System.out.println(getExpireByTtl("D",1,new Date()).getTime());

        // System.out.println(formatShopTime2String("2024-12-12"));
        //
        // System.out.println(getDateBeforeSecond( 7));
        // System.out.println(Date2String8().compareTo("20241109"));
        // System.out.println(monthBeforeToString(new Date(),3));
        // System.out.println(dayBefore(string2Date("2018-03-01", "yyyy-MM-dd"), 90, null));
        // List<LocalDate> local = getBetweenDates("2018-03-01", "2018-04-22","yyyy-MM-dd", true);
        // System.out.println(local.get(0).toString());
        // System.out.println(daysBetweenDates(string2Date("2024-07-04 11:20:20","yyyy-MM-dd
        // HH:mm:ss"),string2Date("2024-06-30 12:30:40","yyyy-MM-dd HH:mm:ss")));

        // System.out.println(getDateBeforeTimeMillis(365));
        // System.out.println(getDateBeforeTimeMillis(0));
        // System.out.println(getDateBefore(0));
        // System.out.println(System.currentTimeMillis());

    }

    /**
     * 返回指定格式时间
     *
     * @param strY
     *            原来时间字符串
     * @param strYGS
     *            原时间格式
     * @return
     */
    public static String string2String(String strY, String strYGS, String strMGS) {
        SimpleDateFormat s = new SimpleDateFormat(strYGS);
        String date = strY;
        String dat = "";
        Date d;
        try {
            d = s.parse(date);
            SimpleDateFormat ss = new SimpleDateFormat(strMGS);
            dat = ss.format(d);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            dat = "时间格式有误！";
            e.printStackTrace();
        }
        return dat;
    }

    /**
     * 返回时分秒
     *
     * @param strY
     *            原来时间字符串
     * @return
     */
    public static String string2StringSecond(String strY) {

        String date = strY;
        if (date == null || date.length() != 6) {
            return date;
        }
        String HH = strY.substring(0, 2);
        String mm = strY.substring(2, 4);
        String ss = strY.substring(4, 6);
        date = HH + ":" + mm + ":" + ss;
        return date;
    }

    /**
     * getTodayBeginTime
     *
     * @return 当日开始时间
     */
    public static Date getTodayBeginTime() {
        Calendar c1 = new GregorianCalendar();
        c1.set(Calendar.HOUR_OF_DAY, 0);
        c1.set(Calendar.MINUTE, 0);
        c1.set(Calendar.SECOND, 0);
        return c1.getTime();
    }

    /**
     * getTodayEndTime
     *
     * @return 当日开始时间
     */
    public static Date getTodayEndTime() {
        Calendar c1 = new GregorianCalendar();
        c1.set(Calendar.HOUR_OF_DAY, 23);
        c1.set(Calendar.MINUTE, 59);
        c1.set(Calendar.SECOND, 59);
        return c1.getTime();
    }

    /**
     * 得到两个日期之间相差的天数
     *
     * @param newDate
     *            大的日期
     * @param oldDate
     *            小的日期
     * @return newDate-oldDate相差的天数
     */
    public static int daysBetweenDates(Date newDate, Date oldDate) {
        int days = 0;
        Calendar calo = Calendar.getInstance();
        Calendar caln = Calendar.getInstance();
        calo.setTime(oldDate);
        caln.setTime(newDate);
        int oday = calo.get(Calendar.DAY_OF_YEAR);
        int nyear = caln.get(Calendar.YEAR);
        int oyear = calo.get(Calendar.YEAR);
        while (nyear > oyear) {
            calo.set(Calendar.MONTH, 11);
            calo.set(Calendar.DATE, 31);
            days = days + calo.get(Calendar.DAY_OF_YEAR);
            oyear = oyear + 1;
            calo.set(Calendar.YEAR, oyear);
        }
        int nday = caln.get(Calendar.DAY_OF_YEAR);
        days = days + nday - oday;

        return days;
    }

    public static String getPerDateDay(int n, String date, String model) {
        // n为推迟的天数 -1表示前一天，1后移一天
        SimpleDateFormat f = new SimpleDateFormat(model);
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(f.parse(date));
        } catch (ParseException e) {
            System.out.println(e);
        }

        c.add(Calendar.DATE, n);
        String day = f.format(c.getTime());
        return day;
    }

    /**
     * 传递一个数据返回精准的yyyy/mm/dd hh:mm:ss
     *
     * @param dateStr
     * @return
     */
    public static String formatDate2String(String dateStr) {
        String str = "";
        if (dateStr != null && dateStr.length() == 14) {
            String y = dateStr.substring(0, 4);
            String m = dateStr.substring(4, 6);
            String d = dateStr.substring(6, 8);
            String h = dateStr.substring(8, 10);
            String fen = dateStr.substring(10, 12);
            String sec = dateStr.substring(12, 14);
            str = y + "/" + m + "/" + d + " " + h + ":" + fen + ":" + sec;
            return str;
        } else {
            return dateStr;
        }
    }

    /**
     * 传递一个数据返回精准的yyyy-mm-dd 转换成 yyyy年mm月dd日
     *
     * @param dateStr
     * @return
     */
    public static String formatShopTime2String(String dateStr) {
        String str = "";
        if (dateStr != null && dateStr.length() == 10) {
            String y = dateStr.substring(0, 4);
            String m = dateStr.substring(5, 7);
            String d = dateStr.substring(8, 10);
            str = y + "年" + m + "月" + d + "日";
            return str;
        } else {
            return dateStr;
        }
    }

    /**
     * 计算几个月前时间
     *
     * @param month
     * @return
     */
    public static Date monthBefore(int month) {
        Date dNow = new Date(); // 当前时间
        Date dBefore = new Date();
        Calendar calendar = Calendar.getInstance(); // 得到日历
        calendar.setTime(dNow);// 把当前时间赋给日历
        calendar.add(calendar.MONTH, -month); // 设置为前3月
        dBefore = calendar.getTime(); // 得到前3月的时间
        // SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置时间格式
        // String defaultStartDate = sdf.format(dBefore); //格式化前3月的时间
        // System.out.println("前"+month+"个月的时间是：" + defaultStartDate);
        return dBefore;
    }

    /**
     * 计算指定日期几个月前时间
     *
     * @param month
     * @return
     */
    public static Date monthBefore(Date date, int month) {
        Calendar calendar = Calendar.getInstance(); // 得到日历
        calendar.setTime(date);// 把当前时间赋给日历
        calendar.add(calendar.MONTH, -month); // 设置为前3月
        Date dBefore = calendar.getTime(); // 得到前3月的时间
        return dBefore;
    }

    /**
     * 计算几天前时间
     *
     * @param day
     * @return
     */
    public static Date dayBefore(int day) {
        Date dNow = new Date(); // 当前时间
        Date dBefore = new Date();
        Calendar calendar = Calendar.getInstance(); // 得到日历
        calendar.setTime(dNow);// 把当前时间赋给日历
        calendar.add(calendar.DATE, -day); // 设置为前3月
        calendar.set(Calendar.HOUR_OF_DAY, 00);
        calendar.set(Calendar.MINUTE, 00);
        calendar.set(Calendar.SECOND, 00);
        dBefore = calendar.getTime(); // 得到前3月的时间
        // SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置时间格式
        // String defaultStartDate = sdf.format(dBefore); //格式化前3月的时间
        // System.out.println("前"+month+"个月的时间是：" + defaultStartDate);
        return dBefore;
    }

    // 获取几天前开始时间
    public static String getDateBefore(int day) {
        Date d = new Date();
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        now.set(Calendar.HOUR_OF_DAY, 0);
        now.set(Calendar.MINUTE, 0);
        now.set(Calendar.SECOND, 0);
        now.set(Calendar.MILLISECOND, 0);
        // System.out.println(now.getTime());
        return Date2String(now.getTime(), "yyyy-MM-dd HH:mm:ss");
    }

    // //获取几天前开始时间
    public static long getDateBeforeTimeMillis(int day) {
        Date d = new Date();
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        now.set(Calendar.HOUR_OF_DAY, 0);
        now.set(Calendar.MINUTE, 0);
        now.set(Calendar.SECOND, 0);
        now.set(Calendar.MILLISECOND, 0);
        return now.getTimeInMillis();
    }

    // 获取几天前结束时间
    public static String getEndDateBefore(int day) {

        Date d = new Date();
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        now.set(Calendar.HOUR_OF_DAY, 23);
        now.set(Calendar.MINUTE, 59);
        now.set(Calendar.SECOND, 59);
        return Date2String(now.getTime(), "yyyy-MM-dd HH:mm:ss");
    }

    public static List<String> getMonthBetween(String minDate, String maxDate) throws ParseException {
        ArrayList<String> result = new ArrayList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");// 格式化为年月

        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();

        min.setTime(sdf.parse(minDate));
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

        max.setTime(sdf.parse(maxDate));
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

        Calendar curr = min;
        while (curr.before(max)) {
            result.add(sdf.format(curr.getTime()));
            curr.add(Calendar.MONTH, 1);
        }

        return result;
    }

    /**
     * 获取两个日期之间的日期
     * 
     * @param beginDate
     * @param endDate
     * @return
     */
    public static List<LocalDate> getBetweenDates(String beginDate, String endDate, String fmt, boolean isChoose) {
        List<LocalDate> result = new ArrayList<LocalDate>();
        DateTimeFormatter formatter = null;
        if (Strings.isNullOrEmpty(fmt)) {
            formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        } else {
            formatter = DateTimeFormatter.ofPattern(fmt);
        }
        LocalDate startTime = LocalDate.parse(beginDate, formatter);
        if (!isChoose) {
            startTime = startTime.plusDays(1);
        }
        LocalDate endTime = LocalDate.parse(endDate, formatter);
        while (startTime.isBefore(endTime)) {
            result.add(startTime);
            startTime = startTime.plusDays(1);
        }
        if (isChoose) {
            result.add(endTime);
        }
        return result;
    }

    /**
     * 返回当前系统时间 yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String getCurrentDate(String model) {
        SimpleDateFormat sdf = new SimpleDateFormat(model);
        String strdate = sdf.format(new Date());
        return strdate;
    }

    /**
     * 计算到第二天凌晨0点之后点一个随机值，为了防止大面值key失效导致点服务器压力，使其在10分钟之内均匀失效
     *
     * @return
     */
    public static Long getSecondsNextEarlyMorning() {
        int ranmin = new Random().nextInt(10);
        int ransec = new Random().nextInt(59);
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, 1);
        // 改成这样就好了
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, ransec);
        cal.set(Calendar.MINUTE, ranmin);
        cal.set(Calendar.MILLISECOND, 0);
        return (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
    }


    /**
     * 格式为时间单位+正整数。支持年（Y）、月（M）、日（D）、时（H）、分（m）、秒（S）时间单位。 例如Y1（1年），M2（2个月），D3（3天），H4（4小时），m5（5分钟），S6（6秒）。不支持两个单位同时使用。
     * 如果ttl为空，则默认为一个月。
     *
     * @param ttlTimeUnit
     * @param ttlTime
     * @param now
     * @return
     */
    public static Date getExpireByTtl(String ttlTimeUnit, int ttlTime, Date now) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        switch (ttlTimeUnit) {
            case "Y":
                calendar.add(Calendar.YEAR, ttlTime);
                break;
            case "M":
                calendar.add(Calendar.MONTH, ttlTime);
                break;
            case "D":
                calendar.add(Calendar.DATE, ttlTime);
                break;
            case "H":
                calendar.add(Calendar.HOUR, ttlTime);
                break;
            case "m":
                calendar.add(Calendar.MINUTE, ttlTime);
                break;
            case "S":
                calendar.add(calendar.SECOND, ttlTime);
                break;
        }
        return calendar.getTime();
    }
    /**
     * 获取当前天开始时间
     * @return
     */
    public static String getStartOfToday() {
        LocalDateTime now = LocalDateTime.now();  // 获取当前时间
        LocalDateTime startOfToday = now.withHour(0).withMinute(0).withSecond(0);  // 设置时分秒为0
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");  // 定义日期时间格式
        String startOfTodayStr = startOfToday.format(formatter);  // 格式化为字符串
        return startOfTodayStr;
    }

    /**
     * 返回当前小时前一个小时的时间
     * @return
     */
    public static String getBefore1Hour() {

        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();

        // 减去一小时
        LocalDateTime previousHour = currentTime.minusHours(1);

        // 格式化为字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = previousHour.format(formatter);

        return formattedDateTime;
    }

    /**
     * 返回当前系统时间 yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    // public static String getDateBefore(int n) {
    // Calendar calendar = Calendar.getInstance();
    // Date date = new Date(System.currentTimeMillis());
    // calendar.setTime(date);
    //// calendar.add(Calendar.WEEK_OF_YEAR, -1);
    // calendar.add(Calendar.YEAR, n);
    // date = calendar.getTime();
    // System.out.println(date);
    // return tt;
    // }

    // 获取当前时刻timestamp

    /**
     *
     * @param model
     * @return
     */
    public static String getTimestamp( String model) {
        String timestamp = "";
        SimpleDateFormat sdf = new SimpleDateFormat(model);
        timestamp = sdf.format(new Date());
        return timestamp;
    }
}
