最近项目中用到要用周为单位统计数据,于是需要获得某时间段内的周的时间集合(开始时间和结束时间)
?
class="java" name="code">/** * 获取某时间段内所有周的列表(开始时间,结束时间) * @param startDate * @param endDate * @return */ public static List<String[]> getWeekList(Date startDate,Date endDate){ List<String[]> weekList = new ArrayList<>(); //转换成joda-time的对象 DateTime firstDay = new DateTime(startDate).dayOfWeek().withMinimumValue(); DateTime lastDay = new DateTime(endDate).dayOfWeek().withMaximumValue(); //计算两日期间的区间天数 Period p = new Period(firstDay, lastDay, PeriodType.days()); int days = p.getDays(); if (days > 0){ int weekLength = 7; for(int i=0;i<days;i=i+weekLength){ String monDay = firstDay.plusDays(i).toString("yyyy-MM-dd"); String sunDay = firstDay.plusDays(i+6).toString("yyyy-MM-dd"); String [] week = {monDay,sunDay}; weekList.add(week); } } return weekList; }
?不知道有没有更优写法?