用于日期检查器ASP.NET的IF语句

时间:2017-03-19 15:01:55

标签: c# asp.net

我正在努力完成一项任务,试图让我的代码检查结束日期必须晚于C#中ASP.NET中的开始日期。老师说:

  

创建一个If语句,以检查开始日期和结束日期是否存在为COMPOUND条件。提示:使用&&amp ;.在这个if语句里面(检查日期差异)

以下是我所拥有的:

 DateTime startDate = DateTime.Parse(Request["txtStartDate"]);
    DateTime endDate = DateTime.Parse(Request["txtEndDate"]);
    if (DateTime.Compare(startDate, endDate) > 0)
    {
        txtStartDate.BackColor = System.Drawing.Color.Yellow;
        txtEndDate.BackColor = System.Drawing.Color.Yellow;
        lblError.Text += "The end date must be a later date than the start date.";
        //The Msg text will be displayed in lblError.Text after all the error messages are concatenated
        bIsFormValid = false;
        //Boolean value - test each textbox to see if the data entered is valid, if not set validState=false. 
        //If after testing each validation rule, the validatedState value is true, then submit to frmPersonnelVerified.aspx, if not, then display error message
    }
    else
    {
        txtStartDate.BackColor = System.Drawing.Color.White;
        txtEndDate.BackColor = System.Drawing.Color.White;
    }


    // Redirect the User to frmStudentConfirmed.aspx
    if (bIsFormValid)
    {
        Response.Redirect("frmPersonnelVerified.aspx");
    }
    else
    {
        Session.Clear();
    }

我收到以下错误:

 An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code. Additional information: String was not recognized as a valid DateTime.

任何帮助将不胜感激。 米格尔

1 个答案:

答案 0 :(得分:0)

似乎问题在于您尝试传递的日期格式

Request["txtStartDate"]

Request["txtEndDate"]

DateTime.Prase静态方法默认接受格式数 https://www.dotnetperls.com/datetime-parse

如果由于某种原因你需要以不同的格式传递日期,请尝试使用

DateTime.ParseExact https://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx