Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the closest time from a list of times

Tags:

So, here's the scenario. I have a file with a created time, and I want to choose a time from a list of times that that file's created time is closest or equal too...what would be the best way to accomplish this?

like image 497
Nick DeMayo Avatar asked Nov 18 '09 16:11

Nick DeMayo


People also ask

How to find the closest date to today on a list in Excel?

Finding the future closest date to today in Excel 1. Select the blank cell B2, copy and paste formula =MIN(IF(A2:A18>TODAY(),A2:A18)) into the Formula Bar, and then press Ctrl + Shift + Enter keys simultaneously. See screenshot: Then you will get the future closest date to today in cell B2.

How do I get the nearest date in C#?

Abs((date - targetDate). Ticks)); var nearest = getAlldates. Where(date => Math. Abs((date - targetDate).


2 Answers

var closestTime = listOfTimes.OrderBy(t => Math.Abs((t - fileCreateTime).Ticks))                              .First(); 

If you don't want the performance overhead of the OrderBy call then you could use something like the MinBy extension method from MoreLINQ instead:

var closestTime = listOfTimes.MinBy(t => Math.Abs((t - fileCreateTime).Ticks)); 
like image 178
LukeH Avatar answered Oct 09 '22 08:10

LukeH


Something like this:

DateTime fileDate, closestDate; ArrayList theDates; long min = long.MaxValue;  foreach (DateTime date in theDates)  if (Math.Abs(date.Ticks - fileDate.Ticks) < min)  {    min = Math.Abs(date.Ticks - fileDate.Ticks);    closestDate = date;  } 
like image 20
luvieere Avatar answered Oct 09 '22 06:10

luvieere