记一次将时间段分成时间片段集合

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/xuruanshun/article/details/102723566

场景:开发中遇到一个场景,传入开始时间和结束时间,获取大量日志数据。

问题:当传入的时间间距是三个月时,就可以获取到数据,但如果超出三个月,就会报时间超时,因为数据库的日志量比较大,一次性在数据库查询大量数据容易超时,而且因为业务逻辑问题,所以没法做分页。所以想出一个办法,将传入到时间段,切割成多个时间片段,再通过循环的方式处理业务,获取到所有的日志数据。

 将开始日期和结束日期之间的时间段,分成三个月一组的map集合

    // 将开始日期和结束日期之间的时间段,分成三个月一组的map集合
    public static HashMap<String,String> spiltDateToMonth(Date beginDate,Date endDate){

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 日期集合
        HashMap<String,String> dateMap = new LinkedHashMap<>();
        // 临时开始时间和临时结束时间
        Date tempBeginDate = beginDate;
        Date tempEndDate = null;

        while (true){
            // 临时结束日期为临时开始日期的三个月之后
            tempEndDate = getAfterMonth(tempBeginDate,3);

            // 如果临时结束日期在结束日期之前,此时间段的结束时间为临时结束时间
            if(tempEndDate.compareTo(endDate) <= 0){
                String tempBeginDateStr = simpleDateFormat.format(tempBeginDate);
                String tempEndDateStr = simpleDateFormat.format(tempEndDate);
                dateMap.put(tempBeginDateStr,tempEndDateStr);
                // 如果临时结束日期在结束日期之后,则最后一个时间段的结束时间为结束时间
            }else {
                String tempBeginDateStr = simpleDateFormat.format(tempBeginDate);
                String tempEndDateStr = simpleDateFormat.format(endDate);
                dateMap.put(tempBeginDateStr,tempEndDateStr);
                break;
            }
            // 此一时间段的结束时间是下一个时间段的开始时间
            tempBeginDate = tempEndDate;
        }
        return dateMap;
    }


    /***
     * 获取几个月之后的日期
     * @param inputDate
     * @param number
     * @return
     */
    public static Date getAfterMonth(Date inputDate,int number) {
        if(inputDate == null){
            return null;
        }
        Calendar c = Calendar.getInstance();//获得一个日历的实例
        c.setTime(inputDate);//设置日历时间
        c.add(Calendar.MONTH,number);//在日历的月份上增加6个月
        Date date = c.getTime();
        return date;
    }

测试类:

   public static void main(String[] args) throws ParseException {
        String beginTime = "2014-08-15 10:22:22";
        String endTime   = "2015-10-15 10:10:10";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date bt = sdf.parse(beginTime);
        Date et = sdf.parse(endTime);

        HashMap<String, String> dateMap = spiltDateToMonth(bt, et);
        for (Map.Entry<String, String> entry : dateMap.entrySet()) {
            System.out.println(entry.getKey() + "==========" + entry.getValue());
        }
    }

控制台:

猜你喜欢

转载自blog.csdn.net/xuruanshun/article/details/102723566