时间相关的统计工具

烂漫一生 提交于 2020-01-09 12:11:55
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class StatisticsUtils {

    /**
     * 日期格式:yyyy-MM-dd HH:mm:ss
     */
    public static final String FMT_DATETIME = "yyyy-MM-dd HH:mm:ss";

    private static final int[] SEASON = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4};

    public static final String[] DEFAULT_CHAIN_RATIO = {"0", "0"};

    /**
     * 1:今日;2:本周;3:本月;4当季;5:全年
     */
    public static final int DATA_DATE_TYPE_1 = 1;
    /**
     * 1:今日;2:本周;3:本月;4当季;5:全年
     */
    public static final int DATA_DATE_TYPE_2 = 2;
    /**
     * 1:今日;2:本周;3:本月;4当季;5:全年
     */
    public static final int DATA_DATE_TYPE_3 = 3;
    /**
     * 1:今日;2:本周;3:本月;4当季;5:全年
     */
    public static final int DATA_DATE_TYPE_4 = 4;
    /**
     * 1:今日;2:本周;3:本月;4当季;5:全年
     */
    public static final int DATA_DATE_TYPE_5 = 5;

    public static void main(String[] args) {
        String date = "2019-05-01 05:03:03";
        Date parse = parse(date, FMT_DATETIME);

        Date quarterStartDate = getQuarterFirstDate(parse);
        System.out.println(format(quarterStartDate, FMT_DATETIME));
        Date quarterLastDate = getQuarterLastDate(parse, false);
        System.out.println(format(quarterLastDate, FMT_DATETIME));

        Date quarterStartDate1 = getPreviousQuarterFirstDate(parse);
        System.out.println(format(quarterStartDate1, FMT_DATETIME));
        Date quarterLastDate1 = getPreviousQuarterLastDate(parse, false);
        System.out.println(format(quarterLastDate1, FMT_DATETIME));

        Date yearFirstDate = getYearFirstDate(parse);
        System.out.println(format(yearFirstDate, FMT_DATETIME));
        Date yearLastDate = getYearLastDate(parse, false);
        System.out.println(format(yearLastDate, FMT_DATETIME));
        Date lastYearFirstDate = getLastYearFirstDate(parse);
        System.out.println(format(lastYearFirstDate, FMT_DATETIME));
        Date lastYearLastDate = getLastYearLastDate(parse, false);
        System.out.println(format(lastYearLastDate, FMT_DATETIME));

        Date weekFirstDate = getWeekFirstDate(parse);
        Date lastWeekFirstDate = getLastWeekFirstDate(parse);
        Date lastWeekLastDate = getLastWeekLastDate(parse, false);
        System.out.println(format(weekFirstDate, FMT_DATETIME));
        System.out.println(format(lastWeekFirstDate, FMT_DATETIME));
        System.out.println(format(lastWeekLastDate, FMT_DATETIME));

        Date monthFirstDate = getMonthFirstDate(parse);
        System.out.println(format(monthFirstDate, FMT_DATETIME));
        Date monthLastDate = getMonthLastDate(parse, true);
        System.out.println(format(monthLastDate, FMT_DATETIME));
        Date lastMonthFirstDate = getLastMonthFirstDate(parse);
        Date lastMonthLastDate = getLastMonthLastDate(parse, false);
        System.out.println(format(lastMonthFirstDate, FMT_DATETIME));
        System.out.println(format(lastMonthLastDate, FMT_DATETIME));

        Integer hm2M = getHm2M(parse);
        System.out.println(hm2M);

        double calc = calcAndRounding(123.456, 1, 2);
        System.out.println(calc);

        String format = format(new Date(), "yyyy-MM-dd 23:59:59");
        System.out.println(format);

    }

    /**
     * 格式化日期
     *
     * @param date       日期
     * @param dateFormat 日期格式化模式
     * @return 日期字符串
     */
    public static String format(Date date, String dateFormat) {
        return new SimpleDateFormat(dateFormat).format(date);
    }

    /**
     * 解析日期
     *
     * @param date       日期字符串
     * @param dateFormat 日期格式化模式
     * @return Date
     */
    public static Date parse(String date, String dateFormat) {
        try {
            return new SimpleDateFormat(dateFormat).parse(date);
        } catch (ParseException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * 获取小时转分钟+分钟的值
     *
     * @param date
     * @return
     */
    public static Integer getHm2M(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int minuteTotal = hour * 60 + minute;
        return minuteTotal;
    }

    /**
     * 计算并四舍五入
     *
     * @param ori     原始数据
     * @param divisor 除数
     * @param power   保留小数点几位
     * @return
     */
    public static double calcAndRounding(double ori, Integer divisor, int power) {
        if (divisor == null || divisor == 0) {
            return 0;
        }
        int pow = (int) Math.pow(10, power);
        return (double) Math.round(ori / divisor * pow) / pow;
    }

    /**
     * 计算并四舍五入
     *
     * @param ori
     * @param divisor
     * @param power
     * @return
     */
    public static double calcAndRoundingForInteger(Integer ori, Integer divisor, int power) {
        return calcAndRounding(ori * 1.0, divisor, power);
    }

    /**
     * 获取四个日期段
     *
     * @param type 0:不展示;1:今日;2:本周;3:本月;4当季;5:全年
     * @return type=0:返回null;
     * 1:今日日期,今日日期,昨日日期,昨日日期;
     * 2:本周周一日期,本周周日日期,上周周一日期,上周周日日期
     * 3:本月1号日期,今日日期,上月1号日期,上月最后一天日期
     * 4:当季开始日期,今日日期,上季开始日期,上季最后一天日期
     * 5:今年开始日期,今日日期,上年开始日期,上年最后一天日期
     * default:返回null
     */
    public static Date[] getQueryDate(Integer type, boolean format23h59m59s) {
        Date[] dates = null;
        switch (type) {
            // 今日
            case DATA_DATE_TYPE_1: {
                Date today = new Date();
                Date formatDate = StatisticsUtils.formatDate(today, format23h59m59s);
                Date yesterday = StatisticsUtils.getBeforeNDayDate(formatDate, 1);
                dates = new Date[]{formatDate, formatDate, yesterday, yesterday};
                break;
            }
            // 本周
            case DATA_DATE_TYPE_2: {
                Date today = new Date();
                Date formatDate = StatisticsUtils.formatDate(today, format23h59m59s);
                Date weekFirstDate = StatisticsUtils.getWeekFirstDate(today);
                Date lastWeekFirstDate = StatisticsUtils.getLastWeekFirstDate(today);
                Date lastWeekLastDate = StatisticsUtils.getLastWeekLastDate(today, format23h59m59s);
                dates = new Date[]{weekFirstDate, formatDate, lastWeekFirstDate, lastWeekLastDate};
                break;
            }
            // 本月
            case DATA_DATE_TYPE_3: {
                Date today = new Date();
                Date formatDate = StatisticsUtils.formatDate(today, format23h59m59s);
                Date monthFirstDate = StatisticsUtils.getMonthFirstDate(today);
                Date lastMonthFirstDate = StatisticsUtils.getLastMonthFirstDate(today);
                Date lastMonthLastDate = StatisticsUtils.getLastMonthLastDate(today, false);
                dates = new Date[]{monthFirstDate, formatDate, lastMonthFirstDate, lastMonthLastDate};
                break;
            }
            // 当季
            case DATA_DATE_TYPE_4: {
                Date today = new Date();
                Date formatDate = StatisticsUtils.formatDate(today, format23h59m59s);
                Date quarterFirstDate = StatisticsUtils.getQuarterFirstDate(today);
                Date previousQuarterFirstDate = StatisticsUtils.getPreviousQuarterFirstDate(today);
                Date previousQuarterLastDate = StatisticsUtils.getPreviousQuarterLastDate(today, false);
                dates = new Date[]{quarterFirstDate, formatDate, previousQuarterFirstDate, previousQuarterLastDate};
                break;
            }
            // 全年
            case DATA_DATE_TYPE_5: {
                Date today = new Date();
                Date formatDate = StatisticsUtils.formatDate(today, format23h59m59s);
                Date yearFirstDate = StatisticsUtils.getYearFirstDate(today);
                Date lastYearFirstDate = StatisticsUtils.getLastYearFirstDate(today);
                Date lastYearLastDate = StatisticsUtils.getLastYearLastDate(today, false);
                dates = new Date[]{yearFirstDate, formatDate, lastYearFirstDate, lastYearLastDate};
                break;
            }
            // 不展示
            default:
                break;
        }
        return dates;
    }

    /**
     * 获取当月是第几季度
     *
     * @param date
     * @return
     */
    public static int getQuarterByDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int month = calendar.get(Calendar.MONTH);
        return SEASON[month];
    }

    /**
     * 当前是第几季度
     *
     * @return
     */
    public static int getQuarterNow() {
        Date date = new Date();
        return getQuarterByDate(date);
    }

    /**
     * 根据日期返回所在季度的第一个月的第一天的日期
     *
     * @param date
     * @return
     */
    public static Date getQuarterFirstDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MONTH, SEASON[calendar.get(Calendar.MONTH)] * 3 - 3);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        resetHourMinuteSecondMillisecond(calendar, false);
        return calendar.getTime();
    }

    /**
     * 根据日期返回所在季度的最后一个月的最后一天的日期
     *
     * @param date
     * @param format23h59m59s 是否格式化日期,true格式化日期为23:59:59
     * @return
     */
    public static Date getQuarterLastDate(Date date, boolean format23h59m59s) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MONTH, SEASON[calendar.get(Calendar.MONTH)] * 3);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        resetHourMinuteSecondMillisecond(calendar, format23h59m59s);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        return calendar.getTime();
    }


    /**
     * 根据日期返回所在季度的上一个季度的第一个月的第一天的日期
     *
     * @param date
     * @return
     */
    public static Date getPreviousQuarterFirstDate(Date date) {
        Date quarterFirstDate = getQuarterFirstDate(date);
        return getBeforeNMonthDate(quarterFirstDate, 3);
    }

    /**
     * 根据日期返回所在季度的上一个季度的第一个月的第一天的日期
     *
     * @param date
     * @param format23h59m59s 是否格式化日期,true格式化日期为23:59:59
     * @return
     */
    public static Date getPreviousQuarterLastDate(Date date, boolean format23h59m59s) {
        Date quarterLastDate = getQuarterLastDate(date, format23h59m59s);
        return getBeforeNMonthDate(quarterLastDate, 3);
    }

    /**
     * 获取n个月前的日期
     *
     * @param date
     * @param n
     * @return
     */
    public static Date getBeforeNMonthDate(Date date, Integer n) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.MONTH, -n);
        return c.getTime();
    }

    /**
     * 获取某年第一天日期
     *
     * @param date
     * @return
     */
    public static Date getYearFirstDate(Date date) {
        final Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        final int last = calendar.getActualMinimum(Calendar.DAY_OF_YEAR);
        calendar.set(Calendar.DAY_OF_YEAR, last);
        resetHourMinuteSecondMillisecond(calendar, false);
        return calendar.getTime();

    }

    /**
     * 获取年的最后一天日期
     *
     * @param date
     * @param format23h59m59s
     * @return
     */
    public static Date getYearLastDate(Date date, boolean format23h59m59s) {
        final Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        final int last = calendar.getActualMaximum(Calendar.DAY_OF_YEAR);
        calendar.set(Calendar.DAY_OF_YEAR, last);
        resetHourMinuteSecondMillisecond(calendar, format23h59m59s);
        return calendar.getTime();
    }

    /**
     * 获取上年第一天日期
     *
     * @param date
     * @return
     */
    public static Date getLastYearFirstDate(Date date) {
        Date yearFirstDate = getYearFirstDate(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(yearFirstDate);
        calendar.add(Calendar.YEAR, -1);
        return calendar.getTime();
    }

    /**
     * 获取上年最后一天日期
     *
     * @param date
     * @param format23h59m59s
     * @return
     */
    public static Date getLastYearLastDate(Date date, boolean format23h59m59s) {
        Date yearLastDate = getYearLastDate(date, format23h59m59s);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(yearLastDate);
        calendar.add(Calendar.YEAR, -1);
        return calendar.getTime();
    }

    /**
     * 获取指定间隔天数前的时间
     *
     * @param date
     * @param n
     * @return
     */
    public static Date getBeforeNDayDate(Date date, Integer n) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -n);
        return calendar.getTime();
    }

    /**
     * 格式化日期
     *
     * @param date
     * @param format23h59m59s 是否格式化日期,true格式化日期为23:59:59
     * @return
     */
    public static Date formatDate(Date date, boolean format23h59m59s) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        resetHourMinuteSecondMillisecond(calendar, format23h59m59s);
        return calendar.getTime();
    }

    /**
     * 获取本周第一天的日期
     *
     * @param date
     * @return
     */
    public static Date getWeekFirstDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        resetHourMinuteSecondMillisecond(calendar, false);
        // 获得当前日期是一个星期的第几天
        int dayWeek = calendar.get(Calendar.DAY_OF_WEEK);
        if (1 == dayWeek) {
            calendar.add(Calendar.DAY_OF_MONTH, -1);
        }
        // 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        // 获得当前日期是一个星期的第几天
        int day = calendar.get(Calendar.DAY_OF_WEEK);
        // 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
        calendar.add(Calendar.DATE, calendar.getFirstDayOfWeek() - day);
        return calendar.getTime();
    }

    /**
     * 获取上周第一天的日期
     *
     * @param date
     * @return
     */
    public static Date getLastWeekFirstDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(getWeekFirstDate(date));
        resetHourMinuteSecondMillisecond(calendar, false);
        calendar.add(Calendar.DATE, -7);
        return calendar.getTime();
    }

    /**
     * 获取上周最后一天的日期
     *
     * @param date
     * @param format23h59m59s 是否格式化日期,true格式化日期为23:59:59
     * @return
     */
    public static Date getLastWeekLastDate(Date date, boolean format23h59m59s) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(getWeekFirstDate(date));
        resetHourMinuteSecondMillisecond(calendar, format23h59m59s);
        calendar.add(Calendar.DATE, -1);
        return calendar.getTime();
    }

    /**
     * 重置时分秒和毫秒,flag=true:时分秒设置23.59.59
     *
     * @param calendar
     * @param flag
     */
    private static void resetHourMinuteSecondMillisecond(Calendar calendar, boolean flag) {
        if (!flag) {
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.clear(Calendar.MILLISECOND);
        } else {
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            calendar.clear(Calendar.MILLISECOND);

        }
    }

    /**
     * 获取当月第一天的日期
     *
     * @return
     */
    public static Date getMonthFirstDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        resetHourMinuteSecondMillisecond(calendar, false);
        return calendar.getTime();
    }

    /**
     * 获取当月最后一天的日期
     *
     * @param format23h59m59s true:格式化时分秒23.59.59
     * @return
     */
    public static Date getMonthLastDate(Date date, boolean format23h59m59s) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        resetHourMinuteSecondMillisecond(calendar, format23h59m59s);
        return calendar.getTime();
    }

    /**
     * 获取上月第一天的日期
     *
     * @return
     */
    public static Date getLastMonthFirstDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        resetHourMinuteSecondMillisecond(calendar, false);
        calendar.add(Calendar.MONTH, -1);
        return calendar.getTime();
    }

    /**
     * 获得两个日期之间相差的天数
     *
     * @param startDate 起始日期
     * @param endDate   结束日期
     * @return 天数
     */
    public static int getDaysBetween(Date startDate, Date endDate) {
        long start = startDate.getTime() / 1000 / 60 / 60 / 24;
        long end = endDate.getTime() / 1000 / 60 / 60 / 24;
        return (int) (start - end);
    }

    /**
     * 获取日期的下一天
     *
     * @param date
     * @return
     */
    public static Date getNextDate(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, 1);
        return cal.getTime();
    }

    /**
     * 获取上月的最后一天的日期
     *
     * @param format23h59m59s true:格式化时分秒23.59.59
     * @return
     */
    public static Date getLastMonthLastDate(Date date, boolean format23h59m59s) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        resetHourMinuteSecondMillisecond(calendar, format23h59m59s);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        return calendar.getTime();
    }

    public static <T> Map<String, T> initKDateStrVObj(Date startDate, Date endDate, String format, Class clazz) throws Exception {

        int days = getDaysBetween(endDate, startDate);
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Map<String, T> result = new TreeMap<>();
        result.put(sdf.format(startDate), (T) clazz.newInstance());
        Date foreachDate = startDate;
        for (int i = 0; i < days; i++) {
            foreachDate = getNextDate(foreachDate);
            result.put(sdf.format(foreachDate), (T) clazz.newInstance());
        }
        return result;
    }
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!