Java 将两个日期的时间段按照一定天数进行周期切割
生活随笔
收集整理的這篇文章主要介紹了
Java 将两个日期的时间段按照一定天数进行周期切割
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?上代碼:
public static List<CycleTimeVo> getCycleList(int cycleNum,String startTime,String endTime) throws ParseException {System.out.println("統(tǒng)計的時間段為:從"+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("兩日期間相隔的天數(shù)為:" + daysBetweenNum);System.out.println("周期選擇是:" + cycleNum + "天一周期, 則切割出來的周期存在個數(shù):" + 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));}測試結果:
第一個參數(shù)為周期的天數(shù),這里示例為7天一個周期切割,
getCycleList(7,"2020-02-01","2020-02-14");可以看到結果正確:
總結
以上是生活随笔為你收集整理的Java 将两个日期的时间段按照一定天数进行周期切割的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 南充一中2021成绩查询高考,2021年
- 下一篇: 仿QQ计步器效果的实现