空日期数据补0

1、背景

接口服务中一般对报表或者看板按照年、月维度求和需要对空的日期所对应的数据进行补0,以下是一些处理思路可供借鉴。

2、MySQL查询空日期补0用法
SELECT
	t1.day, COALESCE (t2.cnt, 0) AS cnt
FROM
	(
		SELECT@cdate := date_add(@cdate, INTERVAL - 1 DAY) AS day
		FROM
			(
				SELECT
					@cdate := date_add(CURDATE(), INTERVAL + 1 DAY)
				FROM
					sync_job
			) tmp1
		WHERE
			@cdate > DATE_SUB(CURDATE(), INTERVAL 7 DAY)
	) t1
LEFT JOIN (
SELECT DATE_FORMAT(create_time,'%Y-%m-%d') as day ,count(1) as cnt FROM sync_job
where is_disable = 0  and create_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
group by DATE_FORMAT(create_time,'%Y-%m-%d')
) t2 
ON t1.day = t2.day

--输出
2020-07-10	0
2020-07-09	2
2020-07-08	1
2020-07-07	8
2020-07-06	2
2020-07-05	1
2020-07-04	0
2020-07-03	3

3、代码层面处理查询空日期补0
  • 思路: 使用日期工具类获取指定日期时间内的差值,然后和接口调用返回的结果进行对比,将结果中没有的添加进去并且其count值设置为0,最好以对象的方式如 xxx(time,cnt) 最后以time 排序即可。

以下是工具类:

 public final static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    public final static SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM");

    /**
     * 获取日期差
     *
     * @param start
     * @param end
     * @return
     * @throws Exception
     */
    public static int getDiffDays(String start, String end) throws Exception {
        Date d1 = format.parse(start);
        Date d2 = format.parse(end);
        Long daysBetween = (d2.getTime() - d1.getTime() + 1000000) / (60 * 60 * 24 * 1000);
        return daysBetween.intValue();
    }


    /**
     * 获取过去指定天内的日期数组
     *
     * @param intervals
     * @return
     */
    public static ArrayList<String> getDays(int intervals) {
        ArrayList<String> pastDaysList = new ArrayList<>();
        for (int i = intervals - 1; i >= 0; i--) {
            pastDaysList.add(getPastDate(i));
        }
        return pastDaysList;
    }

    /**
     * 获取月份日期
     *
     * @param past
     * @return
     */
    private static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        String result = format.format(today);
        return result;
    }

    /**
     * 获取年月集合
     *
     * @param intervals
     * @return
     */
    public static Set<String> getYearMonths(int intervals) {
        HashSet<String> pastDaysSets = Sets.newHashSet();
        for (int i = intervals - 1; i >= 0; i--) {
            pastDaysSets.add(getPastDate4Month(i));
        }
        return pastDaysSets;
    }

    /**
     * 获取年份日期
     *
     * @param past
     * @return
     */
    private static String getPastDate4Month(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        String result = format2.format(today);
        return result;
    }

很简单的用法,再此记录下。

你可能感兴趣的:(学习笔记)