/** * 计算分割段数 * * @param period 时段周期 [时|日|周|月] * @param start 开始时间 * @param end 结束时间 * @return 段数 */ private int countDays(Period period, Date start, Date end) { Calendar calendar = Calendar.getInstance(); calendar.setTime(start); int count = 0; while (calendar.getTime().before(end)) { count++; calendar.add(period.getField(), 1); } return count; }
/** * 检测时间分段合理性 * * @param period 时段周期 [时|日|周|月] * @param start 开始时间 * @param end 结束时间 */ private void doCheckPeriod(Period period, Date start, Date end) throws ServiceException { Calendar calendar = Calendar.getInstance(); calendar.setTime(start); int count = 0, max = 200; while (calendar.getTime().before(end)) { if (count++ > max) { throw new ServiceException("数据量偏大,请调整时间跨度再试!"); } calendar.add(period.getField(), 1); } }
/** * 填充数据 * * @param list 数据库有效数据列表 * @return 填充的数据 */ private <T extends TrendValue> List<T> fulldata( List<T> list, DateFormat format, int field, Date start, Date end, Class<T> clazz) { Map<String, T> map = tomap(list); Calendar calendar = Calendar.getInstance(); calendar.setTime(start); List<T> nlist = new ArrayList<>(); while (calendar.getTime().before(end)) { String keytime = format.format(calendar.getTime()); T value = map.get(keytime); if (value == null) { value = AfReflecter.newInstance(clazz); value.setEmpty(); value.setDate(keytime); value.setTime(calendar.getTime()); nlist.add(value); } else { nlist.add(value); map.remove(keytime); } calendar.add(field, 1); } for (Map.Entry<String, T> entry : map.entrySet()) { nlist.add(entry.getValue()); } return nlist; }
/** * 根据周期和便宜计算结束时间 * * @param end 结束时间 * @param span 时间跨度 * @param offset 偏移 * @return 结束时间 */ private Date timeEnd(Date end, Period span, Integer offset) { if (span != null && offset != null /* && !Period.hour.equals(span)*/) { DateFormat format = span.getFormat(); Calendar calendar = Calendar.getInstance(); try { calendar.setTime(format.parse(format.format(calendar.getTime()))); } catch (ParseException e) { e.printStackTrace(); } calendar.add(span.getField(), offset + 1); return calendar.getTime(); } if (end == null) { return timeEnd(new Date(), Period.year, 1000); } return end; }
/** * 根据周期和便宜计算开始时间 * * @param start 开始时间 * @param span 时间跨度 * @param offset 偏移 * @return 开始时间 */ private Date timeStart(Date start, Period span, Integer offset) { if (span != null && offset != null) { DateFormat format = span.getFormat(); Calendar calendar = Calendar.getInstance(); try { calendar.setTime(format.parse(format.format(calendar.getTime()))); } catch (ParseException e) { e.printStackTrace(); } calendar.add(span.getField(), offset); return calendar.getTime(); } if (start == null) { return timeStart(new Date(), Period.year, -1000); } return start; }