c# – 如何测试DateTime是否在星期二之间(DayOfWeek)

前端之家收集整理的这篇文章主要介绍了c# – 如何测试DateTime是否在星期二之间(DayOfWeek)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在C#中,给出一组任意的DayOfWeek终点(如DayOfWeek.Friday和DayOfWeek.Sunday),如果一个任意日期是在两天之间,包含在内的怎么样呢?

例:

// result == true; Oct 23,2010 is a Saturday
var result = InBetweenDaysInclusive(new DateTime(2010,10,23),DayOfWeek.Friday,DayOfWeek.Sunday);

// result == true; Oct 22,2010 is a Friday
result = InBetweenDaysInclusive(new DateTime(2010,22),DayOfWeek.Sunday);

// result == true; Oct 24,2010 is a Sunday
result = InBetweenDaysInclusive(new DateTime(2010,24),DayOfWeek.Sunday);

// result == false; Oct 25,2010 is a Monday
result = InBetweenDaysInclusive(new DateTime(2010,25),DayOfWeek.Sunday);

谢谢!

解决方法

根据开始和结束日期之间的差异是负数还是正/零,此函数将需要两个独立的分支.

我可以完全脱离基地,但我认为这适用于所有情况:

// No state in method,so made it static
public static bool InBetweenDaysInclusive(DateTime date,DayOfWeek start,DayOfWeek end)
{
    DayOfWeek curDay = date.DayOfWeek;

    if (start <= end)
    {
        // Test one range: start to end
        return (start <= curDay && curDay <= end);
    }
    else
    {
        // Test two ranges: start to 6,0 to end
        return (start <= curDay || curDay <= end);
    }
}

作为参考,当我运行它时,您的测试数据返回以下内容,并为每个结果添加了Console.WriteLine:

True
True
True
False

编辑:我最后的解释太模糊了.这是一个固定的.

诀窍在于,开始,那么你有两个有效的范围:开始上限和下限结束.这将导致(开始< = curDay&& curDay< = upperBound)|| curDay< = end&&& lowerBound< = curDay) 然而,由于它们是边界,所以curDay总是< = upperBound和> = lowerBound,因此我们省略了该代码.

原文链接:https://www.f2er.com/csharp/95621.html

猜你在找的C#相关文章