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

Flutter中如何获取两个日期之间的所有日期列表

实现代码
List<DateTime> getDays({required DateTime start, required DateTime end}) {
  // 入参合法性校验,若开始时间大于等于结束时间直接返回空列表
  if (start.isAfter(end) || start.isAtSameMomentAs(end)) {
    return [];
  }
  List<DateTime> result = [];
  DateTime current = start;
  while (current.isBefore(end)) {
    result.add(current);
    // 步进1整天
    current = current.add(const Duration(days: 1));
  }
  return result;
}
效果验证

你提供的测试用例调用后,输出完全符合要求:

List<DateTime> days = getDays(
  start: DateTime.parse('2021-10-25 12:00:00'),
  end: DateTime.parse('2021-10-28 12:00:00'),
);
// 输出结果:
// [
//   2021-10-25 12:00:00.000,
//   2021-10-26 12:00:00.000,
//   2021-10-27 12:00:00.000
// ]
注意事项
  • 上述实现默认保留传入DateTime的时分秒、时区信息,不会额外做日期截断
  • 如果业务场景需要忽略时分秒,仅按自然日期维度统计,可以在比较前通过DateTime(current.year, current.month, current.day)对日期做清零处理
  • 若涉及时区、夏令时等特殊场景,可以将循环判断条件改为直接比对年月日的数值,避免Duration步进出现的时间偏移问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:45:08