DateTime.Now持续时间+ - 2小时?

时间:2011-08-14 04:59:05

标签: xml silverlight linq datetime

我正在尝试根据日期和小时+ - 2小时显示XML列表。

我目前正在使用此方法:

bool MyDateCheckingMethod(string dateString)
        {



            DateTime otherDate = DateTime.ParseExact(dateString, "yyyyMMddHHmmss K", null);
            // Is this today (Checking Date and Hour)
            return otherDate.Hour == DateTime.UtcNow.Hour &&
            otherDate.Date == DateTime.UtcNow.Date ;



        }

但我想更改此选项,以便在当前时间的2小时内从我的XML中选择列表。

我尝试了以下各种变体,但对DateTime不够了解,无法在此网站上找到任何相关问题,MSDN的DateTime也没有任何相关的示例或信息。

bool MyDateCheckingMethod(string dateString)
        {


            DateTime now = DateTime.UtcNow;

            DateTime otherDate = DateTime.ParseExact(dateString, "yyyyMMddHHmmss K", null);
            // Is this today (Checking Date and Hour)
            return otherDate.Hour == DateTime.UtcNow.Hour &&
            otherDate.Date == DateTime.UtcNow.Date ;
            (otherDate - now).Duration <= TimeSpan.FromHours(2);



        }

1 个答案:

答案 0 :(得分:4)

使用此

bool MyDateCheckingMethod(string dateString)
{
DateTime now = DateTime.UtcNow;
DateTime otherDate = DateTime.ParseExact(dateString, "yyyyMMddHHmmss K", null);

return ( now.AddHours (-2) <= otherDate && otherDate <= now.AddHours (2) );
}