简体   繁体   English

字符串未被识别为对SQL Server的有效DateTime C#

[英]String was not recognized as a valid DateTime C# to Sql server

I am passing a datetime value from C# to SQL Server SP. 我正在将datetime值从C#传递到SQL Server SP。 If I pass the format dd-MM-yyyy then it is working fine but not returning any values from SP even there are records of that date. 如果我传递的格式为dd-MM-yyyy那么它可以正常工作,但即使有该日期的记录,也不会从SP返回任何值。 If I run the SP with the format MM-dd-yyyy , then it is returning the error "Error converting data type nvarchar to datetime.". 如果我以MM-dd-yyyy格式运行SP,则它将返回错误“将数据类型nvarchar转换为datetime时出错”。 The SP is SP是

execute usp_detData '22/12/2012 00:00:00', '31/12/2013 23:59:59' --- error execute usp_detData '22/12/2012 00:00:00', '31/12/2013 23:59:59' ---错误

execute usp_detData '12/22/2012 00:00:00', '12/31/2013 23:59:59' --- working fine execute usp_detData '12/22/2012 00:00:00', '12/31/2013 23:59:59'工作正常

Would you please let me the the solution 请让我解决方案

I am passing a datetime value from C# to SQL Server SP. 我正在将datetime值从C#传递到SQL Server SP。

I believe you are passing it via string concatenation. 我相信您是通过字符串串联传递它的。 Its better if you use SqlParameter of type DateTime and let the server handle it. 如果使用DateTime类型的SqlParameter并让服务器处理它,则更好。

using (SqlCommand cmd = new SqlCommand(" usp_detData", conn))
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@StartDate", DateTime.Now.AddDays(-10));
    cmd.Parameters.AddWithValue("@EndDate", DateTime.Now);
    SqlDataReader dr = cmd.ExecuteReader();
    .....
}

Also consider using the using block in your code with objects which implements IDisposable . 还可以考虑将代码中的using块与实现IDisposable的对象一起使用 for example. 例如。 SqlCommand , SqlConnection , SqlDataReader etc. SqlCommandSqlConnectionSqlDataReader

Try this : 尝试这个 :

DateTime.ParseExact("12/02/21 10:56:09", "dd/MM/YYYY HH:mm:ss", 
    CultureInfo.InvariantCulture
    ).ToString("MMM. dd, yyyy HH:mm:ss")

or go through this question Convert DateTime to a specified Format 或经历此问题将DateTime转换为指定的格式

使用格式“ yyyy-MM-dd HH:mm:ss”,一切都会好起来的。

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

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