system.formatexception字符串未被识别为有效的日期时间

时间:2015-12-04 05:50:03

标签: c# asp.net

我得到一个FormatException,消息“String未被识别为有效的DateTime”。在以下代码行中:

SqlCommand scmd1 = new SqlCommand("select count(*) Kount  from chequerequests1 where requestdate between '" + DateTime.ParseExact(txtFromDate.Text, "dd-MMM-yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + " 00:00:00.000' and '" + DateTime.ParseExact(txtToDate.Text, "dd-MMM-yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + " 23:59:59.999' group by chequebookstatus", sc);
  • DateFormat是“dd / MM / yyyy”
  • 目前的文化是en-GB
  • 我尝试了各种DateTimeStyles变种,但没效果。

请说明出了什么问题。

感谢。

1 个答案:

答案 0 :(得分:2)

您指定了错误的解析格式:dd-MMM-yyyy 您的文本框采用dd-MM-yyyy格式。

更改格式,传递给ParseExact,它应该有效:

SqlCommand scmd1 = new SqlCommand("select count(*) Kount  from chequerequests1 where requestdate between '" + DateTime.ParseExact(txtFromDate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + " 00:00:00.000' and '" + DateTime.ParseExact(txtToDate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + " 23:59:59.999' group by chequebookstatus", sc);

通常,最好停止连接字符串以构建SQL查询,并开始使用SQL参数。

SqlCommand scmd1 = new SqlCommand("select count(*) Kount from chequerequests1 where requestdate between @dateStart and @dateEnd group by chequebookstatus", sc);

DateTime dtStart = DateTime.ParseExact(txtFromDate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture).StartOfDay();
DateTime dtEnd = DateTime.ParseExact(txtToDate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture).EndOfDay();

scmd1.Parameters.AddWithValue("dateStart", dtStart);
scmd1.Parameters.AddWithValue("dateEnd", dtEnd);