I have a string 20100524 (2010 05 24) and I would like to parse it as an actual date format.
Asked
Active
Viewed 398 times
4 Answers
16
This will do it for you in a safe manner:
DateTime dateTime;
if (DateTime.TryParseExact("20100524", "yyyyMMdd", null, DateTimeStyles.None, out dateTime))
{
// use dateTime here
}
else
{
// the string could not be parsed as a DateTime
}

Fredrik Mörk
- 155,851
- 29
- 291
- 343
3
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
string dateString = "20100524";
string format = "yyyyMMdd";
result = DateTime.ParseExact(dateString, format, provider);

Murph
- 9,985
- 2
- 26
- 41

CARLOS LOTH
- 4,675
- 3
- 38
- 44
-
Of course, DateTime.Parse(string stringToParse); will work. http://msdn.microsoft.com/en-us/library/1k1skd40.aspx – Julius F May 25 '10 at 06:53
-
Looked promising but it faults out saying that it doesnt recognize it as a valid dateTime – Jake Sankey May 25 '10 at 06:53
-
1Actually for custom date formats like yours, it is necessary to use ParseExact. – CARLOS LOTH May 25 '10 at 06:55
-
Just tested that code and, once I'd defined types for dateString and format (I've edited the answer to include), and it worked exactly as required - which is pretty much what one would expect since its right. If you're still getting an error then its likely that either a) you've not got the format string right (its case sensitive) or b) you're not giving it a valid date. – Murph May 25 '10 at 07:05
3
DateTime.ParseExact("20100524", "yyyyMMdd", Thread.CurrentThread.CurrentCulture);

Oscar Cabrero
- 4,168
- 8
- 29
- 49
-
1that line works but hey there are better solutions here than mine no need to down vote – Oscar Cabrero May 25 '10 at 07:49