Parse DateTime in c# from strange format

Grant picture Grant · Feb 10, 2010 · Viewed 29.6k times · Source

if i have a datetime string in a weird format, such as YYYY##MM##DD HH**M**SS, how can i create a new datetime object base on that? i have read something about the datetimeformatinfoclass but not sure how to get it working..

Answer

Jon Skeet picture Jon Skeet · Feb 10, 2010

You can use DateTime.ParseExact, or DateTime.TryParseExact for data which you're not confident in. For example:

using System;

class Test
{
    static void Main()
    {
        string formatString = "yyyy'##'MM'##'dd' 'HH'*'mm'*'ss";
        string sampleData = "2010##02##10 07*22*15";
        Console.WriteLine(DateTime.ParseExact(sampleData,
                                              formatString,
                                              null));
    }
}

The quotes in the format string aren't strictly necessary - this will work too:

string formatString = "yyyy##MM##dd HH*mm*ss";

However, using the quotes means you're being explicit that the characters between the quotes are to be used literally, and not understood as pattern characters - so if you changed "#" to "/" the version using quotes would definitely use "/" whereas the version without would use a culture-specific value.

The null in the call to ParseExact means "use the current culture" - in this case it's unlikely to make much difference, but a commonly useful alternative is CultureInfo.InvariantCulture.

It's unfortunate that there's no way of getting the BCL to parse the format string and retain the information; my own Noda Time project rectifies this situation, and I'm hoping it'll make parsing and formatting a lot faster - but it's far from production-ready at the moment.