繁体   English   中英

DateTime.Parse将字符串转换为DateTime格式等于数据库中的DateTime字段

[英]DateTime.Parse Converting String to DateTime Format Equals to DateTime Field in Database

我试图将文本框中的YYYY / MM / DD日期值转换为datetime,当该值正确时就可以了,但是当我尝试输入不正确的数据来检查数据库时,错误返回为String确认为有效的DateTime。

这是我的代码:

  protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string format = "YYYY-MM-DD HH:MM:SS";
        DateTime birthday = DateTime.Parse(txtBday.Text);
        DataSet ds = new DataSet();
        ds = (newService.checkAccount());
        if (ds.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow dRow in ds.Tables[0].Rows)
            {
                string accountNo = dRow["ACCTNO"].ToString();
                DateTime birthDate = DateTime.Parse(dRow["DATEOFBIRTH"].ToString());
                if (accountNo == txtAccountNo.Text.ToString() && birthDate == birthday)
                {
                    lblMessage.Text = "<br>Account Number Exist. You may now proceed with the registration<br><br>";
                    HttpCookie lmsCookie = new HttpCookie("id");
                    lmsCookie.Value = txtAccountNo.Text;
                    Response.Cookies.Add(lmsCookie);
                    Response.Redirect("Step2.aspx");
                }
                else
                {
                    Image2.Visible = false;
                    lblMessage.Text = "<br>Please check your information and try again." + "<br>Be sure you are entering the correct information.For further assistance, call (+632) 404-2790.<br><br>";
                }
            }
        }
    }

例如,我将输入将在数据库中匹配的数据,否则程序将继续执行;否则,如果我要输入与数据库中任何现有记录都不匹配的数据,则程序将触发错误,字符串为无法识别为有效的日期时间。

当您解析可能由于错误而不是其他原因而失败时,请执行以下操作:

DateTime birthDate = DateTime.Parse(dRow["DATEOFBIRTH"].ToString())

(如您所见,这会引发异常),请使用DateTime.TryParse

DateTime birthDate;
if (DateTime.TryParse(dRow["DATEOFBIRTH"].ToString(), out birthDate))
{
    // Success case
}
else
{
    // Handle error case
}

顺便说一句,我注意到您没有使用 format变量。 如果您知道格式是什么(并且您的问题与您的代码不同,顺便说一句),最好使用TryParseExact

if (DateTime.TryParseExact(dRow["DATEOFBIRTH"].ToString(), "YYYY/MM/dd",
                           CultureInfo.InvariantCulture, DateTimeStyles.None,
                           out birthDate))
...

索维尔

第1步:

this._checkInOutDTO.NgayCham = DateTime.Parse(this.DGVDuLieuVaoRa.Rows [num15] .Cells [1] .Value.ToString()); // this._checkInOutDTO.NgayCham = Convert.ToDateTime(this.DGVDuLieuVaoRa.Rows [num15] .Cells [1] .Value.ToString());

第2步:格式:dd / MM / yyyy

无疑,当尝试将不受支持的格式转换为日期时间时,它将引发异常。 因此,在转换之前,应使用DateTime.TryParse方法对其进行解析。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM