书接上回,由于上次的写法都是纯原生的,这次就借助一些轮子(hutool工具类)完善一下
输入: "2023-03-01", "2023-07-02", 10 输出: "2023-03-01", "2023-03-10", "2023-04-10", "2023-05-10", "2023-06-10", "2023-07-02" 具体实现
public static List<String> getDatePeriodFromRange(String startDateStr, String endDateStr, int day) {
//指定转换格式
List<String> dateStrList = new ArrayList<>();
//开始和结束时间转换
LocalDate start = LocalDateTimeUtil.parseDate(startDateStr, DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate end = LocalDateTimeUtil.parseDate(endDateStr, DateTimeFormatter.ISO_LOCAL_DATE);
//获取开始和结束时间的年月 格式"uuuu-MM"
YearMonth from = YearMonth.from(start);
YearMonth to = YearMonth.from(end);
for (long i = 0; i <= ChronoUnit.MONTHS.between(from, to); i++) {
YearMonth yearMonth = from.plusMonths(i);
int dayTemp = day;
//判断指定的日期是否能和年月构成有效日期
if (!yearMonth.isValidDay(day)) {
//不符合则返回该月的最后一天
dayTemp = yearMonth.lengthOfMonth();
}
//拼接完整的日期
String format = StrUtil.format("{}-{}", Convert.toStr(yearMonth),
StrUtil.padPre(Convert.toStr(dayTemp), 2, "0"));
dateStrList.add(format);
}
//对于拼接后的日期进行一次筛选 保证拼接的日期是在开区间(startDateStr,endDateStr)
List<String> result = dateStrList.stream()
.filter(s -> {
LocalDate sdate = LocalDateTimeUtil.parseDate(s, DateTimeFormatter.ISO_LOCAL_DATE);
return (sdate.isAfter(start) && sdate.isBefore(end));
}).collect(Collectors.toList());
//最后再加上开始和结束时间 形成闭区间[startDateStr,endDateStr]
result.add(0, startDateStr);
result.add(endDateStr);
return result;
}