views:

109

answers:

4

Need to convert a string to normal datetime format so it can be correctly inserted onto a datetime type field.

String Format:

4/21/2010 4:43:03 PM

Example:

2010-04-21 16:43:03.000

I have clarified question:

The need is to change format and not type.

A: 

If it will always be in the same format, you can use Date.ParseExact(...)

Rowland Shaw
A: 

Assuming you know the exact format of the input data, use DateTime.ParseExact to convert the string to a DateTime (or use DateTimeOffset) - but then don't reformat it into a string.

Use a parameterized query to insert it into your database, instead of putting it directly in the SQL as a string. Using a string to represent values which the database driver has direct support for makes your code brittle for no reason.

Jon Skeet
+1  A: 

"Normal datetime" is a bit vague. Normal format is related to the culture you are running under.

Assuming your original string is parsable in your running culture, and you want to reformat it to the other string in your question you could do this:

DateTime.Parse("4/21/2010 4:43:03 PM").ToString("yyyy-MM-dd HH:mm:ss.ttt")

[Edit - Forget the .ToString() part]

Re-read the question, and using parse will return a DateTime object which can be reused.

Mikael Svenson
A: 

you could do:

CDate("4/21/2010 4:43:03 PM")

or

CType("4/21/2010 4:43:03 PM", DateTime)

or

DateTime.Parse("4/21/2010 4:43:03 PM")
quagland