You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取两个LocalDate之间包含的所有YearMonth值

获取日期范围内包含的所有月份(Java实现)

方式一:生成YearMonth类型的列表

利用Java 8+的java.timeAPI可以简洁实现,核心思路是从起始日期对应的YearMonth开始,逐月递增,直到覆盖结束日期对应的YearMonth:

import java.time.LocalDate;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.List;

public class MonthRangeExtractor {
    public static List<YearMonth> getYearMonthsInRange(LocalDate startDate, LocalDate endDate) {
        List<YearMonth> yearMonths = new ArrayList<>();
        YearMonth current = YearMonth.from(startDate);
        YearMonth end = YearMonth.from(endDate);
        
        while (!current.isAfter(end)) {
            yearMonths.add(current);
            current = current.plusMonths(1);
        }
        return yearMonths;
    }

    public static void main(String[] args) {
        LocalDate startDate = LocalDate.of(2020, 1, 1);
        LocalDate endDate = LocalDate.of(2024, 1, 31);
        
        List<YearMonth> result = getYearMonthsInRange(startDate, endDate);
        result.forEach(System.out::println);
    }
}

这段代码会输出从2020-01到2024-01的所有YearMonth实例,自动处理跨年度、单月范围等边界场景。

方式二:生成字符串格式的月份列表

如果需要直接输出类似yyyy-MM格式的字符串,只需在循环中对YearMonth做格式化转换即可:

import java.time.LocalDate;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.List;

public class MonthStringRangeExtractor {
    public static List<String> getMonthStringsInRange(LocalDate startDate, LocalDate endDate) {
        List<String> monthStrings = new ArrayList<>();
        YearMonth current = YearMonth.from(startDate);
        YearMonth end = YearMonth.from(endDate);
        
        while (!current.isAfter(end)) {
            monthStrings.add(current.toString()); // 默认格式为yyyy-MM
            // 也可自定义格式,比如:
            // monthStrings.add(current.format(DateTimeFormatter.ofPattern("yyyy年MM月")));
            current = current.plusMonths(1);
        }
        return monthStrings;
    }

    public static void main(String[] args) {
        LocalDate startDate = LocalDate.of(2020, 1, 1);
        LocalDate endDate = LocalDate.of(2024, 1, 31);
        
        List<String> result = getMonthStringsInRange(startDate, endDate);
        result.forEach(System.out::println);
    }
}

关键逻辑说明

  • YearMonth.from(LocalDate):将日期转换为对应的年月对象,自动忽略日部分,不管起始/结束日期是当月的哪一天,都能正确匹配到所属月份。
  • current.plusMonths(1):安全的月份递增,自动处理跨年(比如2023-12递增后是2024-01)。
  • !current.isAfter(end):循环终止条件,确保包含结束日期所在的月份。

内容的提问来源于stack exchange,提问作者Stan Ostrovskii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 09:42:09