Jake Sankey
Jake Sankey

Reputation: 5137

Format string as date

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

Upvotes: 3

Views: 413

Answers (4)

CARLOS LOTH
CARLOS LOTH

Reputation: 4745

DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;

string dateString = "20100524";
string format = "yyyyMMdd";
result = DateTime.ParseExact(dateString, format, provider);

Upvotes: 3

Oscar Cabrero
Oscar Cabrero

Reputation: 4169

DateTime.ParseExact("20100524", "yyyyMMdd", Thread.CurrentThread.CurrentCulture);

Upvotes: 3

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

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
}

Upvotes: 16

Ovidiu Pacurar
Ovidiu Pacurar

Reputation: 8209

DateTime.Parse and Datetime.ParseExact are your friends.

Upvotes: 6

Related Questions