3

I have a string 20100524 (2010 05 24) and I would like to parse it as an actual date format.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Jake Sankey
  • 4,977
  • 12
  • 39
  • 53

4 Answers4

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
6

DateTime.Parse and Datetime.ParseExact are your friends.

Ovidiu Pacurar
  • 8,173
  • 2
  • 30
  • 36
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
  • 1
    Actually 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