Search code examples
c#listlinquipathuipath-studio

Finding closest date from a list of dates comparing to DateTime.Now


I am trying get the closest date from a list of DateTime. I want to compare the DateTime item present in the list to DateTime.Now and get the closest date.

So far I tried: DateTime.Compare(item, DateTime.Now) but this doesn't work in UiPath as I am unable to find Just DATE type in the UiPath.


Solution

  • With Linq, you can run into an issue with lazy evaluation. In this case since you are using time objects and DateTime.Now, that could be a very bad thing, as the Linq expresion may not evaluate for a return value until the value is required by other code. This may not be an issue for you, and other users have answered on this post for the Linq version. Otherwise, the tried and true For loop approach like in the method below will solve the issue, and return a Datetime object for later use.

    public DateTime ReturnClosest(List<DateTime> dateTimes)
    {
        //Establish Now for simpler code below
        var now = DateTime.Now;
    
        //Start by assuming the first in the list is the closest
        var closestDateToNow = dateTimes[0];
    
        //Set up initial interval value, accounting for dates before and after Now
        TimeSpan shortestInterval = now > dateTimes[0] ? now - dateTimes[0] : dateTimes[0] - now;
    
        //Loop through the rest of the list and correct closest item if appropriate
        //Note this starts at index 1, which is the SECOND value, we've evaluated the first above
        for (var i = 1; i < dateTimes.Count; i++)
        {
            TimeSpan testinterval = now > dateTimes[i] ? now - dateTimes[i] : dateTimes[i] - now;
    
            if(testinterval < shortestInterval)
            {
                shortestInterval = testinterval;
                closestDateToNow = dateTimes[i];
            }
        }
    
        //return the closest Datetime object
        return closestDateToNow;
    }