Java 将两个日期的时间段按照一定天数进行周期切割
上代码:
public static List<CycleTimeVo> getCycleList(int cycleNum,String startTime,String endTime) throws ParseException {
System.out.println("统计的时间段为:从"+startTime+"到"+endTime);
Date endParse = new SimpleDateFormat("yyyy-MM-dd").parse(endTime);
Long endLong = endParse.getTime();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//这个是你要转成后的时间的格式
endTime = sdf.format(new Date(endLong));
System.out.println("结束时间是:"+endTime);
int daysBetweenNum = daysBetween(startTime, endTime);
int cycleForNum = daysBetweenNum % cycleNum == 0 ? (daysBetweenNum / cycleNum) : (daysBetweenNum / cycleNum) + 1;
System.out.println("两日期间相隔的天数为:" + daysBetweenNum);
System.out.println("周期选择是:" + cycleNum + "天一周期, 则切割出来的周期存在个数:" + cycleForNum);
Date startParse = new SimpleDateFormat("yyyy-MM-dd").parse(startTime);
Long startLong = startParse.getTime();
Long calculationLong = startLong;
List<CycleTimeVo> CycleTimeList=new ArrayList();
for (int i = 1; i <= cycleForNum; i++) {
String startStr = sdf.format(new Date(calculationLong));
Date startStrParse = new SimpleDateFormat("yyyy-MM-dd").parse(startStr);
Long startStrLong = startStrParse.getTime();
Long cycleLong = cycleNum*86400000l;
calculationLong = startStrLong + cycleLong;
String endStr = endTime;
if (calculationLong <= endLong) {
endStr = sdf.format(new Date(calculationLong));
}
System.out.println("起始:" + startStr + "结束:" + endStr);
CycleTimeVo cycleTimeVo=new CycleTimeVo();
cycleTimeVo.setStartTimeStr(startStr);
cycleTimeVo.setEndTimeStr(endStr);
CycleTimeList.add(cycleTimeVo);
}
System.out.println("周期list:"+CycleTimeList.toString());
return CycleTimeList;
}
public static int daysBetween(String smdate, String bdate) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(smdate));
long time1 = cal.getTimeInMillis();
cal.setTime(sdf.parse(bdate));
long time2 = cal.getTimeInMillis();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(between_days));
}
测试结果:
第一个参数为周期的天数,这里示例为7天一个周期切割,
getCycleList(7,"2020-02-01","2020-02-14");
可以看到结果正确: