首页 > 解决方案 > Flutter Get closest timestamp to now from List

问题描述

How to get the closest timestamp to now from List?

I got a List of timestamps and I want to determine the closest timestamp in the future to current timestamp.

How can I achieve that?

标签: flutterdarttimestamp

解决方案


像这样的东西?我不确定你是如何表示你的时间戳的,所以我使用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);
  
  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
}

请注意,该解决方案会在列表中找到壁橱时间戳,并查看过去和未来。


推荐阅读