比较C#中AM,PM格式的时间值 [英] Compare time values in AM , PM format in C#

查看:383
本文介绍了比较C#中AM,PM格式的时间值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个时间值列表,格式为"09.00 AM,12.00 PM,03.00 PM"等.让我们将其称为ListTimes. 我有一个单一时间值(testTimeValue),与传递给函数的格式相同,格式为"xx.xx AM/PM". 我希望函数将此"testTimeValue"与ListTimes中的每个项目进行比较,并返回与其最接近的时间.例如:在上述情况下,如果我将01:00 PM传递给该函数,则应返回03.00 PM.

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;

推荐答案

每次都运行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");

这篇关于比较C#中AM,PM格式的时间值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆