Click here to Skip to main content
14,427,436 members
Rate this:
Please Sign up or sign in to vote.
See more:
The column named "updated_at" in my table has datetime2(0) datatype and there is a variable named "_updated_at" in my code-behind has datatype "DateTime".

DateTime _updated_at=System.DateTime.Now;

How to convert System.DateTime.Now into "datetime2(0)"

I tried the following but still the casting exception is thrown saying Conversion failed when converting date and/or time from Character string.

I am using MS-SQL Server 2014.

What I have tried:

DateTime _updated_at =(DateTime)System.DateTime.Now;
Posted
Updated 15-Jan-20 6:55am
Rate this:
Please Sign up or sign in to vote.

Solution 1

You don't need the cast: DateTime.Now already returns a DateTime value, so a cast is redundant.

The error message refers to a character string:
Conversion failed when converting date and/or time from Character string.
Which means that you are passing the DateTime value to your DB by concatenation strings:
string sql = "UPDATE MyTable SET Updated_At='" + _updated_at + "'";
And that is what is causing your problem because the string you pass is being interpreted incorrectly by SQL, And you should be glad it is, because the chances are it would have worked two days ago, but stored the wrong values into your DB.

Never 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. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
DROP TABLE MyTable;
A perfectly valid "delete the table" command
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

Fix that throughout your app, and the problem you have noticed will go at the same time.
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

DateTime _updated_at=DateTime.Now;

........
.......

cmd.Parameters.Add("@updated_at", SqlDbType.DateTime2).Value = _updated_at;
   

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100