工具方法大杂烩

工具方法大杂烩

听风知秋雨 195 2022-03-31

根据周期拆分时间区间

	/**
	 * 根据周期拆分时间区间
	 * @param startTime
	 * @param endTime
	 * @param cycleDay <p>天数</p>
	 * @return <p>map中每个元素都是一个周期,key为开始时间,value为结束日期</p>
	 * @throws ParseException
	 */
	public LinkedHashMap<String, String> getTimeBetweenByCycle(String startTime, String endTime, long cycleDay) throws ParseException {
        System.out.println("统计的时间段为:从" + startTime + "到" + endTime + " 周期:" + cycleDay + "天");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date startParse = simpleDateFormat.parse(startTime), endParse = simpleDateFormat.parse(endTime);
        long start = startParse.getTime(), end = endParse.getTime();
        long diffDay = (end - start) / 1000 / 60 / 60 / 24;
        long cycle = cycleDay * 24 * 60 * 60 * 1000;

        LinkedHashSet<String> dateSet = new LinkedHashSet();
        String dataStr;
        dateSet.add(startTime);
        if (diffDay > cycleDay) {
            long count = diffDay / cycleDay;
            long index = start;
            for (long i = 0; i < count; i++) {
                index += cycle;
                dataStr = simpleDateFormat.format(new Date(index));
                dateSet.add(dataStr);
            }
            dateSet.add(endTime);
        } else {
            dateSet.add(startTime);
            dateSet.add(endTime);
        }

        LinkedHashMap<String, String> dateMap = new LinkedHashMap();
        // 如果set集合长度为1,代表开始、结束日期相同(其它情况下集合长度必然是偶数)
        List<String> dateList = new ArrayList(dateSet);
        if (dateList.size() == 1) {
            dataStr = dateList.get(0);
            dateMap.put(dataStr, dataStr);
        } else {
            for (int i = 0; i < dateList.size(); i++) {
                if (i == dateList.size() - 1) break;
                dateMap.put(dateList.get(i), dateList.get(i + 1));
            }
        }

        System.out.println(dateSet);
        System.out.println(dateMap);
		return dateMap;
	}