需求
在开发项目过程中,系统的首页需要统计一天内每个小时接口调用量,这就需要获取一天内所有的小时时间。
代码
/**
* 获取一段时间范围内所有时分时间,[01:00, 02:00, 03:00, ...]
*/
public static List<String> getTimes(Date fromDate, Date toDate) {
List<String> times = new ArrayList<>();
List<Date> hourlyInterval = getHourlyInterval(fromDate, toDate);
for (Date date : hourlyInterval) {
String dateStr = DateUtil.toString(date, "HH:00");
times.add(dateStr);
}
Collections.sort(times);
return times;
}
private static List<Date> getHourlyInterval(Date fromDate, Date toDate) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(fromDate);
List<Date> hourlyInterval = new ArrayList<>();
hourlyInterval.add(calendar.getTime());
while (calendar.getTime().before(toDate)) {
calendar.add(Calendar.HOUR_OF_DAY, 1);
hourlyInterval.add(calendar.getTime());
}
return hourlyInterval;
}
/**
* 调用
*/
List<String> times = DateUtil.getTimes(DateUtil.addDays(new Date(), -1), new Date());
System.out.println(times);
打印结果
[00:00, 01:00, 02:00, 03:00, 04:00, 05:00, 06:00, 07:00, 08:00, 09:00, 10:00, 11:00, 11:00, 12:00, 12:00, 13:00, 14:00, 15:00, 16:00, 17:00, 18:00, 19:00, 20:00, 21:00, 22:00, 23:00]