我的日期范围比较不起作用?

时间:2015-07-29 13:42:19

标签: c#

好的目标日期:2015年12月16日应该返回true。不是。

 public bool IsBlockedDay(DateTime dtDate)
    {
        DateTime block1Start = new DateTime(dtDate.Year, 12, 16); //Dec 16
        DateTime block1End = new DateTime(dtDate.Year, 1, 14); //Jan 14

        DateTime block2Start = new DateTime(dtDate.Year, 5, 15); // May 16
        DateTime block2End = new DateTime(dtDate.Year, 8, 14); // Aug 14

       // dateTocheck >= startDate && dateToCheck <= endDate

        if (dtDate >= block1Start && dtDate <= block1End)
        {
            return true;
        }

        if (dtDate >= block2Start && dtDate <= block2End)
        {
            return true;
        }

        return false;
    }

当我评估此功能时,无论出于何种原因,12/16/15都会返回false。它让我疯狂......其他人都看到了这个?

2 个答案:

答案 0 :(得分:3)

您的区块1开始和结束都是向后的。试试这个:

    DateTime block1Start = new DateTime(dtDate.Year, 1, 14); //Jan 14
    DateTime block1End = new DateTime(dtDate.Year, 12, 16); //Dec 16

答案 1 :(得分:0)

创建块1结束时,您需要在年份中添加一个。所以,像:

DateTime block1End = new DateTime(dtDate.Year + 1, 1, 14); //Jan 14

因为您的block1End现在是2015年1月14日。所以当您比较2015年12月16日时,dtDate >= block1Start为真,但dtDate <= block1End自2015年12月16日起不为1月因此,您的方法返回false。应用上面的修复程序会使它返回您期望的内容。