Codex73
Codex73

Reputation: 5766

Convert String to datetime Format

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.

Upvotes: 0

Views: 1009

Answers (4)

Beno
Beno

Reputation: 4753

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")

Upvotes: 0

Mikael Svenson
Mikael Svenson

Reputation: 39695

"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.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503120

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.

Upvotes: 1

Rowland Shaw
Rowland Shaw

Reputation: 38129

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

Upvotes: 0

Related Questions