Java 计算日期之间 天数 周数 月数 年数 列表


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class DateUtil {
    public static final String YYYYMM = "yyyy-MM";
    public static final String YYYYMMDD = "yyyy-MM-dd";
    public static final String YYYYMMDDHHMMSS = "yyyy-MM-dd HH:mm:ss";

    /**
     * 获取两个时间中连续日期-包含开始时间结束时间所在日期
     *
     * @param startDay yyyy-MM-dd
     * @param endDay   yyyy-MM-dd
     * @return
     */
    public static List<String> getDayList(String startDay, String endDay) {
        List<String> result = new ArrayList<>();
        result.add(startDay.substring(0, 10));
        if (startDay.equals(endDay)) {
            return result;
        }
        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(parseDate(startDay, null));
        tempStart.add(Calendar.DAY_OF_YEAR, 1);

        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(parseDate(endDay, null));
        while (tempStart.before(tempEnd)) {
            result.add(new SimpleDateFormat("yyyy-MM-dd").format(tempStart.getTime()));
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
        }
        result.add(endDay.substring(0, 10));
        return result;
    }

    /**
     * 获取两个时间中连续周数-包含开始时间结束时间所在周数
     *
     * @param startWeek yyyy-0~53
     * @param endWeek   yyyy-1~53
     * @return
     */
    public static List<String> getWeekList(String startWeek, String endWeek) {
        List<String> result = new ArrayList<>();
        int sYear = Integer.parseInt(startWeek.substring(0, 4));// 开始年数
        int sWeek = Integer.parseInt(startWeek.substring(5, 7));// 开始周数
        int eYear = Integer.parseInt(endWeek.substring(0, 4));// 结束年数
        int eWeek = Integer.parseInt(endWeek.substring(5, 7));// 结束周数
        if (sYear == eYear) {// 开始、结束年数为同一年
            while (sWeek <= eWeek) {
                result.add(sYear + "-" + formatIntStr(sWeek));
                sWeek = sWeek + 1;
            }
        } else {// 开始、结束年数非同一年
            int sYearWeekNum = weekNumOfYear(sYear);// 开始年周总数
            while (sWeek <= sYearWeekNum) {// 开始年周数信息
                result.add(sYear + "-" + formatIntStr(sWeek));
                sWeek = sWeek + 1;
            }
            if ((eYear - sYear) > 1) {// 开始、结束年间隔大于 1
                sYear = sYear + 1;
                while (sYear < eYear) {
                    int tempWeekNum = weekNumOfYear(sYear);// 间隔年周总数
                    for (int i = 1; i <= tempWeekNum; i++) {
                        result.add(sYear + "-" + formatIntStr(i));
                    }
                    sYear = sYear + 1;
                }
            }
            for (int i = 1; i <= eWeek; i++) {
                result.add(eYear + "-" + formatIntStr(i));
            }
        }
        return result;
    }

    /**
     * 获取两个时间中连续月份-包含开始时间结束时间所在月份
     *
     * @param startMonth yyyy-MM
     * @param endMonth   yyyy-MM
     * @return
     */
    public static List<String> getMonthList(String startMonth, String endMonth) {
        ArrayList<String> result = new ArrayList<>();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(YYYYMM);//格式化为年月
            Calendar min = Calendar.getInstance();
            Calendar max = Calendar.getInstance();

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

            max.setTime(sdf.parse(endMonth));
            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);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取两个时间中连续年份-包含开始时间结束时间所在年份
     *
     * @param startYear yyyy
     * @param endYear   yyyy
     * @return
     */
    public static List<String> getYearList(String startYear, String endYear) {
        ArrayList<String> result = new ArrayList<>();
        int start = Integer.parseInt(startYear);
        int end = Integer.parseInt(endYear);
        result.add(startYear);
        while (start < end) {
            start++;
            result.add(String.valueOf(start));
        }
        return result;
    }

    /**
     * 时间字符串转换为时间
     *
     * @param strDate
     * @param pattern
     * @return
     */
    public static Date parseDate(String strDate, String pattern) {
        Date date = null;
        try {
            if (pattern == null) {
                pattern = YYYYMMDD;
            }
            SimpleDateFormat format = new SimpleDateFormat(pattern);
            date = format.parse(strDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 获取一年周数
     *
     * @param year
     * @return
     */
    public static int weekNumOfYear(int year) {
        int weekNum = 0;
        int days = 365;
        int day = 0; // 判断是否闰年,闰年366天
        if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
            days = 366;
        }
        // 得到一年所有天数然后除以7
        day = days % 7 > 0 ? weekNum += 1 : weekNum;
        // 得到余下几天如果有余则周+1,否则不加
        weekNum += days / 7;
        //得到多少周
        return weekNum;
    }

    /**
     * 小于 10 数字前补 0
     *
     * @param formatInt
     * @return
     */
    public static String formatIntStr(int formatInt) {
        if (formatInt > 9) {
            return "" + formatInt;
        } else {
            return "0" + formatInt;
        }
    }

    public static void main(String[] args) {
        getDayList("2019-12-25", "2020-01-01").stream().forEach(str -> System.out.println(str));
        getWeekList("2018-50", "2020-05").stream().forEach(str -> System.out.println(str));
        getMonthList("2019-12", "2020-05").stream().forEach(str -> System.out.println(str));
        getYearList("2001", "2020").stream().forEach(str -> System.out.println(str));
    }
}

Mybatis 统计代码:


    <select id="dayReportForm" resultType="java.util.Map">
        SELECT
            date_format(team.dispatch_time, '%Y-%m-%d') AS dayTime,
            COUNT(*) AS teamCountNum
        FROM
            fire_warn_team_rel AS team
        WHERE 1 = 1
            <if test="startTime != null and startTime != ''">
                AND date_format(team.dispatch_time, '%Y-%m-%d') <![CDATA[ >= ]]> #{startTime}
            </if>
            <if test="endTime != null and endTime != ''">
                AND date_format(team.dispatch_time, '%Y-%m-%d') <![CDATA[ <= ]]> #{endTime}
            </if>
            <if test="limitStart != null and limitStart != ''">
                AND date_format(team.dispatch_time, '%Y-%m-%d') <![CDATA[ >= ]]> #{limitStart}
            </if>
            <if test="limitEnd != null and limitEnd != ''">
                AND date_format(team.dispatch_time, '%Y-%m-%d') <![CDATA[ <= ]]> #{limitEnd}
            </if>
        GROUP BY
            date_format(team.dispatch_time, '%Y-%m-%d');
    </select>

    <select id="weekReportForm" resultType="java.util.Map">
        SELECT
            yearweek(team.dispatch_time, 3) AS weekTime,
            COUNT(*) AS teamCountNum
        FROM
            fire_warn_team_rel AS team
        WHERE 1 = 1
            <if test="startTime != null and startTime != ''">
                AND yearweek(team.dispatch_time, 3) <![CDATA[ >= ]]> #{startTime}
            </if>
            <if test="endTime != null and endTime != ''">
                AND yearweek(team.dispatch_time, 3) <![CDATA[ <= ]]> #{endTime}
            </if>
            <if test="limitStart != null and limitStart != ''">
                AND yearweek(team.dispatch_time, 3) <![CDATA[ >= ]]> #{limitStart}
            </if>
            <if test="limitEnd != null and limitEnd != ''">
                AND yearweek(team.dispatch_time, 3) <![CDATA[ <= ]]> #{limitEnd}
            </if>
        GROUP BY
            yearweek(team.dispatch_time, 3);
    </select>

    <select id="monthReportForm" resultType="java.util.Map">
        SELECT
            date_format(team.dispatch_time, '%Y-%m') AS monthTime,
            COUNT(*) AS teamCountNum
        FROM
            fire_warn_team_rel AS team
        WHERE 1 = 1
            <if test="startTime != null and startTime != ''">
                AND date_format(team.dispatch_time, '%Y-%m') <![CDATA[ >= ]]> #{startTime}
            </if>
            <if test="endTime != null and endTime != ''">
                AND date_format(team.dispatch_time, '%Y-%m') <![CDATA[ <= ]]> #{endTime}
            </if>
            <if test="limitStart != null and limitStart != ''">
                AND date_format(team.dispatch_time, '%Y-%m') <![CDATA[ >= ]]> #{limitStart}
            </if>
            <if test="limitEnd != null and limitEnd != ''">
                AND date_format(team.dispatch_time, '%Y-%m') <![CDATA[ <= ]]> #{limitEnd}
            </if>
        GROUP BY
            date_format(team.dispatch_time, '%Y-%m');
    </select>

    <select id="yearReportForm" resultType="java.util.Map">
        SELECT
            date_format(team.dispatch_time, '%Y') AS yearTime,
            COUNT(*) AS teamCountNum
        FROM
            fire_warn_team_rel AS team
        WHERE 1 = 1
            <if test="startTime != null and startTime != ''">
                AND date_format(team.dispatch_time, '%Y') <![CDATA[ >= ]]> #{startTime}
            </if>
            <if test="endTime != null and endTime != ''">
                AND date_format(team.dispatch_time, '%Y') <![CDATA[ <= ]]> #{endTime}
            </if>
            <if test="limitStart != null and limitStart != ''">
                AND date_format(team.dispatch_time, '%Y') <![CDATA[ >= ]]> #{limitStart}
            </if>
            <if test="limitEnd != null and limitEnd != ''">
                AND date_format(team.dispatch_time, '%Y') <![CDATA[ <= ]]> #{limitEnd}
            </if>
        GROUP BY
            date_format(team.dispatch_time, '%Y');
    </select>
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页