构造小时和天数的时间Map并返回:
有时候我们查询数据库数据的时候,按天数或者按小时查询的话,会出现某些天数或者小时没有数据的情况,这个时候我们就需要手动的去填充数据,下面的代码为构造一个以时间或者天数为键的Map,然后我们可以把查询出来的数据按时间加入到Map中,然后再去遍历Map,没有值的说明数据库没有查询到数据,然后进行数据的填充即可。
补充说明: 这里就是提供一个思路,简单来说就是用时间为键,来构造一个Map,可以用时间对应的时间戳,也可以用时间对应的字符串,只要能达到目的即可。
public Map<Long, PassengerInfo> structureTimeMap(String startTime, String endTime, Integer mode) {
SimpleDateFormat timeFormat = null;
//格式化传入的时间,传入的字符串格式为yyyy-MM-dd HH:mm:ss,可以通过下面的方法进行天或者小时数据的格式化
if (mode == 0) {
timeFormat = new SimpleDateFormat("yyyy-MM-dd");
} else {
timeFormat = new SimpleDateFormat("yyyy-MM-dd HH");
}
Map<Long, PassengerInfo> map = new LinkedHashMap<>();
try {
Date date = timeFormat.parse(startTime);
Long dayStart = date.getTime();
date = timeFormat.parse(endTime);
Long dayEnd = date.getTime();
while (true) {
if (dayStart >= dayEnd) {
map.put(dayStart, null);
break;
}
map.put(dayStart, null);
if (mode == 0) {
//时间增加1天
dayStart += 86400000;
} else {
//时间增加1个小时
dayStart += 3600000;
}
}
} catch (ParseException px) {
logger.error("客流数据查询构造map失败");
px.printStackTrace();
}
return map;
}