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

修改Dart代码:获取列表中当前时间之后的最近DateTime

解决Dart中获取当前时间之后最近DateTime的问题

我原本用以下Dart代码从DateTime列表里查找和本地时间最接近的DateTime,代码能正常运行,但现在需求变了:不想把过去的时间作为结果,只想要当前时间之后的最近DateTime。比如当前时间是23:00时,列表里最近的是22:58,但我要跳过这个,选之后最近的那个时间。

原代码

void main() {
  final dateTimes = <DateTime>[
    DateTime(2020, 8, 1),
    DateTime(2020, 8, 5),
    DateTime(2020, 7, 13),
    DateTime(2020, 7, 18),
    DateTime(2020, 8, 15),
    DateTime(2020, 8, 20)
  ];
  final now = DateTime(2020, 7, 14);
  
  final closetsDateTimeToNow = dateTimes.reduce(
      (a, b) => a.difference(now).abs() < b.difference(now).abs() ? a : b);

  print(closetsDateTimeToNow); // 2020-07-13 00:00:00.000
}

修改后的解决方案

要实现需求,分两步操作:

  • 先过滤掉列表中所有早于(或等于)当前时间的DateTime,只保留未来的时间
  • 在剩下的未来时间里,找到最早的那个,就是当前时间之后最近的DateTime

如果列表中没有未来时间,建议添加边界处理(比如返回提示),避免报错。

修改后的代码如下:

void main() {
  final dateTimes = <DateTime>[
    DateTime(2020, 8, 1),
    DateTime(2020, 8, 5),
    DateTime(2020, 7, 13),
    DateTime(2020, 7, 18),
    DateTime(2020, 8, 15),
    DateTime(2020, 8, 20)
  ];
  final now = DateTime(2020, 7, 14);

  // 筛选出所有当前时间之后的DateTime
  final futureDates = dateTimes.where((date) => date.isAfter(now)).toList();
  
  if (futureDates.isEmpty) {
    print('列表中没有未来的时间');
    return;
  }

  // 在未来时间中找到最早的那个(即离当前时间最近的)
  final nearestFutureDate = futureDates.reduce((a, b) => a.isBefore(b) ? a : b);

  print(nearestFutureDate); // 2020-07-18 00:00:00.000
}

代码说明

  • where((date) => date.isAfter(now)):通过条件筛选,只保留当前时间之后的DateTime
  • futureDates.reduce((a, b) => a.isBefore(b) ? a : b):在筛选后的列表中,通过reduce方法找出最早的时间,也就是离当前时间最近的未来时间
  • 增加空列表判断,防止所有时间都在过去时出现运行异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 08:42:39