Java操作数据库中查询出来的数据,补齐缺少的日期和数据

背景:
需要写一个折线图(展示每一天数量的多少),但是数据库中一些日期对应的数量是不存在数据的(即当天无数据)。所以当讲数据查出来后,需要对数据进行填充。

逻辑背景:
查出来的时间数据形式为:xxxx-xx-xx
页面表现出来的折线图需要完成的逻辑为:近一周(当前时间往前7天)、近一月(当前时间往前30天)

当日期不存在时,将日期填充,并添加数量为0

需要完成:
编写一个通用方法,将日期以及对应的数量补全

方法说明:
1、参数说明:
mapList内保存的数据格式为:[string类型的日期,BigInteger类型的天数]
start:开始日期
day:需要填充到day天前

2、逻辑说明:
获取到最开始的日期(eg:今天为14号,近一周则最开始为7号),此日期与查询出来的数据的第一天进行对比,若相同,不处理;若不同,操作查询出来的这个数据(数组),设置第一条(角标为0)数据为查询的日期,并且设置数据为0。获得第二天数据,进行相同操作(递归)

public static List<Object[]> addPolyLineData(List<Object[]> mapList,String start,int day) {
    
    
		int i = 0;//游标作用,标记位置
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String nextDay = getDateAfter(start, 1);
        Date toDay = new Date();
        String today = format.format(toDay);
        if(!start.equals(today) && i < day){
    
    
            if (mapList.size() == i){
    
    
                Object[] obj = new Object[]{
    
    start,BigInteger.valueOf(0)};
                mapList.add(i,obj);
            }else {
    
    
                String dayList= (String) mapList.get(i)[0];//获得第i个数据的日期
                if (dayList.isEmpty() && dayList.equals("")){
    
    
                    Object[] obj = new Object[]{
    
    start,BigInteger.valueOf(0)};
                    mapList.add(i,obj);
                }else{
    
    
                    if(!start.equals(dayList)){
    
    
                        Object[] obj = new Object[]{
    
    start,BigInteger.valueOf(0)};
                        mapList.add(i,obj);
                    }
            }
            }
            i++;
            addPolyLineData(mapList,nextDay,i,day);//递归调用
        }
        return mapList;
    }

方法说明:
方法为返回指定日期(dd,字符串格式),day天后日期(返回字符串格式)

public static String getDateAfter(String dd, int day) {
    
    
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Calendar now = Calendar.getInstance();
    Date d = null;
    try {
    
    
        d = format.parse(dd);
    } catch (ParseException e) {
    
    
        e.printStackTrace();
    }
    now.setTime(d);
    now.set(Calendar.DATE, now.get(Calendar.DATE) + day);//+后 -前
    return format.format(now.getTime());
}

方法说明:
方法为返回当前日期past天后日期(字符串格式)

public 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();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    String result = format.format(today);
    return result;
}

代码为个人浅见,欢迎指正。

猜你喜欢

转载自blog.csdn.net/weixin_42656358/article/details/105635322