Parse DateTime in c# from strange format

30,110

Solution 1

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.

Solution 2

You can use DateTime.ParseExact method and pass the format you need.

Share:
30,110
Grant
Author by

Grant

Updated on March 03, 2020

Comments

  • Grant
    Grant about 4 years

    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..

  • Admin
    Admin about 14 years
    this is the most efficient way to parse a string to DateTime. parsing with .Parse() and .TryParse() without format info is f..king damn slow!
  • Tanzelax
    Tanzelax about 14 years
    msdn.microsoft.com/en-us/library/8kb3ddd4.aspx has the relevant parsing, if you're providing your own formatString