flutter - 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?
解决方案
像这样的东西?我不确定你是如何表示你的时间戳的,所以我使用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
}
请注意,该解决方案会在列表中找到壁橱时间戳,并查看过去和未来。
推荐阅读
- ruby-on-rails - Ruby Convert string into undescore,避免结果字符串中的“/”
- typescript - 在带有无服务器框架的 AWS Lambda 中将 AWS v3 开发工具包与 Webpack 捆绑在一起?
- postgresql - 如何防止并发函数调用?
- java - 带有 ObjectInputStream 的 EOFException
- javascript - Vue 3 组合 API - 数组的 ref() 与 reactive()
- c++ - 动态分配指向对象的指针数组
- firebase - 使用自定义域的功能进行托管重写不起作用
- java - 骆驼路线未得到识别,在运行应用程序时,启动了 0 条路线中的 0 条
- tensorflow - 为什么 keras 中的 accuracy 和 binary_accuracy 有相同的结果?
- node.js - 当站点项目文件上传到服务器时,如果项目的节点模块通常添加到.gitignore,它们如何仍然工作?