开发者

Convert String to datetime Format

开发者 https://www.devze.com 2022-12-27 22:17 出处:网络
Need to convert a string to normal datetime format so it can be correctly inserted onto a datetime type field.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号