相信很多业务都有各种报表,日报表、月报表、年报表,甚至都有小时、分钟报表。
要生成报表最基本的就是时间列表了,每次用的时候都写方法是不可取的,于是就搞了一个日期的工具类。
后续也会慢慢完善的。
当然了,大家也可以根据我提供的方法按照自己需求进行修改,比如传参、返回值等。
public static List<Date> getAllDatesInRange(Date startDate, Date endDate) {
List<Date> dates = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
while (!calendar.getTime().after(endDate)) {
dates.add(calendar.getTime());
calendar.add(Calendar.DATE, 1);
}
return dates;
}
public static List<Date> getLastDaysOfMonthInRange(Date startDate, Date endDate) {
List<Date> lastDays = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
while (!calendar.getTime().after(endDate)) {
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
lastDays.add(calendar.getTime());
calendar.add(Calendar.MONTH, 1);
}
return lastDays;
}
public static List<Date> getLastDaysOfYearInRange(Date startDate, Date endDate) {
List<Date> lastDays = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
while (!calendar.getTime().after(endDate)) {
calendar.set(Calendar.DAY_OF_YEAR, calendar.getActualMaximum(Calendar.DAY_OF_YEAR));
lastDays.add(calendar.getTime());
calendar.add(Calendar.YEAR, 1);
}
return lastDays;
}
public static List<String> getAllDates(int points, Date endDate, SimpleDateFormat format) {
List<String> timeList = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
calendar.setTime(endDate);
for (int i = 0; i < points; i++) {
calendar.add(Calendar.DATE, -1);
Date day = calendar.getTime();
timeList.add(0, format.format(day));
}
return timeList;
}
public static List<String> getMonthLastDay(int points, Date endDate, SimpleDateFormat format) {
List<String> timeList = new ArrayList<>()
Calendar calendar = Calendar.getInstance();
calendar.setTime(endDate);
for (int i = 0; i < points; i++) {
calendar.add(Calendar.MONTH, -1);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
calendar.set(year, month, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date lastDayOfMonth = calendar.getTime();
timeList.add(0, format.format(lastDayOfMonth));
}
return timeList;
}
public static List<String> getYearLastDay(int points, Date endDate, SimpleDateFormat format) {
List<String> timeList = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
calendar.setTime(endDate);
for (int i = 0; i < points; i++) {
calendar.add(Calendar.YEAR, -1);
int year = calendar.get(Calendar.YEAR);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, Calendar
Date lastDayOfYear = calendar.getTime();
timeList.add(0, format.format(lastDayOfYear));
}
return timeList;
}