根据日,周,月三个维度统计数据,2拆分周,3拆分月
/**
* 2周 3月
* 根据时间段拆分出自然周和月时间段
* type
* @param type
* @param map
* @return
* @throws ParseException
*/
public static List<String> splitDateByType(Integer type, Map<String, Object> map) throws ParseException {
List<String> resList = new ArrayList<>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String startDate = (String)map.get("startTime");
String endDate = (String)map.get("endTime");
Date sDate = dateFormat.parse(startDate);
Calendar sCalendar = Calendar.getInstance();
sCalendar.setFirstDayOfWeek(Calendar.SUNDAY);
sCalendar.setTime(sDate);
Date eDate = dateFormat.parse(endDate);
Calendar eCalendar = Calendar.getInstance();
eCalendar.setFirstDayOfWeek(Calendar.SUNDAY);
eCalendar.setTime(eDate);
boolean firstFlag =true;
if(type.equals(2)){
while(sCalendar.getTime().getTime()<eCalendar.getTime().getTime()){
if(firstFlag||sCalendar.get(Calendar.DAY_OF_WEEK) == 2||sCalendar.get(Calendar.DAY_OF_WEEK) == 1){
resList.add(dateFormat.format(sCalendar.getTime()));
firstFlag = false;
}
sCalendar.add(Calendar.DAY_OF_MONTH, 1);
}
resList.add(dateFormat.format(eCalendar.getTime()));
if(resList.size()%2 != 0){
resList.add(dateFormat.format(eCalendar.getTime()));
}
}else{
while(sCalendar.getTime().getTime()<eCalendar.getTime().getTime()){
if(firstFlag||sCalendar.get(Calendar.DAY_OF_MONTH)==1||sCalendar.get(Calendar.DAY_OF_MONTH)==sCalendar.getActualMaximum(Calendar.DAY_OF_MONTH)){
resList.add(dateFormat.format(sCalendar.getTime()));
if((sCalendar.get(Calendar.DAY_OF_MONTH)==sCalendar.getActualMaximum(Calendar.DAY_OF_MONTH)) && firstFlag){
resList.add(dateFormat.format(sCalendar.getTime()));
}
firstFlag = false;
}
sCalendar.add(Calendar.DAY_OF_MONTH, 1);
}
resList.add(dateFormat.format(eCalendar.getTime()));
if(resList.size()%2 != 0){
resList.add(dateFormat.format(eCalendar.getTime()));
}
}
return resList;
}
测试代码:
public static void main(String[] args) throws ParseException{
Map<String, Object> map = new HashMap<>();
String startTime = "2021-08-31";
String endTime = "2021-09-30";
map.put("startTime", startTime);
map.put("endTime", endTime);
System.out.println(splitDateByType(3, map));
}
type为2:
[2021-08-31, 2021-09-05, 2021-09-06, 2021-09-12, 2021-09-13, 2021-09-19, 2021-09-20, 2021-09-26, 2021-09-27, 2021-09-30]
type为3:
[2021-08-31, 2021-08-31, 2021-09-01, 2021-09-30]