Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare time values in AM , PM format in C#

Tags:

string

c#

.net

list

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;
like image 756
ZVenue Avatar asked Jan 16 '23 13:01

ZVenue


2 Answers

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");
like image 103
Guvante Avatar answered Jan 25 '23 20:01

Guvante


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;
                    }
                }
            }
like image 37
paparazzo Avatar answered Jan 25 '23 20:01

paparazzo