List中有连续的日期则将首尾设置为startDate、endDate,否则startDate=endDate=独立的日期

在实际的业务场景中,时间为一个集合例如

List list = Arrays.asList("2022-11-19","2022-11-20","2022-11-21","2022-07-20");

那么期望得到的list为

[{endDate=2022-11-21, startDate=2022-11-19}, {endDate=2022-07-20, startDate=2022-07-20}]

然后就可以循环list 获取开始和截至时间 使用了

工具类


    public static List> getTime( List list) {
        //初始化list,且该list中的日期是升序的。
        //List list = Arrays.asList("2020-11-19","2020-11-20","2020-11-21","2021-07-20");
       /* List list = Arrays.asList("2021-07-02", "2021-07-03", "2021-07-04", "2021-07-06",
                "2021-07-07", "2021-07-08", "2021-07-09", "2021-07-11", "2021-07-12",
                "2021-07-13", "2021-07-14", "2021-07-16", "2021-07-17", "2021-07-18",
                "2021-07-19", "2021-07-20", "2021-07-21", "2021-07-22", "2021-07-23",
                "2021-07-24", "2021-07-25", "2021-07-26", "2021-07-27", "2021-07-28",
                "2021-07-29", "2021-07-30");
        */
        List> arrayList = new ArrayList<>();
        int num = 0;
        for (int i = 0; i < list.size(); i = num) {
            String start = list.get(i);
            String end = "";
            if (i == list.size() - 1) {
                end = start;
            }
            int n = 0;
            for (int j = i + 1; j < list.size(); j++) {
                //判断当前日期的后一天与list中该元素的下一个元素是否相等
                if (getSpecifiedDayAfter(list.get(j - 1)).equals(list.get(j))) {
                    end = list.get(j);
                    n++;
                    num++;
                    continue;
                } else {
                    //list中该元素不是连续的
                    if (n == 0) {
                        end = list.get(j - 1);
                    }
                    break;
                }
            }
            num = num + 1;
            HashMap map = new HashMap<>();
            map.put("startDate", start);
            map.put("endDate", end);
            arrayList.add(map);
        }

        return arrayList;
}

    /**
     * 获取当前日期的后一天
     * @param specifiedDay
     * @return
     */
    public static String getSpecifiedDayAfter(String specifiedDay) {
        Calendar c = Calendar.getInstance();
        Date date = null;
        try {
            date = new SimpleDateFormat("yyyy-MM-dd").parse(specifiedDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day + 1);
        String dayAfter = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        return dayAfter;
    }

转载:若List中有连续的日期则将首尾设置为startDate、endDate,否则startDate=endDate=独立的日期

你可能感兴趣的:(Java笔记,java)