Priya
Priya

Reputation: 591

How to get nearest date?

I have list of dates in a List. The user entered date will be compared with the list of dates.

If the list contains that particular date, then the target date will be that date. If the list does not contain that particular date, then the nearest date should be taken as target date.

For that I tried of using Min in LINQ:

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

But my getAlldates is a list and targetDate is string. So I am getting problem here.

How to resolve this?

Upvotes: 1

Views: 6570

Answers (3)

Leon van Wyk
Leon van Wyk

Reputation: 689

Here's a static method that will return the nearest date.

    /// <summary>
    /// Get the nearest date from a range of dates.
    /// </summary>
    /// <param name="dateTime">The target date.</param>
    /// <param name="dateTimes">The range of dates to find the nearest date from.</param>
    /// <returns>The nearest date to the given target date.</returns>
    static DateTime GetNearestDate(DateTime dateTime, params DateTime[] dateTimes)
    {
        return dateTime.Add(dateTimes.Min(d => (d - dateTime).Duration()));
    }

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 156948

You can simply first parse the string to a DateTime using DateTime.Parse:

var nearestDiff = getAlldates
                  .Select(x => DateTime.Parse(x)) // this one
                  .Min(date => Math.Abs((date - targetDate).Ticks));

Or an improved version, thanks to the input of Gusdor and Jeppe Stig Nielsen:

getAlldates.Min(x => (DateTime.Parse(x) - targetDate).Duration());

You might want to specify the date format or the culture to use parsing if the date format isn't the current culture's one. (You might want to use DateTime.ParseExact for example)

Upvotes: 3

Harald Coppoolse
Harald Coppoolse

Reputation: 30454

You didn't specify but I guess list of dates is a list of System.DateTime objects. If your targetDate object is a string, you can't subtract if from a System.DateTime. The part of code you show won't compile:

List<System.Datetime> allDates = ...;
string targetDate = ...;
var nearestDiff = getAlldates.Min(date => Math.Abs((date - targetDate).Ticks));

To compile it you should convert targetDate into a System.DateTime. If you are certain that the text in targetDate represents a System.DateTime, then you can use System.DateTime.Parse(string) for it, otherwise use TryParse.

The code would loke like:

List<System.Datetime> allDates = ...;
string targetDateTxt = ...;
System.DateTime targetDate = System.DateTime.Parse(targetDateText)
System.DateTime nearestDiff = getAlldates.Min(date => Math.Abs((date - targetDate).Ticks));

From here the rest of your code works

Upvotes: 2

Related Questions