项目中遇到了这样一个问题:页面有时间控件,用来选择开始时间和结束时间,开始时间(start) 结束时间(end),为图表的显示提供时间参数,图表以月份为单位来显示,需求中遇到了这样的问题,我的图表要显示的数据为1月到12月的,可是中间有几个月是没有数据的,没有数据月份就不会显示,为了防止月份不显示的问题,我只好再new 一个新list用来补上没有的月份:
代码:
public String getAnotherName(List<Ddsj> newList,List<Ddsj> list,String start,String end){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
Date date1;
Date date2;
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
try{
date1 = sdf.parse(start);
date2 = sdf.parse(end);
c1.setTime(date1);
c2.setTime(date2);
catch(ParseException e){
e.printStackTrace();
}
int year = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
int month = c2.get(Calendar.MONTH) - c1.get(Clendar.MONTH);
Ddsj ddsj1 = new Ddsj();//new空对象
//ddsj1.setXXX();
StringBuffer sb = new StringBuffer();
for(int i=0;i<month+(year*12);i++){
c1.setTime(date1);
c1.add(Calendar.Month,i);//加月份
String date_str = sdf.format(c1.getTime());
sb.append(date_str+",");
boolean has = true;//判断条件,如果为真则是查询出的list中当前这个月份没有数据(即没有当前这个月份)
for(Ddsj d : list){
if(d.getYf().equals(date_str)){//如果查询出的月份跟当前外面循环的月份相等
newList.add(d);
has = false;
break;//有相同的月份,就跳出内循环
}
}
if(has){//如果为true则是在list中没有与当前循环中的月份相等的
newList.add(ddsj1);
}
}
String res_str = sb.toString();
if(sb.length()>0){
res_str = res_str.subString(0,res_str.length()-1);
}
return res_str;
}
本文介绍了一种在图表展示中确保所有月份数据均被显示的方法。通过创建一个新列表来补充原始数据中缺失的月份,使得图表能完整展示1月至12月的数据,即使某些月份没有实际数据。

被折叠的 条评论
为什么被折叠?



