I have a list of time values in this format "09.00 AM, 12.00 PM, 03.00 PM" etc..lets call it ListTimes.. I have a single time value (testTimeValue) in the same format "xx.xx AM/PM" that I am passing to a function. I want the function to compare this 'testTimeValue' to each item in the ListTimes and return the closest time to it. For example : In the above scenario, if I pass 01.00 PM to the function, it should return 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;
For each time, run 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");
First I trust the data type is DateTime
List<DateTime> dates = new List<DateTime>();
dates.Add(DateTime.Parse("9/11/2001 1:00 PM"));
dates.Add(DateTime.Parse("9/11/2001 10:00 AM"));
dates.Add(DateTime.Parse("9/11/1002 3:00 PM"));
DateTime dateComp = DateTime.Parse("9/11/2001 11:00 AM");
DateTime? dateClosest = null;
foreach (DateTime dt in dates)
{
if (dateClosest == null) dateClosest = dt;
else
{
if( (dateComp.Subtract(dt).TotalMilliseconds) <
dateComp.Subtract((DateTime)dateClosest).TotalMilliseconds)
{
dateClosest = dt;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With