Click here to Skip to main content
15,893,564 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Exception
the conversion of varchar datatype to a datetime data type resulted in an out-of-range value

ColumnName DataType
Col1 DateTime


public DateTime CurrentDateTime
{
get
{
return DateTime.Now.ToString(dd/MM/yyyy HH:mm:ss);
}
}

return 27/05/2014 21:16:33

Working well in access not in sql

in sql show exception

Help me
Posted

1 solution

Why, I wonder are you doing that?
C#
public DateTime CurrentDateTime
    {
        get
            {
            return DateTime.Now.ToString(dd/MM/yyyy HH:mm:ss);
            }
    }

Since you want a DateTime value, why are you converting it to a string and returning that?
That code won't even compile - you will get a "Cannot implicitly convert type 'string' to 'System.DateTime'" error.

So, lets ignore that and look at what you are doing that is even worse...

Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
The only reason you get an error is because you are converting a DateTime to a string and passing that string to SQL, which is converting it back to a DateTime, and failing - because it is expecting a different format. Now, you could "fix" that by converting the DateTime to an ISO DateTime format, but that would leave the rest of your code vulnerable to anyone you want's to type destructive things in...

Use Parameterized queries throughout, and you can pass the DateTime as a DateTime, no conversion is needed. And your database becomes less at risk...
 
Share this answer
 
Comments
[no name] 27-May-14 12:01pm    
5 because veryhelpfull and complete.
Manamohan Jha 27-May-14 12:39pm    
How to solve by simple query????/
crazie.coder 28-May-14 2:46am    
good explation..
can use
return DateTime.Now;
no need to set date formate ,it will automatically take MM/dd/yyyy HH:mm:ss format and SQL also aceept it as well...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900