Tuesday 2 July 2013

How to calculate the closest date to now in a collection using C#

there are a lot of unnecessarily over-complicated ways out there showing different ways of doing this so I thought I'd post what I think is the simplest and best solution for this.

Just a bit of context first: my scenario is that I want to find out which files in the collection that I have the closest publishing date to today based on the date set on the filet set they belong to.

 var now = DateTime.Now;
                
var closestDiff  = activeFiles.Min(x => Math.Abs((x.Fileset.PublishDate - now).Ticks));

                files = activeFiles.Where(x => Math.Abs((x.Fileset.PublishDate - now).Ticks) == closestDiff  ).ToList();

one important pointer:

make sure to save the DateTime.Now or whatever date you're comparing to in a variable first if you are using a dynamic date like that.

Don't forget that milliseconds count when dealing with datetime so you if you just use that statement inline the code will never match anything since the Ticks result will be different in the next code line and the closestDiff won't match anything


               

No comments:

Post a Comment