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

Dart/Flutter中如何获取两个日期之间的月份列表

Dart 实现两个日期间的月份列表方案

核心实现思路

  • 先将两个输入日期的「日」字段统一重置为当月1号,消除具体日期数值对年月判断的干扰,只保留年、月两个维度做比较
  • 从起始日期对应的年月开始循环,每次递增1个月,利用Dart DateTime自动处理跨年进位的特性(比如12月+1自动变为下一年1月),直到当前年月超过结束日期对应的年月就终止循环
  • 循环过程中按照M/yyyy的格式拼接年月字符串,收集到结果列表即可

完整可运行代码

List<String> getMonthRange(DateTime startDate, DateTime endDate) {
  final monthList = <String>[];
  // 归一化日期,统一取当月1号,屏蔽日维度影响
  var currentMonth = DateTime(startDate.year, startDate.month, 1);
  final endMonth = DateTime(endDate.year, endDate.month, 1);

  // 循环到当前月份超过结束月份为止
  while (!currentMonth.isAfter(endMonth)) {
    monthList.add('${currentMonth.month}/${currentMonth.year}');
    // 月份+1,自动处理跨年逻辑
    currentMonth = DateTime(currentMonth.year, currentMonth.month + 1, 1);
  }

  return monthList;
}

// 测试验证
void main() {
  // 对应示例输入:20/12/2011、22/08/2012
  final date1 = DateTime(2011, 12, 20);
  final date2 = DateTime(2012, 8, 22);
  final result = getMonthRange(date1, date2);
  result.forEach(print);
}

运行输出结果

12/2011
1/2012
2/2012
3/2012
4/2012
5/2012
6/2012
7/2012
8/2012

和需求给出的预期结果完全一致。

补充说明

  • 如果原始输入是dd/MM/yyyy格式的日期字符串,可以通过intl包的DateFormat('dd/MM/yyyy').parse(日期字符串)先转成DateTime类型再传入方法
  • 如果存在传入的起始日期晚于结束日期的场景,可以在方法开头先做日期比较,将更早的日期设为循环起点,避免返回空列表
  • 跨时区使用场景下,建议将DateTime构造替换为DateTime.utc(...),规避时区偏移导致的月份计算错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 07:06:24