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

我试图将日期值YYYY / MM / DD从文本框转换为日期时间,当值正确时它是正常的但是当我尝试输入不正确的数据来检查数据库时,错误返回为字符串不是被识别为有效的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 = "
Account Number Exist. You may now proceed with the registration

"; HttpCookie lmsCookie = new HttpCookie("id"); lmsCookie.Value = txtAccountNo.Text; Response.Cookies.Add(lmsCookie); Response.Redirect("Step2.aspx"); } else { Image2.Visible = false; lblMessage.Text = "
Please check your information and try again." + "
Be sure you are entering the correct information.For further assistance, call (+632) 404-2790.

"; } } } }

例如,我将输入一个将在数据库中匹配的数据,程序将继续,否则如果我要输入的数据与数据库中的任何现有记录不匹配,程序将触发错误,String is未被视为有效日期时间。

解析时可能由于错误以外的原因而失败,而不是:

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

(如你所见,抛出一个exception),使用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)) ... 

当然,当尝试将不支持的格式转换为日期时,它会抛出exception。 因此,在转换之前,您应该使用DateTime.TryParse方法解析它。

Sovel,

步骤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