Java给定两组String类型的起止日期,求交集

   
 public static void main(String[] args) {

        List<String> d = dateIntersection("2020.12","2021.01","2020.01","2021.04");

    }


/**
     * 求两个时间段的交集
     * @param startDate
     * @param endDate
     * @param startDate1
     * @param endDate2
     */
    private static List<String> dateIntersection(String startDate, String endDate, String startDate1, String endDate2 ) {
        List<String> list1 = dateList(startDate, endDate);
        List<String> list2 = dateList(startDate1, endDate2);
        return dateIntersection(list1, list2);
    }

    /**
     * 求两个时间段的交集
     * @param list1
     * @param list2
     */
    private static List<String> dateIntersection(List<String> list1, List<String> list2) {
        List<String> result = new ArrayList<>();
        for (int i = 0; i < list1.size(); i++) {
            for (int j = 0; j < list2.size(); j++) {
                if (Objects.equals(list1.get(i),list2.get(j))) {
                    result.add(list1.get(i));
                }

            }
        }
        return result;
    }

    /**
     * 给定一个日期范围,返回其所有年、月的字符串数组,数组值的格式为: yyyy.MM
     * @param startDate
     * @param endDate
     * @return 
     */
    private static List<String> dateList(String startDate, String endDate) {
        List<String> list = new ArrayList<>();
        addDateToList(startDate, endDate, list);
        return list;
    }

    private static void addDateToList(String startDate, String endDate, List<String> list) {
            list.add(startDate);
        if(!Objects.equals(startDate, endDate)) {
            addDateToList(addMonth(startDate), endDate, list);
        }
    }

    /**
     *
     * @param date  一个日期,格式必须为  yyyy.MM
     * @return
     */
    private static String addMonth(String date) {
        String [] dates = date.split("\\.");
        Integer month = Integer.valueOf(dates[1]);
        if(month == 12) {
            Integer year = Integer.valueOf(dates[0]);
            year++;
            dates[0] = year + "";
            month = 1;
        } else {
            month++;
        }
        if(month<10) {
          return dates[0] +".0"+ month;
        } else {
         return dates[0] +"."+ month;
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_38974073/article/details/115497074