Flutter Get closest timestamp to now from List

958

Something like this? I am not sure how you are representing your timestamps so I have made the example by using DateTime objects:

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
}

Note, the solution finds the closets timestamp in the list and looks both in the past and future.

Share:
958
Juju
Author by

Juju

Updated on December 22, 2022

Comments

  • Juju
    Juju over 1 year

    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?

    • meditat
      meditat almost 4 years
      it is like finding the second maximum in a list
  • Tobechukwu Ezenachukwu
    Tobechukwu Ezenachukwu almost 2 years
    what if I'm interested in only the closest future timestamps. In your example case, 2020-07-13 will not be considered as it's already in the past.
  • julemand101
    julemand101 almost 2 years
    @TobechukwuEzenachukwu You could just start by filtering out any timestamps that are already in the past. What should happen if there are no timestamp in the future that fits? Should we then still return the closest including the past or should we return null ?