假设起止日期为 起: 2023-11-08 止: 2025-11-08
获取月份:
第一种情况: 不包含起始时间, 循环获取日期范围内每个月固定号日期
例子: 获取2023-12-08 2024-01-08 2024-02-08 选择几号可以自行改变;
/**
* 获取指定日期范围内的每个月的指定号日期
* @param startDate 开始日期
* @param endDate 结束日期
* @return
*/
public static List<LocalDate> getDatesInRange(LocalDate startDate, LocalDate endDate, int day) {
List<LocalDate> dates = new ArrayList<>();
LocalDate currentDate = startDate;
while (currentDate.isBefore(endDate) || currentDate.equals(endDate)) {
// 如果当前日期是固定号,则添加到列表中
if (currentDate.getDayOfMonth() == day) {
dates.add(currentDate);
}
currentDate = currentDate.plusDays(1);
}
return dates;
}
第二种情况: 包含起始时间, 循环获取日期范围内每个月固定号日期
例子: 获取2023-11-08 2023-12-08 2024-01-08
/**
* 获取指定日期范围内的每个月的固定号日期
* @param startDate 开始日期
* @param endDate 结束日期
* @return 包含每个月固定号日期的列表
*/
public static List<LocalDate> getDatesInRange(LocalDate startDate, LocalDate endDate, int day) {
List<LocalDate> dates = new ArrayList<>();
LocalDate currentDate = startDate;
// 首先添加起始年份的固定号日期
dates.add(currentDate);
while (currentDate.isBefore(endDate) || currentDate.equals(endDate)) {
// 如果当前日期是固定号,则添加到列表中
if (currentDate.getDayOfMonth() == day) {
dates.add(currentDate);
}
currentDate = currentDate.plusDays(1);
}
return dates;
}
获取年份:
获取指定日期范围内每个年份的固定号日期
/** 测试 其中payRecord为实体类, 该业务是计算用户需缴纳维保年费,并设置提前提醒天数*/
public static void main(String[] args) {
int num = Integer.parseInt(payRecord.getRemindDate());//提前提醒天数
LocalDate startDate = DateUtils.toLocalDate(payRecord.getStartDate());
LocalDate endDate = DateUtils.toLocalDate(payRecord.getEndDate());
List<LocalDate> range = DateUtils.getYearDatesInRange(startDate, startDate.minusDays(num),
endDate, endDate.minusDays(num).getDayOfMonth());
}
/**
* 获取指定日期范围内每个年份的固定号日期
* @param startDate 开始日期
* @param startMinusDate 开始日期计算后提前日期
* @param endDate 结束日期
* @return 包含每个年份固定号日期的列表
*/
public static List<LocalDate> getYearDatesInRange(LocalDate startDate, LocalDate startMinusDate, LocalDate endDate, int day) {
List<LocalDate> dates = new ArrayList<>();
LocalDate currentDate = startDate;
// 首先添加起始年份的固定号日期
dates.add(startMinusDate);
while (currentDate.isBefore(endDate) || currentDate.equals(endDate)) {
// 如果当前日期是固定号,则添加到列表中
if (currentDate.getDayOfMonth() == day) {
dates.add(currentDate);
}
// 移动到下一个年份的固定号日期
currentDate = currentDate.plusYears(1).withDayOfMonth(day);
}
return dates;
}