简体   繁体   中英

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

I am passing a datetime value from C# to 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. If I run the SP with the format MM-dd-yyyy , then it is returning the error "Error converting data type nvarchar to datetime.". The SP is

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

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

Would you please let me the the solution

I am passing a datetime value from C# to 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.

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 . for example. SqlCommand , SqlConnection , SqlDataReader etc.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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