views:

53

answers:

2

Hello everyone,

I am using VSTS 2008 + C# + .Net 3.5 + ADO.Net + SQL Server 2008. I have some C# string type variables, and I want to insert them into database as type DateTime, any code samples?

My problem is how to do the conversion from string to database DateTime type.

thanks in advance, George

+4  A: 

Have a look at the DateTime.Parse() method.

Edit: I suppose you use the SqlCommand, then you just add the resulting c# DateTime object to the Parameters collection.

Albin Sunnanbo
...or preferrably TryParse
spender
Thanks, question answered!
George2
+1  A: 

I'd recommend the DateTime.TryParse(string input, out variableName)

Something like this:

DateTime safeDateTime;

if(!DateTime.TryParse("2010-09-15 10:00:00", out safeDateTime))
    safeDateTime = DateTime.MinValue;

Like that you will always have a value in the variable that the database can use. Otherwise you could implement a warning if you couldn't parse the date.

NoLifeKing