How to get nearest date?

﹥>﹥吖頭↗ 提交于 2019-12-24 16:58:58

问题


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?


回答1:


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)




回答2:


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




回答3:


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()));
    }


来源:https://stackoverflow.com/questions/31647822/how-to-get-nearest-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!