C# 从字符串转换日期和/或时间时,日期时间转换失败

C# 从字符串转换日期和/或时间时,日期时间转换失败,c#,sql,winforms,C#,Sql,Winforms,我正在尝试运行以下简单的SQL查询,以选择两个日期之间的数据。日期来自以下日期时间选择器:DTP\u from,DTP\u To DateTime startDate = DTP_From.Value.Date; DateTime endDate = DTP_To.Value.Date; SqlConnection con = new SqlConnection(strConnection); con.Open();

我正在尝试运行以下简单的SQL查询,以选择两个日期之间的数据。日期来自以下日期时间选择器:
DTP\u from
DTP\u To

        DateTime startDate = DTP_From.Value.Date;
        DateTime endDate = DTP_To.Value.Date;
        SqlConnection con = new SqlConnection(strConnection);
        con.Open();
        SqlCommand sqlCmd = new SqlCommand();
        sqlCmd.Connection = con;
        sqlCmd.CommandType = CommandType.Text;
        sqlCmd.CommandText = "SELECT * From Report_Sales where Date >= '" + startDate + "' AND Date <= '" + endDate + "'";
DateTime startDate=DTP_From.Value.Date;
DateTime endDate=DTP_To.Value.Date;
SqlConnection con=新的SqlConnection(strConnection);
con.Open();
SqlCommand sqlCmd=新的SqlCommand();
sqlCmd.Connection=con;
sqlCmd.CommandType=CommandType.Text;

sqlCmd.CommandText=“SELECT*From Report_Sales where Date>=”“+startDate+””和Date参数化您的查询以避免类似问题

sqlCmd.CommandText = "SELECT * From Report_Sales where Date >= @startDate AND Date <= @endDate";
sqlCmd.Parameters.AddWithValue("@startDate", startDate);
sqlCmd.Parameters.AddWithValue("@endDate", endDate);

sqlCmd.CommandText=“SELECT*From Report_Sales where Date>=@startDate AND Date如果您不遵循Grant Winney的优秀建议来参数化您的查询,这也将帮助您避免其他问题;要将
DateTime
数据包含到Transact-SQL查询中,需要使用ISO 8601样式对其进行格式化:

YYYY-MM-DDThh:MM:ss.nnn[Z]

选择*
来自销售报告
其中日期>='2014-04-18T21:26:01Z'

和日期我希望使用“Between”关键字而不是>=并将日期转换为“yyyy-MM-dd HH:MM”格式。并确保开始日期的时间必须为00:00,结束日期的时间必须为23:29,否则将不会显示某些记录。
SELECT *
FROM Report_Sales
WHERE Date >= '2014-04-18T21:26:01Z'
AND Date <= '2014-04-18T22:26:01Z'