Bart
Bart

Reputation: 4920

String to Date parsing in C#?

I have a data string 'yyyymmddhhmmss' example: '20101001151014', how Do I parse this to date in C#?

Upvotes: 2

Views: 1608

Answers (4)

Raj
Raj

Reputation: 1770

Use the DateTime.ParseExact method.

Upvotes: 2

Yogesh
Yogesh

Reputation: 14608

public DateTime ShortDateStringToDate(string dateText)
{
    if (dateText == null)
        return DateTime.MinValue;

    if (dateText.Length != 14)
        throw new ArgumentException();

    string dateFormatString = "yyyyMMddHHmmss";
    return DateTime.ParseExact(dateText, dateFormatString, CultureInfo.InvariantCulture);
}

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062502

DateTime when = DateTime.ParseExact("20101001151014", "yyyyMMddHHmmss",
    CultureInfo.InvariantCulture);

Points to note: 24-hour hour is HH; 2-digit month is MM

Upvotes: 7

anishMarokey
anishMarokey

Reputation: 11397

DateTime.ParseExact you can use and parse it

  DateTime dt = DateTime.ParseExact("20101001151014", "yyyyMMddHHmmss", CultureInfo.InvariantCulture);

Upvotes: 0

Related Questions