这本书接上来了,因为上次写的都是纯原生的,所以这次借助一些轮子(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; }