1.由于传入的查询年月可能是不固定的所以首先需要将开始和结束日期中间的所有的日期利用代码获取。
public static List<String> getMonthBetweenDate(String startTime, String endTime) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
// 声明保存日期集合
List<String> list = new ArrayList<>();
try {
// 转化成日期类型
Date startDate = sdf.parse(startTime);
Date endDate = sdf.parse(endTime);
//用Calendar 进行日期比较判断
Calendar calendar = Calendar.getInstance();
while (startDate.getTime() <= endDate.getTime()) {
// 把日期添加到集合
list.add(sdf.format(startDate));
// 设置日期
calendar.setTime(startDate);
//把月数增加 1
calendar.add(Calendar.MONTH, 1);
// 获取增加后的日期
startDate = calendar.getTime();
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
根据开始结束时间年月日获取中间的每一天的日期
/**
* 获取两个日期字符串之间的日期集合
* @param startTime:String
* @param endTime:String
* @return list:yyyy-MM-dd
*/
public static List<String> getBetweenDate(String startTime, String endTime){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// 声明保存日期集合
List<String> list = new ArrayList<String>();
try {
// 转化成日期类型
Date startDate = sdf.parse(startTime);
Date endDate = sdf.parse(endTime);
//用Calendar 进行日期比较判断
Calendar calendar = Calendar.getInstance();
while (startDate.getTime()<=endDate.getTime()){
// 把日期添加到集合
list.add(sdf.format(startDate));
// 设置日期
calendar.setTime(startDate);
//把日期增加一天
calendar.add(Calendar.DATE, 1);
// 获取增加后的日期
startDate=calendar.getTime();
}
} catch (ParseException e) {
e.printStackTrace();
}
return list;
}
现根据查询添加查询出数据库中已经存在的数据集合,然后根据日期进行循环,判断是否存在月份,如果存在则不需要处理,如果不存在则需要将日期和补0的数据插入到集合中,最后根据月份将列表进行排序即可。
//调用工具栏获取日期列表
List<String> monthBetweenDate = TimeUtil.getMonthBetweenDate(startTime, endTime);
//查询数据列表
List<Map<String, Object>> count = Amapper.getCountInputHospital(startTime, endTime);
//循环日期列表进行判断
for(String month:monthBetweenDate){
//根据日期判断查询的数据列表中是否存在
boolean countInput = count.stream().filter(m -> m.get("month").equals(month)).findAny().isPresent();
//判断如果不存在则进行补齐操作
if(!countInput){
Map<String, Object> input=new HashMap<>();
input.put("count",0);
input.put("month",month);
count .add(input);
}
}
//根据时间字段进行排序处理
count= count.stream().sorted(new Comparator<Map<String, Object>>() {
@Override
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
return o1.get("month").toString().compareTo(o2.get("month").toString());
}
}).collect(Collectors.toList());