Click here to Skip to main content
15,888,351 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?
Posted
Updated 6-May-15 3:41am
v2

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
 
Comments
Sergey Alexandrovich Kryukov 6-May-15 11:30am    
5ed.
—SA
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 6-May-15 11:30am    
You are missing TryParse, TryParseExact and ParseExact.
—SA
Use DateTime.Parse() function to convert String into DateTime format.

E.g.
C#
<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
http://www.dotnetperls.com/datetime-parse[^]
 
Share this answer
 
Comments
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