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
Use the yyyy-MM-ddTHH:mm:ss. SSS+/-HH:mm or yyyy-MM-ddTHH:mm:ss. SSSZ formats to specify dateTime fields. yyyy is the four-digit year.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With