我有一个时间值列表,格式为“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;
每次运行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");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)