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

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

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

 

 将开始日期和结束日期之间的时间段,分成三个月一组的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());
        }
    }

 

控制台:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值