mvc 2开始日期和结束日期验证

时间:2012-05-25 07:35:01

标签: c# datetime asp.net-mvc-2

大家好我正在尝试比较两个日期,由于某种原因,如果我指定25/05/2012(startdate)和31/05/12(结束日期),以下代码将返回false。

只有当第25次用作开始日期时才会发生这种情况,如果我使用第26次则可以正常工作。

 public bool IsValidDate(DateTime startDate, DateTime endDate)
    {
        return startDate < endDate && endDate > startDate;
    }

可能出错?

2 个答案:

答案 0 :(得分:2)

你一定是弄错了。对于您指定的给定输入,此代码返回true

class Program
{
    static void Main()
    {
        var startDate = new DateTime(2012, 5, 25);
        var endDate = new DateTime(2012, 5, 31);
        Console.WriteLine(IsValidDate(startDate, endDate));
    }

    public static bool IsValidDate(DateTime startDate, DateTime endDate)
    {
        return startDate < endDate && endDate > startDate;
    }
}

在控制台上打印true

现在当然重复完全相同的条件两次是没有意义的。陈述一次就足够了:

public bool IsValidDate(DateTime startDate, DateTime endDate)
{
    return startDate < endDate;
}

答案 1 :(得分:0)

为什么要创建一个函数来检查startDate < endDate

private void button1_Click(object sender, EventArgs e)
{
    DateTime startDate = new DateTime(2012 , 05 , 25);
    DateTime endDate = new DateTime(2012 , 05 , 31);

    bool rtnval = IsValidDate(startDate, endDate);

}


public bool IsValidDate(DateTime startDate, DateTime endDate)
{
    return startDate < endDate && endDate > startDate; 
}

此代码返回true !!!

将其分解并检查您是否拥有所需的值

public bool IsValidDate(DateTime startDate, DateTime endDate)
{
    bool resulta = startDate < endDate; // break here
    bool resultb = endDate > startDate; // break here
    return startDate < endDate && endDate > startDate;
}

// oops我没有意识到它已被回答