DateTime.Compare验证

时间:2015-07-26 03:54:07

标签: asp.net visual-studio

我在DateTime.ParseExact的日期时间验证代码中一直收到此错误,并且不知道问题是什么

“字符串未被识别为有效的DateTime。”

正在从需要验证的文本字段输入字符串startDate和EndDate,并且startDate不能大于endDate。如果没有正确输入日期,如果用户按下提交按钮,则应该抛出错误。

 String startDate = Request["txtStartDate"];
    String endDate = Request["txtEndDate"];
    DateTime start = DateTime.ParseExact(startDate, "MM/dd/yyyy",
                           System.Globalization.CultureInfo.InvariantCulture);
    DateTime end = DateTime.ParseExact(endDate, "MM/dd/yyyy",
                        System.Globalization.CultureInfo.InvariantCulture);
    if (DateTime.Compare(start, end) > 0)
    {
        txtStartDate.BackColor = System.Drawing.Color.Yellow;
        txtEndDate.BackColor = System.Drawing.Color.Yellow;
        Msg = " The end date must be a later date than the start date. ";
        lblError.Text += Msg;
        validatedState = false;

    }
    else
    {
        txtStartDate.BackColor = System.Drawing.Color.White;
        txtEndDate.BackColor = System.Drawing.Color.White;

    }

1 个答案:

答案 0 :(得分:2)

您需要使用DateTime.TryParseExact来首先测试传递的日期时间字符串是否有效。然后,如果未通过验证,则可以提供错误消息。

        String startDate = Request["txtStartDate"];
        String endDate = Request["txtEndDate"];

        DateTime start;
        if (!DateTime.TryParseExact(startDate, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out start))
        {
            txtStartDate.BackColor = System.Drawing.Color.Yellow;
            txtEndDate.BackColor = System.Drawing.Color.Yellow;
            Msg = " The start date is a invalid format.";
            lblError.Text += Msg;
            validatedState = false;
            return;
        }

        DateTime end;
        if (!DateTime.TryParseExact(endDate , "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out end))
        {
            txtStartDate.BackColor = System.Drawing.Color.Yellow;
            txtEndDate.BackColor = System.Drawing.Color.Yellow;
            Msg = " The end date is a invalid format.";
            lblError.Text += Msg;
            validatedState = false;
            return;
        }
        if (DateTime.Compare(start, end) > 0)
        {
            txtStartDate.BackColor = System.Drawing.Color.Yellow;
            txtEndDate.BackColor = System.Drawing.Color.Yellow;
            Msg = " The end date must be a later date than the start date. ";
            lblError.Text += Msg;
            validatedState = false;

        }
        else
        {
            txtStartDate.BackColor = System.Drawing.Color.White;
            txtEndDate.BackColor = System.Drawing.Color.White;

        }