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

Flutter:如何判断列表中DateTime是否为对应月份的最后日期?

实现日期列表的月末最后日期判断函数

核心思路

要判断传入的日期是不是对应月份在列表里的最后一个,只需要两步:

  1. 从列表里筛选出和传入日期年月完全一致的所有日期
  2. 找到这些日期里的最大值(也就是当月最后一个),再和传入日期对比

Dart/Flutter 代码实现

bool isLastDateOfMonthInList(DateTime targetDate, List<DateTime> dateList) {
  // 1. 筛选出同一年月的所有日期
  final sameMonthDates = dateList.where((date) => 
    date.year == targetDate.year && 
    date.month == targetDate.month
  ).toList();

  // 如果当月没有任何日期,直接返回false
  if (sameMonthDates.isEmpty) return false;

  // 2. 找到当月列表里的最后一个日期(最大的日期)
  final lastDateInMonth = sameMonthDates.reduce((a, b) => a.isAfter(b) ? a : b);

  // 3. 对比目标日期和当月最后日期是否一致
  // 注意:DateTime比较要忽略时分秒,只看年月日
  return targetDate.year == lastDateInMonth.year &&
         targetDate.month == lastDateInMonth.month &&
         targetDate.day == lastDateInMonth.day;
}

注意事项

  • 代码里特意忽略了DateTime的时分秒部分,避免因为时间戳不同导致判断错误
  • 如果列表里没有对应月份的日期,函数会直接返回false,你可以根据需求改成抛出异常或者其他逻辑
  • 测试的时候可以用你给出的例子,比如列表里7月最后一个是23.07,传入23.07就会返回true,传入其他7月日期则返回false

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:45:44