Edword
Edword

Reputation: 78

Parsing non-standard string date to DateTime (ParseExact won't work)

I'm working on a C#-WPF parser that read lines from a document and creates objects with several fields, including a "Date added" field. Problem: the date is in a non-standard Spanish format, and I am not able to make DateTime.ParseExact work, as my research suggested. This is the code:

        string input = dateAddedStringSPA;  //domingo 2 septiembre 2012, 23:54:20
        string format = "dddd dd MMMM yyy, HH:mm:ss";

        CultureInfo cultureInfo = new CultureInfo("es-ES");
        DateTime dateAddedSPA;

        try
        {
            dateAddedSPA = DateTime.ParseExact(input, format, cultureInfo);                
            if (dateAddedSPA == DateTime.MinValue) 
            {
                clipping.DateAdded = DateTime.Now; /*Added this conditional workaround to avoid an exception if parsing fails (and always fails). While this doesn't work every object will have the same date: current. */
            }

            else
            {
                clipping.DateAdded = dateAddedSPA;
            }             
        }

        catch (Exception)
        {
            throw new Exception("Error encountered while adding date.");
        }              

The comment that you can see by the side of input is the actual string format, which looks like that. "format" is my attempt to get DateTime to understand it, I also tried removing the comma after the year, still didn't work. I'm not sure if it's the culture the one causing the problems, but I'm afraid my expertise isn't enough yet to know. Thing is, parsing fails and I get the date set to 1/1/0001 12:00:00 AM. Any hint that what could be happening here?

Thanks in advance.

Upvotes: 0

Views: 407

Answers (1)

Alexander Bell
Alexander Bell

Reputation: 7918

To make the solution more "universal" you can specify multiple formats and use TryParseExact() .NET/C# method as shown in the following demo sample code snippet:

CultureInfo cultureInfo = new CultureInfo("es-ES");
string[] formats ={"dddd d MMMM yyy, HH:mm:ss", "dddd d MMMM yyy, HH:mm:ss"};

string input = "domingo 2 septiembre 2012, 23:54:20";
DateTime dt;
if (DateTime.TryParseExact(input, formats, cultureInfo, DateTimeStyles.None, out dt));
{
    if (dt<DateTime.Now)
    Console.WriteLine("OK");
    Console.ReadKey();
}

Hope this may help.

Upvotes: 2

Related Questions