在C#中比较AM,PM格式的时间值

ZVe*_*nue 4 .net c# string list

我有一个时间值列表,格式为"09.00 AM,12.00 PM,03.00 PM"等等.我们称之为ListTimes ..我有一个时间值(testTimeValue),格式相同"xx.xx AM/PM"我正在传递给一个函数.我希望函数将此'testTimeValue'与ListTimes中的每个项进行比较,并返回最接近它的时间.例如:在上面的场景中,如果我将01.00 PM传递给该函数,它应该返回03.00 PM.

foreach (string item in listItems)
{
    //I need to consider the time formats in AM and PM and do a
    //proper comparison and return the closest in original format.                                           
}

return closestTimeValue;
Run Code Online (Sandbox Code Playgroud)

Guv*_*nte 5

每次都跑 DateTime.ParseExact

List<string> listTimes = new List<string>() { "09.00 AM", "12.00 PM", "03.00 PM" };
string testTimeString = "01.00 PM";
DateTime testTime = DateTime.ParseExact(testTimeString, "hh.mm tt", CultureInfo.InvariantCulture);
DateTime closestTime = DateTime.MinValue;
TimeSpan closestDifference = TimeSpan.MaxValue;

foreach (string item in listTimes)
{
    DateTime itemTime = DateTime.ParseExact(item, "hh.mm tt", CultureInfo.InvariantCulture);
    TimeSpan itemDifference = (itemTime - testTime).Duration();

    if (itemDifference < closestDifference)
    {
        closestTime = itemTime;
        closestDifference = itemDifference;
    }
}

return closestTime.ToString("hh.mm tt");
Run Code Online (Sandbox Code Playgroud)