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 开发者_如何学JAVAquestion:
The need is to change format and not type.
"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.
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.
If it will always be in the same format, you can use Date.ParseExact(...)
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")
精彩评论