Click here to Skip to main content
15,662,459 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a DateTime value as string, the date format may be different each time.
How to convert this string to DateTime?
Updated 6-May-15 3:41am

You can see if DateTime.TryParse converts it for you, or you can try DateTime.TryParseExact with a list of possible formats one by one until one works. I'd advise against using DateTime.Parse or DateTime.ParseExact as they will raise exceptions if the conversion fails.

In general you should avoid allowing users to enter dates in any format. Either use separate day\month\year boxes or a date picker etc. In some cases you might just have to accept that the date is wrong if the user doesn't follow your preferred convention, eg is 1\2\2015 Jan 2nd or Feb 1st? You can never tell unless you set the locale and format.
Share this answer
Sergey Alexandrovich Kryukov 6-May-15 11:30am    
Share this answer
Sergey Alexandrovich Kryukov 6-May-15 11:30am    
You are missing TryParse, TryParseExact and ParseExact.
Use DateTime.Parse() function to convert String into DateTime format.

<br />
string strTime ="Wed, 06 May 2015 07:11:21 GMT";<br />
DateTime time = DateTime.Parse(strTime);<br />

Refer the link for more detailed information[^]
Share this answer
M. Daban 6-May-15 10:47am    
this may throw exception according to your system date format
MayurDighe 13-Jul-15 14:33pm    
DO you try it..?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900